babylon.2.2.max.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907
  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.scale = function (scale) {
  56. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  57. };
  58. Color3.prototype.scaleToRef = function (scale, result) {
  59. result.r = this.r * scale;
  60. result.g = this.g * scale;
  61. result.b = this.b * scale;
  62. return this;
  63. };
  64. Color3.prototype.add = function (otherColor) {
  65. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  66. };
  67. Color3.prototype.addToRef = function (otherColor, result) {
  68. result.r = this.r + otherColor.r;
  69. result.g = this.g + otherColor.g;
  70. result.b = this.b + otherColor.b;
  71. return this;
  72. };
  73. Color3.prototype.subtract = function (otherColor) {
  74. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  75. };
  76. Color3.prototype.subtractToRef = function (otherColor, result) {
  77. result.r = this.r - otherColor.r;
  78. result.g = this.g - otherColor.g;
  79. result.b = this.b - otherColor.b;
  80. return this;
  81. };
  82. Color3.prototype.clone = function () {
  83. return new Color3(this.r, this.g, this.b);
  84. };
  85. Color3.prototype.copyFrom = function (source) {
  86. this.r = source.r;
  87. this.g = source.g;
  88. this.b = source.b;
  89. return this;
  90. };
  91. Color3.prototype.copyFromFloats = function (r, g, b) {
  92. this.r = r;
  93. this.g = g;
  94. this.b = b;
  95. return this;
  96. };
  97. // Statics
  98. Color3.FromArray = function (array, offset) {
  99. if (offset === void 0) { offset = 0; }
  100. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  101. };
  102. Color3.FromInts = function (r, g, b) {
  103. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  104. };
  105. Color3.Lerp = function (start, end, amount) {
  106. var r = start.r + ((end.r - start.r) * amount);
  107. var g = start.g + ((end.g - start.g) * amount);
  108. var b = start.b + ((end.b - start.b) * amount);
  109. return new Color3(r, g, b);
  110. };
  111. Color3.Red = function () { return new Color3(1, 0, 0); };
  112. Color3.Green = function () { return new Color3(0, 1, 0); };
  113. Color3.Blue = function () { return new Color3(0, 0, 1); };
  114. Color3.Black = function () { return new Color3(0, 0, 0); };
  115. Color3.White = function () { return new Color3(1, 1, 1); };
  116. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  117. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  118. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  119. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  120. return Color3;
  121. })();
  122. BABYLON.Color3 = Color3;
  123. var Color4 = (function () {
  124. function Color4(r, g, b, a) {
  125. this.r = r;
  126. this.g = g;
  127. this.b = b;
  128. this.a = a;
  129. }
  130. // Operators
  131. Color4.prototype.addInPlace = function (right) {
  132. this.r += right.r;
  133. this.g += right.g;
  134. this.b += right.b;
  135. this.a += right.a;
  136. return this;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. return this;
  152. };
  153. Color4.prototype.add = function (right) {
  154. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  155. };
  156. Color4.prototype.subtract = function (right) {
  157. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  158. };
  159. Color4.prototype.subtractToRef = function (right, result) {
  160. result.r = this.r - right.r;
  161. result.g = this.g - right.g;
  162. result.b = this.b - right.b;
  163. result.a = this.a - right.a;
  164. return this;
  165. };
  166. Color4.prototype.scale = function (scale) {
  167. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  168. };
  169. Color4.prototype.scaleToRef = function (scale, result) {
  170. result.r = this.r * scale;
  171. result.g = this.g * scale;
  172. result.b = this.b * scale;
  173. result.a = this.a * scale;
  174. return this;
  175. };
  176. Color4.prototype.toString = function () {
  177. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  178. };
  179. Color4.prototype.clone = function () {
  180. return new Color4(this.r, this.g, this.b, this.a);
  181. };
  182. Color4.prototype.copyFrom = function (source) {
  183. this.r = source.r;
  184. this.g = source.g;
  185. this.b = source.b;
  186. this.a = source.a;
  187. return this;
  188. };
  189. // Statics
  190. Color4.Lerp = function (left, right, amount) {
  191. var result = new Color4(0, 0, 0, 0);
  192. Color4.LerpToRef(left, right, amount, result);
  193. return result;
  194. };
  195. Color4.LerpToRef = function (left, right, amount, result) {
  196. result.r = left.r + (right.r - left.r) * amount;
  197. result.g = left.g + (right.g - left.g) * amount;
  198. result.b = left.b + (right.b - left.b) * amount;
  199. result.a = left.a + (right.a - left.a) * amount;
  200. };
  201. Color4.FromArray = function (array, offset) {
  202. if (offset === void 0) { offset = 0; }
  203. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  204. };
  205. Color4.FromInts = function (r, g, b, a) {
  206. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  207. };
  208. return Color4;
  209. })();
  210. BABYLON.Color4 = Color4;
  211. var Vector2 = (function () {
  212. function Vector2(x, y) {
  213. this.x = x;
  214. this.y = y;
  215. }
  216. Vector2.prototype.toString = function () {
  217. return "{X: " + this.x + " Y:" + this.y + "}";
  218. };
  219. // Operators
  220. Vector2.prototype.toArray = function (array, index) {
  221. if (index === void 0) { index = 0; }
  222. array[index] = this.x;
  223. array[index + 1] = this.y;
  224. return this;
  225. };
  226. Vector2.prototype.asArray = function () {
  227. var result = [];
  228. this.toArray(result, 0);
  229. return result;
  230. };
  231. Vector2.prototype.copyFrom = function (source) {
  232. this.x = source.x;
  233. this.y = source.y;
  234. return this;
  235. };
  236. Vector2.prototype.copyFromFloats = function (x, y) {
  237. this.x = x;
  238. this.y = y;
  239. return this;
  240. };
  241. Vector2.prototype.add = function (otherVector) {
  242. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  243. };
  244. Vector2.prototype.addVector3 = function (otherVector) {
  245. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  246. };
  247. Vector2.prototype.subtract = function (otherVector) {
  248. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  249. };
  250. Vector2.prototype.subtractInPlace = function (otherVector) {
  251. this.x -= otherVector.x;
  252. this.y -= otherVector.y;
  253. return this;
  254. };
  255. Vector2.prototype.multiplyInPlace = function (otherVector) {
  256. this.x *= otherVector.x;
  257. this.y *= otherVector.y;
  258. return this;
  259. };
  260. Vector2.prototype.multiply = function (otherVector) {
  261. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  262. };
  263. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  264. result.x = this.x * otherVector.x;
  265. result.y = this.y * otherVector.y;
  266. return this;
  267. };
  268. Vector2.prototype.multiplyByFloats = function (x, y) {
  269. return new Vector2(this.x * x, this.y * y);
  270. };
  271. Vector2.prototype.divide = function (otherVector) {
  272. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  273. };
  274. Vector2.prototype.divideToRef = function (otherVector, result) {
  275. result.x = this.x / otherVector.x;
  276. result.y = this.y / otherVector.y;
  277. return this;
  278. };
  279. Vector2.prototype.negate = function () {
  280. return new Vector2(-this.x, -this.y);
  281. };
  282. Vector2.prototype.scaleInPlace = function (scale) {
  283. this.x *= scale;
  284. this.y *= scale;
  285. return this;
  286. };
  287. Vector2.prototype.scale = function (scale) {
  288. return new Vector2(this.x * scale, this.y * scale);
  289. };
  290. Vector2.prototype.equals = function (otherVector) {
  291. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  292. };
  293. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  294. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  295. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  296. };
  297. // Properties
  298. Vector2.prototype.length = function () {
  299. return Math.sqrt(this.x * this.x + this.y * this.y);
  300. };
  301. Vector2.prototype.lengthSquared = function () {
  302. return (this.x * this.x + this.y * this.y);
  303. };
  304. // Methods
  305. Vector2.prototype.normalize = function () {
  306. var len = this.length();
  307. if (len === 0)
  308. return this;
  309. var num = 1.0 / len;
  310. this.x *= num;
  311. this.y *= num;
  312. return this;
  313. };
  314. Vector2.prototype.clone = function () {
  315. return new Vector2(this.x, this.y);
  316. };
  317. // Statics
  318. Vector2.Zero = function () {
  319. return new Vector2(0, 0);
  320. };
  321. Vector2.FromArray = function (array, offset) {
  322. if (offset === void 0) { offset = 0; }
  323. return new Vector2(array[offset], array[offset + 1]);
  324. };
  325. Vector2.FromArrayToRef = function (array, offset, result) {
  326. result.x = array[offset];
  327. result.y = array[offset + 1];
  328. };
  329. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  330. var squared = amount * amount;
  331. var cubed = amount * squared;
  332. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  333. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  334. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  335. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  336. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  337. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  338. return new Vector2(x, y);
  339. };
  340. Vector2.Clamp = function (value, min, max) {
  341. var x = value.x;
  342. x = (x > max.x) ? max.x : x;
  343. x = (x < min.x) ? min.x : x;
  344. var y = value.y;
  345. y = (y > max.y) ? max.y : y;
  346. y = (y < min.y) ? min.y : y;
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  350. var squared = amount * amount;
  351. var cubed = amount * squared;
  352. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  353. var part2 = (-2.0 * cubed) + (3.0 * squared);
  354. var part3 = (cubed - (2.0 * squared)) + amount;
  355. var part4 = cubed - squared;
  356. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  357. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  358. return new Vector2(x, y);
  359. };
  360. Vector2.Lerp = function (start, end, amount) {
  361. var x = start.x + ((end.x - start.x) * amount);
  362. var y = start.y + ((end.y - start.y) * amount);
  363. return new Vector2(x, y);
  364. };
  365. Vector2.Dot = function (left, right) {
  366. return left.x * right.x + left.y * right.y;
  367. };
  368. Vector2.Normalize = function (vector) {
  369. var newVector = vector.clone();
  370. newVector.normalize();
  371. return newVector;
  372. };
  373. Vector2.Minimize = function (left, right) {
  374. var x = (left.x < right.x) ? left.x : right.x;
  375. var y = (left.y < right.y) ? left.y : right.y;
  376. return new Vector2(x, y);
  377. };
  378. Vector2.Maximize = function (left, right) {
  379. var x = (left.x > right.x) ? left.x : right.x;
  380. var y = (left.y > right.y) ? left.y : right.y;
  381. return new Vector2(x, y);
  382. };
  383. Vector2.Transform = function (vector, transformation) {
  384. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  385. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  386. return new Vector2(x, y);
  387. };
  388. Vector2.Distance = function (value1, value2) {
  389. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  390. };
  391. Vector2.DistanceSquared = function (value1, value2) {
  392. var x = value1.x - value2.x;
  393. var y = value1.y - value2.y;
  394. return (x * x) + (y * y);
  395. };
  396. return Vector2;
  397. })();
  398. BABYLON.Vector2 = Vector2;
  399. var Vector3 = (function () {
  400. function Vector3(x, y, z) {
  401. this.x = x;
  402. this.y = y;
  403. this.z = z;
  404. }
  405. Vector3.prototype.toString = function () {
  406. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  407. };
  408. // Operators
  409. Vector3.prototype.asArray = function () {
  410. var result = [];
  411. this.toArray(result, 0);
  412. return result;
  413. };
  414. Vector3.prototype.toArray = function (array, index) {
  415. if (index === void 0) { index = 0; }
  416. array[index] = this.x;
  417. array[index + 1] = this.y;
  418. array[index + 2] = this.z;
  419. return this;
  420. };
  421. Vector3.prototype.toQuaternion = function () {
  422. var result = new Quaternion(0, 0, 0, 1);
  423. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  424. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  425. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  426. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  427. var cosy = Math.cos(this.y * 0.5);
  428. var siny = Math.sin(this.y * 0.5);
  429. result.x = coszMinusx * siny;
  430. result.y = -sinzMinusx * siny;
  431. result.z = sinxPlusz * cosy;
  432. result.w = cosxPlusz * cosy;
  433. return result;
  434. };
  435. Vector3.prototype.addInPlace = function (otherVector) {
  436. this.x += otherVector.x;
  437. this.y += otherVector.y;
  438. this.z += otherVector.z;
  439. return this;
  440. };
  441. Vector3.prototype.add = function (otherVector) {
  442. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  443. };
  444. Vector3.prototype.addToRef = function (otherVector, result) {
  445. result.x = this.x + otherVector.x;
  446. result.y = this.y + otherVector.y;
  447. result.z = this.z + otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.subtractInPlace = function (otherVector) {
  451. this.x -= otherVector.x;
  452. this.y -= otherVector.y;
  453. this.z -= otherVector.z;
  454. return this;
  455. };
  456. Vector3.prototype.subtract = function (otherVector) {
  457. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  458. };
  459. Vector3.prototype.subtractToRef = function (otherVector, result) {
  460. result.x = this.x - otherVector.x;
  461. result.y = this.y - otherVector.y;
  462. result.z = this.z - otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  466. return new Vector3(this.x - x, this.y - y, this.z - z);
  467. };
  468. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  469. result.x = this.x - x;
  470. result.y = this.y - y;
  471. result.z = this.z - z;
  472. return this;
  473. };
  474. Vector3.prototype.negate = function () {
  475. return new Vector3(-this.x, -this.y, -this.z);
  476. };
  477. Vector3.prototype.scaleInPlace = function (scale) {
  478. this.x *= scale;
  479. this.y *= scale;
  480. this.z *= scale;
  481. return this;
  482. };
  483. Vector3.prototype.scale = function (scale) {
  484. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  485. };
  486. Vector3.prototype.scaleToRef = function (scale, result) {
  487. result.x = this.x * scale;
  488. result.y = this.y * scale;
  489. result.z = this.z * scale;
  490. };
  491. Vector3.prototype.equals = function (otherVector) {
  492. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  493. };
  494. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  495. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  496. 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);
  497. };
  498. Vector3.prototype.equalsToFloats = function (x, y, z) {
  499. return this.x === x && this.y === y && this.z === z;
  500. };
  501. Vector3.prototype.multiplyInPlace = function (otherVector) {
  502. this.x *= otherVector.x;
  503. this.y *= otherVector.y;
  504. this.z *= otherVector.z;
  505. return this;
  506. };
  507. Vector3.prototype.multiply = function (otherVector) {
  508. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  509. };
  510. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  511. result.x = this.x * otherVector.x;
  512. result.y = this.y * otherVector.y;
  513. result.z = this.z * otherVector.z;
  514. return this;
  515. };
  516. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  517. return new Vector3(this.x * x, this.y * y, this.z * z);
  518. };
  519. Vector3.prototype.divide = function (otherVector) {
  520. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  521. };
  522. Vector3.prototype.divideToRef = function (otherVector, result) {
  523. result.x = this.x / otherVector.x;
  524. result.y = this.y / otherVector.y;
  525. result.z = this.z / otherVector.z;
  526. return this;
  527. };
  528. Vector3.prototype.MinimizeInPlace = function (other) {
  529. if (other.x < this.x)
  530. this.x = other.x;
  531. if (other.y < this.y)
  532. this.y = other.y;
  533. if (other.z < this.z)
  534. this.z = other.z;
  535. return this;
  536. };
  537. Vector3.prototype.MaximizeInPlace = function (other) {
  538. if (other.x > this.x)
  539. this.x = other.x;
  540. if (other.y > this.y)
  541. this.y = other.y;
  542. if (other.z > this.z)
  543. this.z = other.z;
  544. return this;
  545. };
  546. // Properties
  547. Vector3.prototype.length = function () {
  548. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  549. };
  550. Vector3.prototype.lengthSquared = function () {
  551. return (this.x * this.x + this.y * this.y + this.z * this.z);
  552. };
  553. // Methods
  554. Vector3.prototype.normalize = function () {
  555. var len = this.length();
  556. if (len === 0 || len === 1.0)
  557. return this;
  558. var num = 1.0 / len;
  559. this.x *= num;
  560. this.y *= num;
  561. this.z *= num;
  562. return this;
  563. };
  564. Vector3.prototype.clone = function () {
  565. return new Vector3(this.x, this.y, this.z);
  566. };
  567. Vector3.prototype.copyFrom = function (source) {
  568. this.x = source.x;
  569. this.y = source.y;
  570. this.z = source.z;
  571. return this;
  572. };
  573. Vector3.prototype.copyFromFloats = function (x, y, z) {
  574. this.x = x;
  575. this.y = y;
  576. this.z = z;
  577. return this;
  578. };
  579. // Statics
  580. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  581. var d0 = Vector3.Dot(vector0, axis) - size;
  582. var d1 = Vector3.Dot(vector1, axis) - size;
  583. var s = d0 / (d0 - d1);
  584. return s;
  585. };
  586. Vector3.FromArray = function (array, offset) {
  587. if (!offset) {
  588. offset = 0;
  589. }
  590. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  591. };
  592. Vector3.FromArrayToRef = function (array, offset, result) {
  593. result.x = array[offset];
  594. result.y = array[offset + 1];
  595. result.z = array[offset + 2];
  596. };
  597. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  598. result.x = array[offset];
  599. result.y = array[offset + 1];
  600. result.z = array[offset + 2];
  601. };
  602. Vector3.FromFloatsToRef = function (x, y, z, result) {
  603. result.x = x;
  604. result.y = y;
  605. result.z = z;
  606. };
  607. Vector3.Zero = function () {
  608. return new Vector3(0, 0, 0);
  609. };
  610. Vector3.Up = function () {
  611. return new Vector3(0, 1.0, 0);
  612. };
  613. Vector3.TransformCoordinates = function (vector, transformation) {
  614. var result = Vector3.Zero();
  615. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  616. return result;
  617. };
  618. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  619. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  620. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  621. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  622. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  623. result.x = x / w;
  624. result.y = y / w;
  625. result.z = z / w;
  626. };
  627. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  628. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  629. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  630. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  631. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  632. result.x = rx / rw;
  633. result.y = ry / rw;
  634. result.z = rz / rw;
  635. };
  636. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  637. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  638. var m0 = SIMD.float32x4.load(transformation.m, 0);
  639. var m1 = SIMD.float32x4.load(transformation.m, 4);
  640. var m2 = SIMD.float32x4.load(transformation.m, 8);
  641. var m3 = SIMD.float32x4.load(transformation.m, 12);
  642. 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));
  643. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  644. SIMD.float32x4.storeXYZ(result._data, 0, r);
  645. };
  646. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  647. var v0 = SIMD.float32x4.splat(x);
  648. var v1 = SIMD.float32x4.splat(y);
  649. var v2 = SIMD.float32x4.splat(z);
  650. var m0 = SIMD.float32x4.load(transformation.m, 0);
  651. var m1 = SIMD.float32x4.load(transformation.m, 4);
  652. var m2 = SIMD.float32x4.load(transformation.m, 8);
  653. var m3 = SIMD.float32x4.load(transformation.m, 12);
  654. 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));
  655. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  656. SIMD.float32x4.storeXYZ(result._data, 0, r);
  657. };
  658. Vector3.TransformNormal = function (vector, transformation) {
  659. var result = Vector3.Zero();
  660. Vector3.TransformNormalToRef(vector, transformation, result);
  661. return result;
  662. };
  663. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  664. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  665. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  666. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  667. };
  668. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  669. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  670. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  671. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  672. };
  673. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  677. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  678. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  679. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  680. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  681. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  682. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  683. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  684. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  685. return new Vector3(x, y, z);
  686. };
  687. Vector3.Clamp = function (value, min, max) {
  688. var x = value.x;
  689. x = (x > max.x) ? max.x : x;
  690. x = (x < min.x) ? min.x : x;
  691. var y = value.y;
  692. y = (y > max.y) ? max.y : y;
  693. y = (y < min.y) ? min.y : y;
  694. var z = value.z;
  695. z = (z > max.z) ? max.z : z;
  696. z = (z < min.z) ? min.z : z;
  697. return new Vector3(x, y, z);
  698. };
  699. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  700. var squared = amount * amount;
  701. var cubed = amount * squared;
  702. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  703. var part2 = (-2.0 * cubed) + (3.0 * squared);
  704. var part3 = (cubed - (2.0 * squared)) + amount;
  705. var part4 = cubed - squared;
  706. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  707. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  708. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  709. return new Vector3(x, y, z);
  710. };
  711. Vector3.Lerp = function (start, end, amount) {
  712. var x = start.x + ((end.x - start.x) * amount);
  713. var y = start.y + ((end.y - start.y) * amount);
  714. var z = start.z + ((end.z - start.z) * amount);
  715. return new Vector3(x, y, z);
  716. };
  717. Vector3.Dot = function (left, right) {
  718. return (left.x * right.x + left.y * right.y + left.z * right.z);
  719. };
  720. Vector3.Cross = function (left, right) {
  721. var result = Vector3.Zero();
  722. Vector3.CrossToRef(left, right, result);
  723. return result;
  724. };
  725. Vector3.CrossToRef = function (left, right, result) {
  726. result.x = left.y * right.z - left.z * right.y;
  727. result.y = left.z * right.x - left.x * right.z;
  728. result.z = left.x * right.y - left.y * right.x;
  729. };
  730. Vector3.Normalize = function (vector) {
  731. var result = Vector3.Zero();
  732. Vector3.NormalizeToRef(vector, result);
  733. return result;
  734. };
  735. Vector3.NormalizeToRef = function (vector, result) {
  736. result.copyFrom(vector);
  737. result.normalize();
  738. };
  739. Vector3.Project = function (vector, world, transform, viewport) {
  740. var cw = viewport.width;
  741. var ch = viewport.height;
  742. var cx = viewport.x;
  743. var cy = viewport.y;
  744. 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);
  745. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  746. return Vector3.TransformCoordinates(vector, finalMatrix);
  747. };
  748. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  749. var matrix = world.multiply(transform);
  750. matrix.invert();
  751. source.x = source.x / viewportWidth * 2 - 1;
  752. source.y = -(source.y / viewportHeight * 2 - 1);
  753. var vector = Vector3.TransformCoordinates(source, matrix);
  754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  755. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  756. vector = vector.scale(1.0 / num);
  757. }
  758. return vector;
  759. };
  760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  761. var matrix = world.multiply(view).multiply(projection);
  762. matrix.invert();
  763. source.x = source.x / viewportWidth * 2 - 1;
  764. source.y = -(source.y / viewportHeight * 2 - 1);
  765. var vector = Vector3.TransformCoordinates(source, matrix);
  766. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  767. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  768. vector = vector.scale(1.0 / num);
  769. }
  770. return vector;
  771. };
  772. Vector3.Minimize = function (left, right) {
  773. var min = left.clone();
  774. min.MinimizeInPlace(right);
  775. return min;
  776. };
  777. Vector3.Maximize = function (left, right) {
  778. var max = left.clone();
  779. max.MaximizeInPlace(right);
  780. return max;
  781. };
  782. Vector3.Distance = function (value1, value2) {
  783. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  784. };
  785. Vector3.DistanceSquared = function (value1, value2) {
  786. var x = value1.x - value2.x;
  787. var y = value1.y - value2.y;
  788. var z = value1.z - value2.z;
  789. return (x * x) + (y * y) + (z * z);
  790. };
  791. Vector3.Center = function (value1, value2) {
  792. var center = value1.add(value2);
  793. center.scaleInPlace(0.5);
  794. return center;
  795. };
  796. /**
  797. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  798. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  799. * to something in order to rotate it from its local system to the given target system.
  800. */
  801. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  802. var u = Vector3.Normalize(axis1);
  803. var v = Vector3.Normalize(axis2);
  804. var w = Vector3.Normalize(axis3);
  805. // world axis
  806. var X = Axis.X;
  807. var Y = Axis.Y;
  808. var Z = Axis.Z;
  809. // equation unknowns and vars
  810. var yaw = 0.0;
  811. var pitch = 0.0;
  812. var roll = 0.0;
  813. var x = 0.0;
  814. var y = 0.0;
  815. var z = 0.0;
  816. var t = 0.0;
  817. var sign = -1.0;
  818. var pi = Math.PI;
  819. var nbRevert = 0;
  820. var cross;
  821. var dot = 0.0;
  822. // step 1 : rotation around w
  823. // Rv3(u) = u1, and u1 belongs to plane xOz
  824. // Rv3(w) = w1 = w invariant
  825. var u1;
  826. var v1;
  827. if (w.z == 0) {
  828. z = 1.0;
  829. }
  830. else if (w.x == 0) {
  831. x = 1.0;
  832. }
  833. else {
  834. t = w.z / w.x;
  835. x = -t * Math.sqrt(1 / (1 + t * t));
  836. z = Math.sqrt(1 / (1 + t * t));
  837. }
  838. u1 = new Vector3(x, y, z);
  839. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  840. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  841. if (Vector3.Dot(w, cross) < 0) {
  842. sign = 1;
  843. }
  844. dot = Vector3.Dot(u, u1);
  845. roll = Math.acos(dot) * sign;
  846. if (Vector3.Dot(u1, X) < 0) {
  847. roll = Math.PI + roll;
  848. u1 = u1.scaleInPlace(-1);
  849. v1 = v1.scaleInPlace(-1);
  850. nbRevert++;
  851. }
  852. // step 2 : rotate around u1
  853. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  854. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  855. var w2;
  856. var v2;
  857. x = 0.0;
  858. y = 0.0;
  859. z = 0.0;
  860. sign = -1;
  861. if (w.z == 0) {
  862. x = 1.0;
  863. }
  864. else {
  865. t = u1.z / u1.x;
  866. x = -t * Math.sqrt(1 / (1 + t * t));
  867. z = Math.sqrt(1 / (1 + t * t));
  868. }
  869. w2 = new Vector3(x, y, z);
  870. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  871. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  872. if (Vector3.Dot(u1, cross) < 0) {
  873. sign = 1;
  874. }
  875. dot = Vector3.Dot(w, w2);
  876. pitch = Math.acos(dot) * sign;
  877. if (Vector3.Dot(v2, Y) < 0) {
  878. pitch = Math.PI + pitch;
  879. v2 = v2.scaleInPlace(-1);
  880. w2 = w2.scaleInPlace(-1);
  881. nbRevert++;
  882. }
  883. // step 3 : rotate around v2
  884. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  885. sign = -1;
  886. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  887. if (Vector3.Dot(cross, Y) < 0) {
  888. sign = 1;
  889. }
  890. dot = Vector3.Dot(u1, X);
  891. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  892. if (dot < 0 && nbRevert < 2) {
  893. yaw = Math.PI + yaw;
  894. }
  895. return new Vector3(pitch, yaw, roll);
  896. };
  897. return Vector3;
  898. })();
  899. BABYLON.Vector3 = Vector3;
  900. //Vector4 class created for EulerAngle class conversion to Quaternion
  901. var Vector4 = (function () {
  902. function Vector4(x, y, z, w) {
  903. this.x = x;
  904. this.y = y;
  905. this.z = z;
  906. this.w = w;
  907. }
  908. Vector4.prototype.toString = function () {
  909. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  910. };
  911. // Operators
  912. Vector4.prototype.asArray = function () {
  913. var result = [];
  914. this.toArray(result, 0);
  915. return result;
  916. };
  917. Vector4.prototype.toArray = function (array, index) {
  918. if (index === undefined) {
  919. index = 0;
  920. }
  921. array[index] = this.x;
  922. array[index + 1] = this.y;
  923. array[index + 2] = this.z;
  924. array[index + 3] = this.w;
  925. return this;
  926. };
  927. Vector4.prototype.addInPlace = function (otherVector) {
  928. this.x += otherVector.x;
  929. this.y += otherVector.y;
  930. this.z += otherVector.z;
  931. this.w += otherVector.w;
  932. return this;
  933. };
  934. Vector4.prototype.add = function (otherVector) {
  935. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  936. };
  937. Vector4.prototype.addToRef = function (otherVector, result) {
  938. result.x = this.x + otherVector.x;
  939. result.y = this.y + otherVector.y;
  940. result.z = this.z + otherVector.z;
  941. result.w = this.w + otherVector.w;
  942. return this;
  943. };
  944. Vector4.prototype.subtractInPlace = function (otherVector) {
  945. this.x -= otherVector.x;
  946. this.y -= otherVector.y;
  947. this.z -= otherVector.z;
  948. this.w -= otherVector.w;
  949. return this;
  950. };
  951. Vector4.prototype.subtract = function (otherVector) {
  952. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  953. };
  954. Vector4.prototype.subtractToRef = function (otherVector, result) {
  955. result.x = this.x - otherVector.x;
  956. result.y = this.y - otherVector.y;
  957. result.z = this.z - otherVector.z;
  958. result.w = this.w - otherVector.w;
  959. return this;
  960. };
  961. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  962. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  963. };
  964. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  965. result.x = this.x - x;
  966. result.y = this.y - y;
  967. result.z = this.z - z;
  968. result.w = this.w - w;
  969. return this;
  970. };
  971. Vector4.prototype.negate = function () {
  972. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  973. };
  974. Vector4.prototype.scaleInPlace = function (scale) {
  975. this.x *= scale;
  976. this.y *= scale;
  977. this.z *= scale;
  978. this.w *= scale;
  979. return this;
  980. };
  981. Vector4.prototype.scale = function (scale) {
  982. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  983. };
  984. Vector4.prototype.scaleToRef = function (scale, result) {
  985. result.x = this.x * scale;
  986. result.y = this.y * scale;
  987. result.z = this.z * scale;
  988. result.w = this.w * scale;
  989. };
  990. Vector4.prototype.equals = function (otherVector) {
  991. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  992. };
  993. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  994. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  995. return otherVector
  996. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  997. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  998. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  999. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1000. };
  1001. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1002. return this.x === x && this.y === y && this.z === z && this.w === w;
  1003. };
  1004. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1005. this.x *= otherVector.x;
  1006. this.y *= otherVector.y;
  1007. this.z *= otherVector.z;
  1008. this.w *= otherVector.w;
  1009. return this;
  1010. };
  1011. Vector4.prototype.multiply = function (otherVector) {
  1012. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1013. };
  1014. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1015. result.x = this.x * otherVector.x;
  1016. result.y = this.y * otherVector.y;
  1017. result.z = this.z * otherVector.z;
  1018. result.w = this.w * otherVector.w;
  1019. return this;
  1020. };
  1021. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1022. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1023. };
  1024. Vector4.prototype.divide = function (otherVector) {
  1025. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1026. };
  1027. Vector4.prototype.divideToRef = function (otherVector, result) {
  1028. result.x = this.x / otherVector.x;
  1029. result.y = this.y / otherVector.y;
  1030. result.z = this.z / otherVector.z;
  1031. result.w = this.w / otherVector.w;
  1032. return this;
  1033. };
  1034. Vector4.prototype.MinimizeInPlace = function (other) {
  1035. if (other.x < this.x)
  1036. this.x = other.x;
  1037. if (other.y < this.y)
  1038. this.y = other.y;
  1039. if (other.z < this.z)
  1040. this.z = other.z;
  1041. if (other.w < this.w)
  1042. this.w = other.w;
  1043. return this;
  1044. };
  1045. Vector4.prototype.MaximizeInPlace = function (other) {
  1046. if (other.x > this.x)
  1047. this.x = other.x;
  1048. if (other.y > this.y)
  1049. this.y = other.y;
  1050. if (other.z > this.z)
  1051. this.z = other.z;
  1052. if (other.w > this.w)
  1053. this.w = other.w;
  1054. return this;
  1055. };
  1056. // Properties
  1057. Vector4.prototype.length = function () {
  1058. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1059. };
  1060. Vector4.prototype.lengthSquared = function () {
  1061. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1062. };
  1063. // Methods
  1064. Vector4.prototype.normalize = function () {
  1065. var len = this.length();
  1066. if (len === 0)
  1067. return this;
  1068. var num = 1.0 / len;
  1069. this.x *= num;
  1070. this.y *= num;
  1071. this.z *= num;
  1072. this.w *= num;
  1073. return this;
  1074. };
  1075. Vector4.prototype.clone = function () {
  1076. return new Vector4(this.x, this.y, this.z, this.w);
  1077. };
  1078. Vector4.prototype.copyFrom = function (source) {
  1079. this.x = source.x;
  1080. this.y = source.y;
  1081. this.z = source.z;
  1082. this.w = source.w;
  1083. return this;
  1084. };
  1085. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1086. this.x = x;
  1087. this.y = y;
  1088. this.z = z;
  1089. this.w = w;
  1090. return this;
  1091. };
  1092. // Statics
  1093. Vector4.FromArray = function (array, offset) {
  1094. if (!offset) {
  1095. offset = 0;
  1096. }
  1097. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1098. };
  1099. Vector4.FromArrayToRef = function (array, offset, result) {
  1100. result.x = array[offset];
  1101. result.y = array[offset + 1];
  1102. result.z = array[offset + 2];
  1103. result.w = array[offset + 3];
  1104. };
  1105. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1106. result.x = array[offset];
  1107. result.y = array[offset + 1];
  1108. result.z = array[offset + 2];
  1109. result.w = array[offset + 3];
  1110. };
  1111. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1112. result.x = x;
  1113. result.y = y;
  1114. result.z = z;
  1115. result.w = w;
  1116. };
  1117. Vector4.Zero = function () {
  1118. return new Vector4(0, 0, 0, 0);
  1119. };
  1120. Vector4.Normalize = function (vector) {
  1121. var result = Vector4.Zero();
  1122. Vector4.NormalizeToRef(vector, result);
  1123. return result;
  1124. };
  1125. Vector4.NormalizeToRef = function (vector, result) {
  1126. result.copyFrom(vector);
  1127. result.normalize();
  1128. };
  1129. Vector4.Minimize = function (left, right) {
  1130. var min = left.clone();
  1131. min.MinimizeInPlace(right);
  1132. return min;
  1133. };
  1134. Vector4.Maximize = function (left, right) {
  1135. var max = left.clone();
  1136. max.MaximizeInPlace(right);
  1137. return max;
  1138. };
  1139. Vector4.Distance = function (value1, value2) {
  1140. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1141. };
  1142. Vector4.DistanceSquared = function (value1, value2) {
  1143. var x = value1.x - value2.x;
  1144. var y = value1.y - value2.y;
  1145. var z = value1.z - value2.z;
  1146. var w = value1.w - value2.w;
  1147. return (x * x) + (y * y) + (z * z) + (w * w);
  1148. };
  1149. Vector4.Center = function (value1, value2) {
  1150. var center = value1.add(value2);
  1151. center.scaleInPlace(0.5);
  1152. return center;
  1153. };
  1154. return Vector4;
  1155. })();
  1156. BABYLON.Vector4 = Vector4;
  1157. var Quaternion = (function () {
  1158. function Quaternion(x, y, z, w) {
  1159. if (x === void 0) { x = 0; }
  1160. if (y === void 0) { y = 0; }
  1161. if (z === void 0) { z = 0; }
  1162. if (w === void 0) { w = 1; }
  1163. this.x = x;
  1164. this.y = y;
  1165. this.z = z;
  1166. this.w = w;
  1167. }
  1168. Quaternion.prototype.toString = function () {
  1169. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1170. };
  1171. Quaternion.prototype.asArray = function () {
  1172. return [this.x, this.y, this.z, this.w];
  1173. };
  1174. Quaternion.prototype.equals = function (otherQuaternion) {
  1175. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1176. };
  1177. Quaternion.prototype.clone = function () {
  1178. return new Quaternion(this.x, this.y, this.z, this.w);
  1179. };
  1180. Quaternion.prototype.copyFrom = function (other) {
  1181. this.x = other.x;
  1182. this.y = other.y;
  1183. this.z = other.z;
  1184. this.w = other.w;
  1185. return this;
  1186. };
  1187. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1188. this.x = x;
  1189. this.y = y;
  1190. this.z = z;
  1191. this.w = w;
  1192. return this;
  1193. };
  1194. Quaternion.prototype.add = function (other) {
  1195. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1196. };
  1197. Quaternion.prototype.subtract = function (other) {
  1198. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1199. };
  1200. Quaternion.prototype.scale = function (value) {
  1201. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1202. };
  1203. Quaternion.prototype.multiply = function (q1) {
  1204. var result = new Quaternion(0, 0, 0, 1.0);
  1205. this.multiplyToRef(q1, result);
  1206. return result;
  1207. };
  1208. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1209. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1210. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1211. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1212. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1213. result.copyFromFloats(x, y, z, w);
  1214. return this;
  1215. };
  1216. Quaternion.prototype.length = function () {
  1217. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1218. };
  1219. Quaternion.prototype.normalize = function () {
  1220. var length = 1.0 / this.length();
  1221. this.x *= length;
  1222. this.y *= length;
  1223. this.z *= length;
  1224. this.w *= length;
  1225. return this;
  1226. };
  1227. Quaternion.prototype.toEulerAngles = function () {
  1228. var result = Vector3.Zero();
  1229. this.toEulerAnglesToRef(result);
  1230. return result;
  1231. };
  1232. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1233. //result is an EulerAngles in the in the z-x-z convention
  1234. var qx = this.x;
  1235. var qy = this.y;
  1236. var qz = this.z;
  1237. var qw = this.w;
  1238. var qxy = qx * qy;
  1239. var qxz = qx * qz;
  1240. var qwy = qw * qy;
  1241. var qwz = qw * qz;
  1242. var qwx = qw * qx;
  1243. var qyz = qy * qz;
  1244. var sqx = qx * qx;
  1245. var sqy = qy * qy;
  1246. var determinant = sqx + sqy;
  1247. if (determinant !== 0.000 && determinant !== 1.000) {
  1248. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1249. result.y = Math.acos(1 - 2 * determinant);
  1250. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1251. }
  1252. else {
  1253. if (determinant === 0.0) {
  1254. result.x = 0.0;
  1255. result.y = 0.0;
  1256. 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)
  1257. }
  1258. else {
  1259. 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)
  1260. result.y = Math.PI;
  1261. result.z = 0.0;
  1262. }
  1263. }
  1264. return this;
  1265. };
  1266. Quaternion.prototype.toRotationMatrix = function (result) {
  1267. var xx = this.x * this.x;
  1268. var yy = this.y * this.y;
  1269. var zz = this.z * this.z;
  1270. var xy = this.x * this.y;
  1271. var zw = this.z * this.w;
  1272. var zx = this.z * this.x;
  1273. var yw = this.y * this.w;
  1274. var yz = this.y * this.z;
  1275. var xw = this.x * this.w;
  1276. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1277. result.m[1] = 2.0 * (xy + zw);
  1278. result.m[2] = 2.0 * (zx - yw);
  1279. result.m[3] = 0;
  1280. result.m[4] = 2.0 * (xy - zw);
  1281. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1282. result.m[6] = 2.0 * (yz + xw);
  1283. result.m[7] = 0;
  1284. result.m[8] = 2.0 * (zx + yw);
  1285. result.m[9] = 2.0 * (yz - xw);
  1286. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1287. result.m[11] = 0;
  1288. result.m[12] = 0;
  1289. result.m[13] = 0;
  1290. result.m[14] = 0;
  1291. result.m[15] = 1.0;
  1292. return this;
  1293. };
  1294. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1295. Quaternion.FromRotationMatrixToRef(matrix, this);
  1296. return this;
  1297. };
  1298. // Statics
  1299. Quaternion.FromRotationMatrix = function (matrix) {
  1300. var result = new Quaternion();
  1301. Quaternion.FromRotationMatrixToRef(matrix, result);
  1302. return result;
  1303. };
  1304. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1305. var data = matrix.m;
  1306. var m11 = data[0], m12 = data[4], m13 = data[8];
  1307. var m21 = data[1], m22 = data[5], m23 = data[9];
  1308. var m31 = data[2], m32 = data[6], m33 = data[10];
  1309. var trace = m11 + m22 + m33;
  1310. var s;
  1311. if (trace > 0) {
  1312. s = 0.5 / Math.sqrt(trace + 1.0);
  1313. result.w = 0.25 / s;
  1314. result.x = (m32 - m23) * s;
  1315. result.y = (m13 - m31) * s;
  1316. result.z = (m21 - m12) * s;
  1317. }
  1318. else if (m11 > m22 && m11 > m33) {
  1319. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1320. result.w = (m32 - m23) / s;
  1321. result.x = 0.25 * s;
  1322. result.y = (m12 + m21) / s;
  1323. result.z = (m13 + m31) / s;
  1324. }
  1325. else if (m22 > m33) {
  1326. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1327. result.w = (m13 - m31) / s;
  1328. result.x = (m12 + m21) / s;
  1329. result.y = 0.25 * s;
  1330. result.z = (m23 + m32) / s;
  1331. }
  1332. else {
  1333. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1334. result.w = (m21 - m12) / s;
  1335. result.x = (m13 + m31) / s;
  1336. result.y = (m23 + m32) / s;
  1337. result.z = 0.25 * s;
  1338. }
  1339. };
  1340. Quaternion.Inverse = function (q) {
  1341. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1342. };
  1343. Quaternion.Identity = function () {
  1344. return new Quaternion(0, 0, 0, 1);
  1345. };
  1346. Quaternion.RotationAxis = function (axis, angle) {
  1347. var result = new Quaternion();
  1348. var sin = Math.sin(angle / 2);
  1349. result.w = Math.cos(angle / 2);
  1350. result.x = axis.x * sin;
  1351. result.y = axis.y * sin;
  1352. result.z = axis.z * sin;
  1353. return result;
  1354. };
  1355. Quaternion.FromArray = function (array, offset) {
  1356. if (!offset) {
  1357. offset = 0;
  1358. }
  1359. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1360. };
  1361. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1362. var result = new Quaternion();
  1363. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1364. return result;
  1365. };
  1366. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1367. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1368. var halfRoll = roll * 0.5;
  1369. var halfPitch = pitch * 0.5;
  1370. var halfYaw = yaw * 0.5;
  1371. var sinRoll = Math.sin(halfRoll);
  1372. var cosRoll = Math.cos(halfRoll);
  1373. var sinPitch = Math.sin(halfPitch);
  1374. var cosPitch = Math.cos(halfPitch);
  1375. var sinYaw = Math.sin(halfYaw);
  1376. var cosYaw = Math.cos(halfYaw);
  1377. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1378. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1379. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1380. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1381. };
  1382. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1383. var result = new Quaternion();
  1384. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1385. return result;
  1386. };
  1387. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1388. // Produces a quaternion from Euler angles in the z-x-z orientation
  1389. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1390. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1391. var halfBeta = beta * 0.5;
  1392. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1393. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1394. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1395. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1396. };
  1397. Quaternion.Slerp = function (left, right, amount) {
  1398. var num2;
  1399. var num3;
  1400. var num = amount;
  1401. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1402. var flag = false;
  1403. if (num4 < 0) {
  1404. flag = true;
  1405. num4 = -num4;
  1406. }
  1407. if (num4 > 0.999999) {
  1408. num3 = 1 - num;
  1409. num2 = flag ? -num : num;
  1410. }
  1411. else {
  1412. var num5 = Math.acos(num4);
  1413. var num6 = (1.0 / Math.sin(num5));
  1414. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1415. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1416. }
  1417. 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));
  1418. };
  1419. return Quaternion;
  1420. })();
  1421. BABYLON.Quaternion = Quaternion;
  1422. var Matrix = (function () {
  1423. function Matrix() {
  1424. this.m = new Float32Array(16);
  1425. }
  1426. // Properties
  1427. Matrix.prototype.isIdentity = function () {
  1428. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1429. return false;
  1430. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1431. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1432. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1433. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1434. return false;
  1435. return true;
  1436. };
  1437. Matrix.prototype.determinant = function () {
  1438. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1439. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1440. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1441. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1442. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1443. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1444. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1445. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1446. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1447. };
  1448. // Methods
  1449. Matrix.prototype.toArray = function () {
  1450. return this.m;
  1451. };
  1452. Matrix.prototype.asArray = function () {
  1453. return this.toArray();
  1454. };
  1455. Matrix.prototype.invert = function () {
  1456. this.invertToRef(this);
  1457. return this;
  1458. };
  1459. Matrix.prototype.invertToRef = function (other) {
  1460. var l1 = this.m[0];
  1461. var l2 = this.m[1];
  1462. var l3 = this.m[2];
  1463. var l4 = this.m[3];
  1464. var l5 = this.m[4];
  1465. var l6 = this.m[5];
  1466. var l7 = this.m[6];
  1467. var l8 = this.m[7];
  1468. var l9 = this.m[8];
  1469. var l10 = this.m[9];
  1470. var l11 = this.m[10];
  1471. var l12 = this.m[11];
  1472. var l13 = this.m[12];
  1473. var l14 = this.m[13];
  1474. var l15 = this.m[14];
  1475. var l16 = this.m[15];
  1476. var l17 = (l11 * l16) - (l12 * l15);
  1477. var l18 = (l10 * l16) - (l12 * l14);
  1478. var l19 = (l10 * l15) - (l11 * l14);
  1479. var l20 = (l9 * l16) - (l12 * l13);
  1480. var l21 = (l9 * l15) - (l11 * l13);
  1481. var l22 = (l9 * l14) - (l10 * l13);
  1482. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1483. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1484. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1485. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1486. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1487. var l28 = (l7 * l16) - (l8 * l15);
  1488. var l29 = (l6 * l16) - (l8 * l14);
  1489. var l30 = (l6 * l15) - (l7 * l14);
  1490. var l31 = (l5 * l16) - (l8 * l13);
  1491. var l32 = (l5 * l15) - (l7 * l13);
  1492. var l33 = (l5 * l14) - (l6 * l13);
  1493. var l34 = (l7 * l12) - (l8 * l11);
  1494. var l35 = (l6 * l12) - (l8 * l10);
  1495. var l36 = (l6 * l11) - (l7 * l10);
  1496. var l37 = (l5 * l12) - (l8 * l9);
  1497. var l38 = (l5 * l11) - (l7 * l9);
  1498. var l39 = (l5 * l10) - (l6 * l9);
  1499. other.m[0] = l23 * l27;
  1500. other.m[4] = l24 * l27;
  1501. other.m[8] = l25 * l27;
  1502. other.m[12] = l26 * l27;
  1503. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1504. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1505. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1506. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1507. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1508. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1509. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1510. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1511. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1512. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1513. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1514. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1515. return this;
  1516. };
  1517. Matrix.prototype.invertToRefSIMD = function (other) {
  1518. var src = this.m;
  1519. var dest = other.m;
  1520. var row0, row1, row2, row3;
  1521. var tmp1;
  1522. var minor0, minor1, minor2, minor3;
  1523. var det;
  1524. // Load the 4 rows
  1525. var src0 = SIMD.float32x4.load(src, 0);
  1526. var src1 = SIMD.float32x4.load(src, 4);
  1527. var src2 = SIMD.float32x4.load(src, 8);
  1528. var src3 = SIMD.float32x4.load(src, 12);
  1529. // Transpose the source matrix. Sort of. Not a true transpose operation
  1530. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1531. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1532. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1533. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1534. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1535. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1536. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1537. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1538. // This is a true transposition, but it will lead to an incorrect result
  1539. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1540. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1541. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1542. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1543. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1544. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1545. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1546. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1547. // ----
  1548. tmp1 = SIMD.float32x4.mul(row2, row3);
  1549. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1550. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1551. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1552. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1553. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1554. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1555. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1556. // ----
  1557. tmp1 = SIMD.float32x4.mul(row1, row2);
  1558. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1559. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1560. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1561. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1562. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1563. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1564. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1565. // ----
  1566. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1567. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1568. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1569. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1570. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1571. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1572. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1573. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1574. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1575. // ----
  1576. tmp1 = SIMD.float32x4.mul(row0, row1);
  1577. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1578. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1579. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1580. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1581. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1582. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1583. // ----
  1584. tmp1 = SIMD.float32x4.mul(row0, row3);
  1585. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1586. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1587. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1588. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1589. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1590. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1591. // ----
  1592. tmp1 = SIMD.float32x4.mul(row0, row2);
  1593. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1594. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1595. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1596. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1597. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1598. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1599. // Compute determinant
  1600. det = SIMD.float32x4.mul(row0, minor0);
  1601. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1602. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1603. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1604. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1605. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1606. // These shuffles aren't necessary if the faulty transposition is done
  1607. // up at the top of this function.
  1608. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1609. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1610. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1611. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1612. // Compute final values by multiplying with 1/det
  1613. minor0 = SIMD.float32x4.mul(det, minor0);
  1614. minor1 = SIMD.float32x4.mul(det, minor1);
  1615. minor2 = SIMD.float32x4.mul(det, minor2);
  1616. minor3 = SIMD.float32x4.mul(det, minor3);
  1617. SIMD.float32x4.store(dest, 0, minor0);
  1618. SIMD.float32x4.store(dest, 4, minor1);
  1619. SIMD.float32x4.store(dest, 8, minor2);
  1620. SIMD.float32x4.store(dest, 12, minor3);
  1621. return this;
  1622. };
  1623. Matrix.prototype.setTranslation = function (vector3) {
  1624. this.m[12] = vector3.x;
  1625. this.m[13] = vector3.y;
  1626. this.m[14] = vector3.z;
  1627. return this;
  1628. };
  1629. Matrix.prototype.multiply = function (other) {
  1630. var result = new Matrix();
  1631. this.multiplyToRef(other, result);
  1632. return result;
  1633. };
  1634. Matrix.prototype.copyFrom = function (other) {
  1635. for (var index = 0; index < 16; index++) {
  1636. this.m[index] = other.m[index];
  1637. }
  1638. return this;
  1639. };
  1640. Matrix.prototype.copyToArray = function (array, offset) {
  1641. if (offset === void 0) { offset = 0; }
  1642. for (var index = 0; index < 16; index++) {
  1643. array[offset + index] = this.m[index];
  1644. }
  1645. return this;
  1646. };
  1647. Matrix.prototype.multiplyToRef = function (other, result) {
  1648. this.multiplyToArray(other, result.m, 0);
  1649. return this;
  1650. };
  1651. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1652. var tm0 = this.m[0];
  1653. var tm1 = this.m[1];
  1654. var tm2 = this.m[2];
  1655. var tm3 = this.m[3];
  1656. var tm4 = this.m[4];
  1657. var tm5 = this.m[5];
  1658. var tm6 = this.m[6];
  1659. var tm7 = this.m[7];
  1660. var tm8 = this.m[8];
  1661. var tm9 = this.m[9];
  1662. var tm10 = this.m[10];
  1663. var tm11 = this.m[11];
  1664. var tm12 = this.m[12];
  1665. var tm13 = this.m[13];
  1666. var tm14 = this.m[14];
  1667. var tm15 = this.m[15];
  1668. var om0 = other.m[0];
  1669. var om1 = other.m[1];
  1670. var om2 = other.m[2];
  1671. var om3 = other.m[3];
  1672. var om4 = other.m[4];
  1673. var om5 = other.m[5];
  1674. var om6 = other.m[6];
  1675. var om7 = other.m[7];
  1676. var om8 = other.m[8];
  1677. var om9 = other.m[9];
  1678. var om10 = other.m[10];
  1679. var om11 = other.m[11];
  1680. var om12 = other.m[12];
  1681. var om13 = other.m[13];
  1682. var om14 = other.m[14];
  1683. var om15 = other.m[15];
  1684. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1685. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1686. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1687. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1688. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1689. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1690. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1691. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1692. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1693. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1694. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1695. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1696. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1697. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1698. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1699. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1700. return this;
  1701. };
  1702. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1703. if (offset === void 0) { offset = 0; }
  1704. var tm = this.m;
  1705. var om = other.m;
  1706. var om0 = SIMD.float32x4.load(om, 0);
  1707. var om1 = SIMD.float32x4.load(om, 4);
  1708. var om2 = SIMD.float32x4.load(om, 8);
  1709. var om3 = SIMD.float32x4.load(om, 12);
  1710. var tm0 = SIMD.float32x4.load(tm, 0);
  1711. 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)))));
  1712. var tm1 = SIMD.float32x4.load(tm, 4);
  1713. 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)))));
  1714. var tm2 = SIMD.float32x4.load(tm, 8);
  1715. 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)))));
  1716. var tm3 = SIMD.float32x4.load(tm, 12);
  1717. 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)))));
  1718. };
  1719. Matrix.prototype.equals = function (value) {
  1720. return value &&
  1721. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1722. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1723. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1724. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1725. };
  1726. Matrix.prototype.clone = function () {
  1727. 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]);
  1728. };
  1729. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1730. translation.x = this.m[12];
  1731. translation.y = this.m[13];
  1732. translation.z = this.m[14];
  1733. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1734. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1735. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1736. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1737. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1738. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1739. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1740. rotation.x = 0;
  1741. rotation.y = 0;
  1742. rotation.z = 0;
  1743. rotation.w = 1;
  1744. return false;
  1745. }
  1746. 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);
  1747. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1748. return true;
  1749. };
  1750. // Statics
  1751. Matrix.FromArray = function (array, offset) {
  1752. var result = new Matrix();
  1753. if (!offset) {
  1754. offset = 0;
  1755. }
  1756. Matrix.FromArrayToRef(array, offset, result);
  1757. return result;
  1758. };
  1759. Matrix.FromArrayToRef = function (array, offset, result) {
  1760. for (var index = 0; index < 16; index++) {
  1761. result.m[index] = array[index + offset];
  1762. }
  1763. };
  1764. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1765. result.m[0] = initialM11;
  1766. result.m[1] = initialM12;
  1767. result.m[2] = initialM13;
  1768. result.m[3] = initialM14;
  1769. result.m[4] = initialM21;
  1770. result.m[5] = initialM22;
  1771. result.m[6] = initialM23;
  1772. result.m[7] = initialM24;
  1773. result.m[8] = initialM31;
  1774. result.m[9] = initialM32;
  1775. result.m[10] = initialM33;
  1776. result.m[11] = initialM34;
  1777. result.m[12] = initialM41;
  1778. result.m[13] = initialM42;
  1779. result.m[14] = initialM43;
  1780. result.m[15] = initialM44;
  1781. };
  1782. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1783. var result = new Matrix();
  1784. result.m[0] = initialM11;
  1785. result.m[1] = initialM12;
  1786. result.m[2] = initialM13;
  1787. result.m[3] = initialM14;
  1788. result.m[4] = initialM21;
  1789. result.m[5] = initialM22;
  1790. result.m[6] = initialM23;
  1791. result.m[7] = initialM24;
  1792. result.m[8] = initialM31;
  1793. result.m[9] = initialM32;
  1794. result.m[10] = initialM33;
  1795. result.m[11] = initialM34;
  1796. result.m[12] = initialM41;
  1797. result.m[13] = initialM42;
  1798. result.m[14] = initialM43;
  1799. result.m[15] = initialM44;
  1800. return result;
  1801. };
  1802. Matrix.Compose = function (scale, rotation, translation) {
  1803. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1804. var rotationMatrix = Matrix.Identity();
  1805. rotation.toRotationMatrix(rotationMatrix);
  1806. result = result.multiply(rotationMatrix);
  1807. result.setTranslation(translation);
  1808. return result;
  1809. };
  1810. Matrix.Identity = function () {
  1811. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1812. };
  1813. Matrix.IdentityToRef = function (result) {
  1814. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1815. };
  1816. Matrix.Zero = function () {
  1817. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1818. };
  1819. Matrix.RotationX = function (angle) {
  1820. var result = new Matrix();
  1821. Matrix.RotationXToRef(angle, result);
  1822. return result;
  1823. };
  1824. Matrix.Invert = function (source) {
  1825. var result = new Matrix();
  1826. source.invertToRef(result);
  1827. return result;
  1828. };
  1829. Matrix.RotationXToRef = function (angle, result) {
  1830. var s = Math.sin(angle);
  1831. var c = Math.cos(angle);
  1832. result.m[0] = 1.0;
  1833. result.m[15] = 1.0;
  1834. result.m[5] = c;
  1835. result.m[10] = c;
  1836. result.m[9] = -s;
  1837. result.m[6] = s;
  1838. result.m[1] = 0;
  1839. result.m[2] = 0;
  1840. result.m[3] = 0;
  1841. result.m[4] = 0;
  1842. result.m[7] = 0;
  1843. result.m[8] = 0;
  1844. result.m[11] = 0;
  1845. result.m[12] = 0;
  1846. result.m[13] = 0;
  1847. result.m[14] = 0;
  1848. };
  1849. Matrix.RotationY = function (angle) {
  1850. var result = new Matrix();
  1851. Matrix.RotationYToRef(angle, result);
  1852. return result;
  1853. };
  1854. Matrix.RotationYToRef = function (angle, result) {
  1855. var s = Math.sin(angle);
  1856. var c = Math.cos(angle);
  1857. result.m[5] = 1.0;
  1858. result.m[15] = 1.0;
  1859. result.m[0] = c;
  1860. result.m[2] = -s;
  1861. result.m[8] = s;
  1862. result.m[10] = c;
  1863. result.m[1] = 0;
  1864. result.m[3] = 0;
  1865. result.m[4] = 0;
  1866. result.m[6] = 0;
  1867. result.m[7] = 0;
  1868. result.m[9] = 0;
  1869. result.m[11] = 0;
  1870. result.m[12] = 0;
  1871. result.m[13] = 0;
  1872. result.m[14] = 0;
  1873. };
  1874. Matrix.RotationZ = function (angle) {
  1875. var result = new Matrix();
  1876. Matrix.RotationZToRef(angle, result);
  1877. return result;
  1878. };
  1879. Matrix.RotationZToRef = function (angle, result) {
  1880. var s = Math.sin(angle);
  1881. var c = Math.cos(angle);
  1882. result.m[10] = 1.0;
  1883. result.m[15] = 1.0;
  1884. result.m[0] = c;
  1885. result.m[1] = s;
  1886. result.m[4] = -s;
  1887. result.m[5] = c;
  1888. result.m[2] = 0;
  1889. result.m[3] = 0;
  1890. result.m[6] = 0;
  1891. result.m[7] = 0;
  1892. result.m[8] = 0;
  1893. result.m[9] = 0;
  1894. result.m[11] = 0;
  1895. result.m[12] = 0;
  1896. result.m[13] = 0;
  1897. result.m[14] = 0;
  1898. };
  1899. Matrix.RotationAxis = function (axis, angle) {
  1900. var s = Math.sin(-angle);
  1901. var c = Math.cos(-angle);
  1902. var c1 = 1 - c;
  1903. axis.normalize();
  1904. var result = Matrix.Zero();
  1905. result.m[0] = (axis.x * axis.x) * c1 + c;
  1906. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1907. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1908. result.m[3] = 0.0;
  1909. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1910. result.m[5] = (axis.y * axis.y) * c1 + c;
  1911. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1912. result.m[7] = 0.0;
  1913. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1914. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1915. result.m[10] = (axis.z * axis.z) * c1 + c;
  1916. result.m[11] = 0.0;
  1917. result.m[15] = 1.0;
  1918. return result;
  1919. };
  1920. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1921. var result = new Matrix();
  1922. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1923. return result;
  1924. };
  1925. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1926. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1927. this._tempQuaternion.toRotationMatrix(result);
  1928. };
  1929. Matrix.Scaling = function (x, y, z) {
  1930. var result = Matrix.Zero();
  1931. Matrix.ScalingToRef(x, y, z, result);
  1932. return result;
  1933. };
  1934. Matrix.ScalingToRef = function (x, y, z, result) {
  1935. result.m[0] = x;
  1936. result.m[1] = 0;
  1937. result.m[2] = 0;
  1938. result.m[3] = 0;
  1939. result.m[4] = 0;
  1940. result.m[5] = y;
  1941. result.m[6] = 0;
  1942. result.m[7] = 0;
  1943. result.m[8] = 0;
  1944. result.m[9] = 0;
  1945. result.m[10] = z;
  1946. result.m[11] = 0;
  1947. result.m[12] = 0;
  1948. result.m[13] = 0;
  1949. result.m[14] = 0;
  1950. result.m[15] = 1.0;
  1951. };
  1952. Matrix.Translation = function (x, y, z) {
  1953. var result = Matrix.Identity();
  1954. Matrix.TranslationToRef(x, y, z, result);
  1955. return result;
  1956. };
  1957. Matrix.TranslationToRef = function (x, y, z, result) {
  1958. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1959. };
  1960. Matrix.LookAtLH = function (eye, target, up) {
  1961. var result = Matrix.Zero();
  1962. Matrix.LookAtLHToRef(eye, target, up, result);
  1963. return result;
  1964. };
  1965. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1966. // Z axis
  1967. target.subtractToRef(eye, this._zAxis);
  1968. this._zAxis.normalize();
  1969. // X axis
  1970. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1971. this._xAxis.normalize();
  1972. // Y axis
  1973. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1974. this._yAxis.normalize();
  1975. // Eye angles
  1976. var ex = -Vector3.Dot(this._xAxis, eye);
  1977. var ey = -Vector3.Dot(this._yAxis, eye);
  1978. var ez = -Vector3.Dot(this._zAxis, eye);
  1979. 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);
  1980. };
  1981. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1982. var out = result.m;
  1983. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1984. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1985. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1986. // cc.kmVec3Subtract(f, pCenter, pEye);
  1987. var f = SIMD.float32x4.sub(center, eye);
  1988. // cc.kmVec3Normalize(f, f);
  1989. var tmp = SIMD.float32x4.mul(f, f);
  1990. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1991. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1992. // cc.kmVec3Assign(up, pUp);
  1993. // cc.kmVec3Normalize(up, up);
  1994. tmp = SIMD.float32x4.mul(up, up);
  1995. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1996. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1997. // cc.kmVec3Cross(s, f, up);
  1998. 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)));
  1999. // cc.kmVec3Normalize(s, s);
  2000. tmp = SIMD.float32x4.mul(s, s);
  2001. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2002. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2003. // cc.kmVec3Cross(u, s, f);
  2004. 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)));
  2005. // cc.kmVec3Normalize(s, s);
  2006. tmp = SIMD.float32x4.mul(s, s);
  2007. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2008. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2009. var zero = SIMD.float32x4.splat(0.0);
  2010. s = SIMD.float32x4.neg(s);
  2011. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2012. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2013. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2014. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2015. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2016. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2017. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2018. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2019. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2020. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2021. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2022. var b3 = SIMD.float32x4.neg(eye);
  2023. b3 = SIMD.float32x4.withW(b3, 1.0);
  2024. 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)))));
  2025. 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)))));
  2026. 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)))));
  2027. 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)))));
  2028. };
  2029. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2030. var matrix = Matrix.Zero();
  2031. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2032. return matrix;
  2033. };
  2034. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2035. var hw = 2.0 / width;
  2036. var hh = 2.0 / height;
  2037. var id = 1.0 / (zfar - znear);
  2038. var nid = znear / (znear - zfar);
  2039. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2040. };
  2041. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2042. var matrix = Matrix.Zero();
  2043. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2044. return matrix;
  2045. };
  2046. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2047. result.m[0] = 2.0 / (right - left);
  2048. result.m[1] = result.m[2] = result.m[3] = 0;
  2049. result.m[5] = 2.0 / (top - bottom);
  2050. result.m[4] = result.m[6] = result.m[7] = 0;
  2051. result.m[10] = -1.0 / (znear - zfar);
  2052. result.m[8] = result.m[9] = result.m[11] = 0;
  2053. result.m[12] = (left + right) / (left - right);
  2054. result.m[13] = (top + bottom) / (bottom - top);
  2055. result.m[14] = znear / (znear - zfar);
  2056. result.m[15] = 1.0;
  2057. };
  2058. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2059. var matrix = Matrix.Zero();
  2060. matrix.m[0] = (2.0 * znear) / width;
  2061. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2062. matrix.m[5] = (2.0 * znear) / height;
  2063. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2064. matrix.m[10] = -zfar / (znear - zfar);
  2065. matrix.m[8] = matrix.m[9] = 0.0;
  2066. matrix.m[11] = 1.0;
  2067. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2068. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2069. return matrix;
  2070. };
  2071. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2072. var matrix = Matrix.Zero();
  2073. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2074. return matrix;
  2075. };
  2076. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2077. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2078. var tan = 1.0 / (Math.tan(fov * 0.5));
  2079. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2080. if (v_fixed) {
  2081. result.m[0] = tan / aspect;
  2082. }
  2083. else {
  2084. result.m[0] = tan;
  2085. }
  2086. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2087. if (v_fixed) {
  2088. result.m[5] = tan;
  2089. }
  2090. else {
  2091. result.m[5] = tan * aspect;
  2092. }
  2093. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2094. result.m[8] = result.m[9] = 0.0;
  2095. result.m[10] = -zfar / (znear - zfar);
  2096. result.m[11] = 1.0;
  2097. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2098. result.m[14] = (znear * zfar) / (znear - zfar);
  2099. };
  2100. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2101. var cw = viewport.width;
  2102. var ch = viewport.height;
  2103. var cx = viewport.x;
  2104. var cy = viewport.y;
  2105. 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);
  2106. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2107. };
  2108. Matrix.Transpose = function (matrix) {
  2109. var result = new Matrix();
  2110. result.m[0] = matrix.m[0];
  2111. result.m[1] = matrix.m[4];
  2112. result.m[2] = matrix.m[8];
  2113. result.m[3] = matrix.m[12];
  2114. result.m[4] = matrix.m[1];
  2115. result.m[5] = matrix.m[5];
  2116. result.m[6] = matrix.m[9];
  2117. result.m[7] = matrix.m[13];
  2118. result.m[8] = matrix.m[2];
  2119. result.m[9] = matrix.m[6];
  2120. result.m[10] = matrix.m[10];
  2121. result.m[11] = matrix.m[14];
  2122. result.m[12] = matrix.m[3];
  2123. result.m[13] = matrix.m[7];
  2124. result.m[14] = matrix.m[11];
  2125. result.m[15] = matrix.m[15];
  2126. return result;
  2127. };
  2128. Matrix.Reflection = function (plane) {
  2129. var matrix = new Matrix();
  2130. Matrix.ReflectionToRef(plane, matrix);
  2131. return matrix;
  2132. };
  2133. Matrix.ReflectionToRef = function (plane, result) {
  2134. plane.normalize();
  2135. var x = plane.normal.x;
  2136. var y = plane.normal.y;
  2137. var z = plane.normal.z;
  2138. var temp = -2 * x;
  2139. var temp2 = -2 * y;
  2140. var temp3 = -2 * z;
  2141. result.m[0] = (temp * x) + 1;
  2142. result.m[1] = temp2 * x;
  2143. result.m[2] = temp3 * x;
  2144. result.m[3] = 0.0;
  2145. result.m[4] = temp * y;
  2146. result.m[5] = (temp2 * y) + 1;
  2147. result.m[6] = temp3 * y;
  2148. result.m[7] = 0.0;
  2149. result.m[8] = temp * z;
  2150. result.m[9] = temp2 * z;
  2151. result.m[10] = (temp3 * z) + 1;
  2152. result.m[11] = 0.0;
  2153. result.m[12] = temp * plane.d;
  2154. result.m[13] = temp2 * plane.d;
  2155. result.m[14] = temp3 * plane.d;
  2156. result.m[15] = 1.0;
  2157. };
  2158. Matrix._tempQuaternion = new Quaternion();
  2159. Matrix._xAxis = Vector3.Zero();
  2160. Matrix._yAxis = Vector3.Zero();
  2161. Matrix._zAxis = Vector3.Zero();
  2162. return Matrix;
  2163. })();
  2164. BABYLON.Matrix = Matrix;
  2165. var Plane = (function () {
  2166. function Plane(a, b, c, d) {
  2167. this.normal = new Vector3(a, b, c);
  2168. this.d = d;
  2169. }
  2170. Plane.prototype.asArray = function () {
  2171. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2172. };
  2173. // Methods
  2174. Plane.prototype.clone = function () {
  2175. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2176. };
  2177. Plane.prototype.normalize = function () {
  2178. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2179. var magnitude = 0;
  2180. if (norm !== 0) {
  2181. magnitude = 1.0 / norm;
  2182. }
  2183. this.normal.x *= magnitude;
  2184. this.normal.y *= magnitude;
  2185. this.normal.z *= magnitude;
  2186. this.d *= magnitude;
  2187. return this;
  2188. };
  2189. Plane.prototype.transform = function (transformation) {
  2190. var transposedMatrix = Matrix.Transpose(transformation);
  2191. var x = this.normal.x;
  2192. var y = this.normal.y;
  2193. var z = this.normal.z;
  2194. var d = this.d;
  2195. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2196. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2197. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2198. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2199. return new Plane(normalX, normalY, normalZ, finalD);
  2200. };
  2201. Plane.prototype.dotCoordinate = function (point) {
  2202. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2203. };
  2204. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2205. var x1 = point2.x - point1.x;
  2206. var y1 = point2.y - point1.y;
  2207. var z1 = point2.z - point1.z;
  2208. var x2 = point3.x - point1.x;
  2209. var y2 = point3.y - point1.y;
  2210. var z2 = point3.z - point1.z;
  2211. var yz = (y1 * z2) - (z1 * y2);
  2212. var xz = (z1 * x2) - (x1 * z2);
  2213. var xy = (x1 * y2) - (y1 * x2);
  2214. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2215. var invPyth;
  2216. if (pyth !== 0) {
  2217. invPyth = 1.0 / pyth;
  2218. }
  2219. else {
  2220. invPyth = 0;
  2221. }
  2222. this.normal.x = yz * invPyth;
  2223. this.normal.y = xz * invPyth;
  2224. this.normal.z = xy * invPyth;
  2225. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2226. return this;
  2227. };
  2228. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2229. var dot = Vector3.Dot(this.normal, direction);
  2230. return (dot <= epsilon);
  2231. };
  2232. Plane.prototype.signedDistanceTo = function (point) {
  2233. return Vector3.Dot(point, this.normal) + this.d;
  2234. };
  2235. // Statics
  2236. Plane.FromArray = function (array) {
  2237. return new Plane(array[0], array[1], array[2], array[3]);
  2238. };
  2239. Plane.FromPoints = function (point1, point2, point3) {
  2240. var result = new Plane(0, 0, 0, 0);
  2241. result.copyFromPoints(point1, point2, point3);
  2242. return result;
  2243. };
  2244. Plane.FromPositionAndNormal = function (origin, normal) {
  2245. var result = new Plane(0, 0, 0, 0);
  2246. normal.normalize();
  2247. result.normal = normal;
  2248. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2249. return result;
  2250. };
  2251. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2252. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2253. return Vector3.Dot(point, normal) + d;
  2254. };
  2255. return Plane;
  2256. })();
  2257. BABYLON.Plane = Plane;
  2258. var Viewport = (function () {
  2259. function Viewport(x, y, width, height) {
  2260. this.x = x;
  2261. this.y = y;
  2262. this.width = width;
  2263. this.height = height;
  2264. }
  2265. Viewport.prototype.toGlobal = function (engine) {
  2266. var width = engine.getRenderWidth();
  2267. var height = engine.getRenderHeight();
  2268. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2269. };
  2270. return Viewport;
  2271. })();
  2272. BABYLON.Viewport = Viewport;
  2273. var Frustum = (function () {
  2274. function Frustum() {
  2275. }
  2276. Frustum.GetPlanes = function (transform) {
  2277. var frustumPlanes = [];
  2278. for (var index = 0; index < 6; index++) {
  2279. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2280. }
  2281. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2282. return frustumPlanes;
  2283. };
  2284. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2285. // Near
  2286. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2287. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2288. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2289. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2290. frustumPlanes[0].normalize();
  2291. // Far
  2292. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2293. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2294. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2295. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2296. frustumPlanes[1].normalize();
  2297. // Left
  2298. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2299. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2300. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2301. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2302. frustumPlanes[2].normalize();
  2303. // Right
  2304. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2305. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2306. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2307. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2308. frustumPlanes[3].normalize();
  2309. // Top
  2310. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2311. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2312. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2313. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2314. frustumPlanes[4].normalize();
  2315. // Bottom
  2316. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2317. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2318. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2319. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2320. frustumPlanes[5].normalize();
  2321. };
  2322. return Frustum;
  2323. })();
  2324. BABYLON.Frustum = Frustum;
  2325. var Ray = (function () {
  2326. function Ray(origin, direction, length) {
  2327. if (length === void 0) { length = Number.MAX_VALUE; }
  2328. this.origin = origin;
  2329. this.direction = direction;
  2330. this.length = length;
  2331. }
  2332. // Methods
  2333. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2334. var d = 0.0;
  2335. var maxValue = Number.MAX_VALUE;
  2336. if (Math.abs(this.direction.x) < 0.0000001) {
  2337. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2338. return false;
  2339. }
  2340. }
  2341. else {
  2342. var inv = 1.0 / this.direction.x;
  2343. var min = (minimum.x - this.origin.x) * inv;
  2344. var max = (maximum.x - this.origin.x) * inv;
  2345. if (max === -Infinity) {
  2346. max = Infinity;
  2347. }
  2348. if (min > max) {
  2349. var temp = min;
  2350. min = max;
  2351. max = temp;
  2352. }
  2353. d = Math.max(min, d);
  2354. maxValue = Math.min(max, maxValue);
  2355. if (d > maxValue) {
  2356. return false;
  2357. }
  2358. }
  2359. if (Math.abs(this.direction.y) < 0.0000001) {
  2360. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2361. return false;
  2362. }
  2363. }
  2364. else {
  2365. inv = 1.0 / this.direction.y;
  2366. min = (minimum.y - this.origin.y) * inv;
  2367. max = (maximum.y - this.origin.y) * inv;
  2368. if (max === -Infinity) {
  2369. max = Infinity;
  2370. }
  2371. if (min > max) {
  2372. temp = min;
  2373. min = max;
  2374. max = temp;
  2375. }
  2376. d = Math.max(min, d);
  2377. maxValue = Math.min(max, maxValue);
  2378. if (d > maxValue) {
  2379. return false;
  2380. }
  2381. }
  2382. if (Math.abs(this.direction.z) < 0.0000001) {
  2383. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2384. return false;
  2385. }
  2386. }
  2387. else {
  2388. inv = 1.0 / this.direction.z;
  2389. min = (minimum.z - this.origin.z) * inv;
  2390. max = (maximum.z - this.origin.z) * inv;
  2391. if (max === -Infinity) {
  2392. max = Infinity;
  2393. }
  2394. if (min > max) {
  2395. temp = min;
  2396. min = max;
  2397. max = temp;
  2398. }
  2399. d = Math.max(min, d);
  2400. maxValue = Math.min(max, maxValue);
  2401. if (d > maxValue) {
  2402. return false;
  2403. }
  2404. }
  2405. return true;
  2406. };
  2407. Ray.prototype.intersectsBox = function (box) {
  2408. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2409. };
  2410. Ray.prototype.intersectsSphere = function (sphere) {
  2411. var x = sphere.center.x - this.origin.x;
  2412. var y = sphere.center.y - this.origin.y;
  2413. var z = sphere.center.z - this.origin.z;
  2414. var pyth = (x * x) + (y * y) + (z * z);
  2415. var rr = sphere.radius * sphere.radius;
  2416. if (pyth <= rr) {
  2417. return true;
  2418. }
  2419. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2420. if (dot < 0.0) {
  2421. return false;
  2422. }
  2423. var temp = pyth - (dot * dot);
  2424. return temp <= rr;
  2425. };
  2426. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2427. if (!this._edge1) {
  2428. this._edge1 = Vector3.Zero();
  2429. this._edge2 = Vector3.Zero();
  2430. this._pvec = Vector3.Zero();
  2431. this._tvec = Vector3.Zero();
  2432. this._qvec = Vector3.Zero();
  2433. }
  2434. vertex1.subtractToRef(vertex0, this._edge1);
  2435. vertex2.subtractToRef(vertex0, this._edge2);
  2436. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2437. var det = Vector3.Dot(this._edge1, this._pvec);
  2438. if (det === 0) {
  2439. return null;
  2440. }
  2441. var invdet = 1 / det;
  2442. this.origin.subtractToRef(vertex0, this._tvec);
  2443. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2444. if (bu < 0 || bu > 1.0) {
  2445. return null;
  2446. }
  2447. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2448. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2449. if (bv < 0 || bu + bv > 1.0) {
  2450. return null;
  2451. }
  2452. //check if the distance is longer than the predefined length.
  2453. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2454. if (distance > this.length) {
  2455. return null;
  2456. }
  2457. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2458. };
  2459. // Statics
  2460. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2461. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2462. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2463. var direction = end.subtract(start);
  2464. direction.normalize();
  2465. return new Ray(start, direction);
  2466. };
  2467. /**
  2468. * 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
  2469. * transformed to the given world matrix.
  2470. * @param origin The origin point
  2471. * @param end The end point
  2472. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2473. */
  2474. Ray.CreateNewFromTo = function (origin, end, world) {
  2475. if (world === void 0) { world = Matrix.Identity(); }
  2476. var direction = end.subtract(origin);
  2477. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2478. direction.normalize();
  2479. return Ray.Transform(new Ray(origin, direction, length), world);
  2480. };
  2481. Ray.Transform = function (ray, matrix) {
  2482. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2483. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2484. return new Ray(newOrigin, newDirection, ray.length);
  2485. };
  2486. return Ray;
  2487. })();
  2488. BABYLON.Ray = Ray;
  2489. (function (Space) {
  2490. Space[Space["LOCAL"] = 0] = "LOCAL";
  2491. Space[Space["WORLD"] = 1] = "WORLD";
  2492. })(BABYLON.Space || (BABYLON.Space = {}));
  2493. var Space = BABYLON.Space;
  2494. var Axis = (function () {
  2495. function Axis() {
  2496. }
  2497. Axis.X = new Vector3(1, 0, 0);
  2498. Axis.Y = new Vector3(0, 1, 0);
  2499. Axis.Z = new Vector3(0, 0, 1);
  2500. return Axis;
  2501. })();
  2502. BABYLON.Axis = Axis;
  2503. ;
  2504. var BezierCurve = (function () {
  2505. function BezierCurve() {
  2506. }
  2507. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2508. // Extract X (which is equal to time here)
  2509. var f0 = 1 - 3 * x2 + 3 * x1;
  2510. var f1 = 3 * x2 - 6 * x1;
  2511. var f2 = 3 * x1;
  2512. var refinedT = t;
  2513. for (var i = 0; i < 5; i++) {
  2514. var refinedT2 = refinedT * refinedT;
  2515. var refinedT3 = refinedT2 * refinedT;
  2516. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2517. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2518. refinedT -= (x - t) * slope;
  2519. refinedT = Math.min(1, Math.max(0, refinedT));
  2520. }
  2521. // Resolve cubic bezier for the given x
  2522. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2523. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2524. Math.pow(refinedT, 3);
  2525. };
  2526. return BezierCurve;
  2527. })();
  2528. BABYLON.BezierCurve = BezierCurve;
  2529. (function (Orientation) {
  2530. Orientation[Orientation["CW"] = 0] = "CW";
  2531. Orientation[Orientation["CCW"] = 1] = "CCW";
  2532. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2533. var Orientation = BABYLON.Orientation;
  2534. var Angle = (function () {
  2535. function Angle(radians) {
  2536. var _this = this;
  2537. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2538. this.radians = function () { return _this._radians; };
  2539. this._radians = radians;
  2540. if (this._radians < 0)
  2541. this._radians += (2 * Math.PI);
  2542. }
  2543. Angle.BetweenTwoPoints = function (a, b) {
  2544. var delta = b.subtract(a);
  2545. var theta = Math.atan2(delta.y, delta.x);
  2546. return new Angle(theta);
  2547. };
  2548. Angle.FromRadians = function (radians) {
  2549. return new Angle(radians);
  2550. };
  2551. Angle.FromDegrees = function (degrees) {
  2552. return new Angle(degrees * Math.PI / 180);
  2553. };
  2554. return Angle;
  2555. })();
  2556. BABYLON.Angle = Angle;
  2557. var Arc2 = (function () {
  2558. function Arc2(startPoint, midPoint, endPoint) {
  2559. this.startPoint = startPoint;
  2560. this.midPoint = midPoint;
  2561. this.endPoint = endPoint;
  2562. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2563. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2564. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2565. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2566. 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);
  2567. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2568. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2569. var a1 = this.startAngle.degrees();
  2570. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2571. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2572. // angles correction
  2573. if (a2 - a1 > +180.0)
  2574. a2 -= 360.0;
  2575. if (a2 - a1 < -180.0)
  2576. a2 += 360.0;
  2577. if (a3 - a2 > +180.0)
  2578. a3 -= 360.0;
  2579. if (a3 - a2 < -180.0)
  2580. a3 += 360.0;
  2581. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2582. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2583. }
  2584. return Arc2;
  2585. })();
  2586. BABYLON.Arc2 = Arc2;
  2587. var PathCursor = (function () {
  2588. function PathCursor(path) {
  2589. this.path = path;
  2590. this._onchange = new Array();
  2591. this.value = 0;
  2592. this.animations = new Array();
  2593. }
  2594. PathCursor.prototype.getPoint = function () {
  2595. var point = this.path.getPointAtLengthPosition(this.value);
  2596. return new Vector3(point.x, 0, point.y);
  2597. };
  2598. PathCursor.prototype.moveAhead = function (step) {
  2599. if (step === void 0) { step = 0.002; }
  2600. this.move(step);
  2601. return this;
  2602. };
  2603. PathCursor.prototype.moveBack = function (step) {
  2604. if (step === void 0) { step = 0.002; }
  2605. this.move(-step);
  2606. return this;
  2607. };
  2608. PathCursor.prototype.move = function (step) {
  2609. if (Math.abs(step) > 1) {
  2610. throw "step size should be less than 1.";
  2611. }
  2612. this.value += step;
  2613. this.ensureLimits();
  2614. this.raiseOnChange();
  2615. return this;
  2616. };
  2617. PathCursor.prototype.ensureLimits = function () {
  2618. while (this.value > 1) {
  2619. this.value -= 1;
  2620. }
  2621. while (this.value < 0) {
  2622. this.value += 1;
  2623. }
  2624. return this;
  2625. };
  2626. // used by animation engine
  2627. PathCursor.prototype.markAsDirty = function (propertyName) {
  2628. this.ensureLimits();
  2629. this.raiseOnChange();
  2630. return this;
  2631. };
  2632. PathCursor.prototype.raiseOnChange = function () {
  2633. var _this = this;
  2634. this._onchange.forEach(function (f) { return f(_this); });
  2635. return this;
  2636. };
  2637. PathCursor.prototype.onchange = function (f) {
  2638. this._onchange.push(f);
  2639. return this;
  2640. };
  2641. return PathCursor;
  2642. })();
  2643. BABYLON.PathCursor = PathCursor;
  2644. var Path2 = (function () {
  2645. function Path2(x, y) {
  2646. this._points = new Array();
  2647. this._length = 0;
  2648. this.closed = false;
  2649. this._points.push(new Vector2(x, y));
  2650. }
  2651. Path2.prototype.addLineTo = function (x, y) {
  2652. if (closed) {
  2653. BABYLON.Tools.Error("cannot add lines to closed paths");
  2654. return this;
  2655. }
  2656. var newPoint = new Vector2(x, y);
  2657. var previousPoint = this._points[this._points.length - 1];
  2658. this._points.push(newPoint);
  2659. this._length += newPoint.subtract(previousPoint).length();
  2660. return this;
  2661. };
  2662. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2663. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2664. if (closed) {
  2665. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2666. return this;
  2667. }
  2668. var startPoint = this._points[this._points.length - 1];
  2669. var midPoint = new Vector2(midX, midY);
  2670. var endPoint = new Vector2(endX, endY);
  2671. var arc = new Arc2(startPoint, midPoint, endPoint);
  2672. var increment = arc.angle.radians() / numberOfSegments;
  2673. if (arc.orientation === Orientation.CW)
  2674. increment *= -1;
  2675. var currentAngle = arc.startAngle.radians() + increment;
  2676. for (var i = 0; i < numberOfSegments; i++) {
  2677. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2678. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2679. this.addLineTo(x, y);
  2680. currentAngle += increment;
  2681. }
  2682. return this;
  2683. };
  2684. Path2.prototype.close = function () {
  2685. this.closed = true;
  2686. return this;
  2687. };
  2688. Path2.prototype.length = function () {
  2689. var result = this._length;
  2690. if (!this.closed) {
  2691. var lastPoint = this._points[this._points.length - 1];
  2692. var firstPoint = this._points[0];
  2693. result += (firstPoint.subtract(lastPoint).length());
  2694. }
  2695. return result;
  2696. };
  2697. Path2.prototype.getPoints = function () {
  2698. return this._points;
  2699. };
  2700. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2701. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2702. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2703. return Vector2.Zero();
  2704. }
  2705. var lengthPosition = normalizedLengthPosition * this.length();
  2706. var previousOffset = 0;
  2707. for (var i = 0; i < this._points.length; i++) {
  2708. var j = (i + 1) % this._points.length;
  2709. var a = this._points[i];
  2710. var b = this._points[j];
  2711. var bToA = b.subtract(a);
  2712. var nextOffset = (bToA.length() + previousOffset);
  2713. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2714. var dir = bToA.normalize();
  2715. var localOffset = lengthPosition - previousOffset;
  2716. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2717. }
  2718. previousOffset = nextOffset;
  2719. }
  2720. BABYLON.Tools.Error("internal error");
  2721. return Vector2.Zero();
  2722. };
  2723. Path2.StartingAt = function (x, y) {
  2724. return new Path2(x, y);
  2725. };
  2726. return Path2;
  2727. })();
  2728. BABYLON.Path2 = Path2;
  2729. var Path3D = (function () {
  2730. function Path3D(path, firstNormal) {
  2731. this.path = path;
  2732. this._curve = new Array();
  2733. this._distances = new Array();
  2734. this._tangents = new Array();
  2735. this._normals = new Array();
  2736. this._binormals = new Array();
  2737. for (var p = 0; p < path.length; p++) {
  2738. this._curve[p] = path[p].clone(); // hard copy
  2739. }
  2740. this._compute(firstNormal);
  2741. }
  2742. Path3D.prototype.getCurve = function () {
  2743. return this._curve;
  2744. };
  2745. Path3D.prototype.getTangents = function () {
  2746. return this._tangents;
  2747. };
  2748. Path3D.prototype.getNormals = function () {
  2749. return this._normals;
  2750. };
  2751. Path3D.prototype.getBinormals = function () {
  2752. return this._binormals;
  2753. };
  2754. Path3D.prototype.getDistances = function () {
  2755. return this._distances;
  2756. };
  2757. Path3D.prototype.update = function (path, firstNormal) {
  2758. for (var p = 0; p < path.length; p++) {
  2759. this._curve[p].x = path[p].x;
  2760. this._curve[p].y = path[p].y;
  2761. this._curve[p].z = path[p].z;
  2762. }
  2763. this._compute(firstNormal);
  2764. return this;
  2765. };
  2766. // private function compute() : computes tangents, normals and binormals
  2767. Path3D.prototype._compute = function (firstNormal) {
  2768. var l = this._curve.length;
  2769. // first and last tangents
  2770. this._tangents[0] = this._getFirstNonNullVector(0);
  2771. this._tangents[0].normalize();
  2772. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2773. this._tangents[l - 1].normalize();
  2774. // normals and binormals at first point : arbitrary vector with _normalVector()
  2775. var tg0 = this._tangents[0];
  2776. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2777. this._normals[0] = pp0;
  2778. this._normals[0].normalize();
  2779. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2780. this._binormals[0].normalize();
  2781. this._distances[0] = 0;
  2782. // normals and binormals : next points
  2783. var prev; // previous vector (segment)
  2784. var cur; // current vector (segment)
  2785. var curTang; // current tangent
  2786. var prevNorm; // previous normal
  2787. var prevBinor; // previous binormal
  2788. for (var i = 1; i < l; i++) {
  2789. // tangents
  2790. prev = this._getLastNonNullVector(i);
  2791. if (i < l - 1) {
  2792. cur = this._getFirstNonNullVector(i);
  2793. this._tangents[i] = prev.add(cur);
  2794. this._tangents[i].normalize();
  2795. }
  2796. this._distances[i] = this._distances[i - 1] + prev.length();
  2797. // normals and binormals
  2798. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2799. curTang = this._tangents[i];
  2800. prevNorm = this._normals[i - 1];
  2801. prevBinor = this._binormals[i - 1];
  2802. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2803. this._normals[i].normalize();
  2804. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2805. this._binormals[i].normalize();
  2806. }
  2807. };
  2808. // private function getFirstNonNullVector(index)
  2809. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2810. Path3D.prototype._getFirstNonNullVector = function (index) {
  2811. var i = 1;
  2812. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2813. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2814. i++;
  2815. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2816. }
  2817. return nNVector;
  2818. };
  2819. // private function getLastNonNullVector(index)
  2820. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2821. Path3D.prototype._getLastNonNullVector = function (index) {
  2822. var i = 1;
  2823. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2824. while (nLVector.length() == 0 && index > i + 1) {
  2825. i++;
  2826. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2827. }
  2828. return nLVector;
  2829. };
  2830. // private function normalVector(v0, vt, va) :
  2831. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2832. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2833. Path3D.prototype._normalVector = function (v0, vt, va) {
  2834. var normal0;
  2835. if (va === undefined || va === null) {
  2836. var point;
  2837. if (vt.y !== 1) {
  2838. point = new Vector3(0, -1, 0);
  2839. }
  2840. else if (vt.x !== 1) {
  2841. point = new Vector3(1, 0, 0);
  2842. }
  2843. else if (vt.z !== 1) {
  2844. point = new Vector3(0, 0, 1);
  2845. }
  2846. normal0 = Vector3.Cross(vt, point);
  2847. }
  2848. else {
  2849. normal0 = Vector3.Cross(vt, va);
  2850. Vector3.CrossToRef(normal0, vt, normal0);
  2851. }
  2852. normal0.normalize();
  2853. return normal0;
  2854. };
  2855. return Path3D;
  2856. })();
  2857. BABYLON.Path3D = Path3D;
  2858. var Curve3 = (function () {
  2859. function Curve3(points) {
  2860. this._length = 0;
  2861. this._points = points;
  2862. this._length = this._computeLength(points);
  2863. }
  2864. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2865. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2866. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2867. var bez = new Array();
  2868. var equation = function (t, val0, val1, val2) {
  2869. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2870. return res;
  2871. };
  2872. for (var i = 0; i <= nbPoints; i++) {
  2873. 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)));
  2874. }
  2875. return new Curve3(bez);
  2876. };
  2877. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2878. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2879. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2880. var bez = new Array();
  2881. var equation = function (t, val0, val1, val2, val3) {
  2882. 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;
  2883. return res;
  2884. };
  2885. for (var i = 0; i <= nbPoints; i++) {
  2886. 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)));
  2887. }
  2888. return new Curve3(bez);
  2889. };
  2890. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2891. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2892. var hermite = new Array();
  2893. var step = 1 / nbPoints;
  2894. for (var i = 0; i <= nbPoints; i++) {
  2895. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2896. }
  2897. return new Curve3(hermite);
  2898. };
  2899. Curve3.prototype.getPoints = function () {
  2900. return this._points;
  2901. };
  2902. Curve3.prototype.length = function () {
  2903. return this._length;
  2904. };
  2905. Curve3.prototype.continue = function (curve) {
  2906. var lastPoint = this._points[this._points.length - 1];
  2907. var continuedPoints = this._points.slice();
  2908. var curvePoints = curve.getPoints();
  2909. for (var i = 1; i < curvePoints.length; i++) {
  2910. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2911. }
  2912. var continuedCurve = new Curve3(continuedPoints);
  2913. return continuedCurve;
  2914. };
  2915. Curve3.prototype._computeLength = function (path) {
  2916. var l = 0;
  2917. for (var i = 1; i < path.length; i++) {
  2918. l += (path[i].subtract(path[i - 1])).length();
  2919. }
  2920. return l;
  2921. };
  2922. return Curve3;
  2923. })();
  2924. BABYLON.Curve3 = Curve3;
  2925. // Vertex formats
  2926. var PositionNormalVertex = (function () {
  2927. function PositionNormalVertex(position, normal) {
  2928. if (position === void 0) { position = Vector3.Zero(); }
  2929. if (normal === void 0) { normal = Vector3.Up(); }
  2930. this.position = position;
  2931. this.normal = normal;
  2932. }
  2933. PositionNormalVertex.prototype.clone = function () {
  2934. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2935. };
  2936. return PositionNormalVertex;
  2937. })();
  2938. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2939. var PositionNormalTextureVertex = (function () {
  2940. function PositionNormalTextureVertex(position, normal, uv) {
  2941. if (position === void 0) { position = Vector3.Zero(); }
  2942. if (normal === void 0) { normal = Vector3.Up(); }
  2943. if (uv === void 0) { uv = Vector2.Zero(); }
  2944. this.position = position;
  2945. this.normal = normal;
  2946. this.uv = uv;
  2947. }
  2948. PositionNormalTextureVertex.prototype.clone = function () {
  2949. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2950. };
  2951. return PositionNormalTextureVertex;
  2952. })();
  2953. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2954. // SIMD
  2955. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2956. var previousInvertToRef = Matrix.prototype.invertToRef;
  2957. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2958. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2959. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2960. var SIMDHelper = (function () {
  2961. function SIMDHelper() {
  2962. }
  2963. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2964. get: function () {
  2965. return SIMDHelper._isEnabled;
  2966. },
  2967. enumerable: true,
  2968. configurable: true
  2969. });
  2970. SIMDHelper.DisableSIMD = function () {
  2971. // Replace functions
  2972. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2973. Matrix.prototype.invertToRef = previousInvertToRef;
  2974. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2975. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2976. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2977. SIMDHelper._isEnabled = false;
  2978. };
  2979. SIMDHelper.EnableSIMD = function () {
  2980. if (window.SIMD === undefined) {
  2981. return;
  2982. }
  2983. // Replace functions
  2984. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2985. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2986. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2987. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2988. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2989. Object.defineProperty(Vector3.prototype, "x", {
  2990. get: function () { return this._data[0]; },
  2991. set: function (value) {
  2992. if (!this._data) {
  2993. this._data = new Float32Array(3);
  2994. }
  2995. this._data[0] = value;
  2996. }
  2997. });
  2998. Object.defineProperty(Vector3.prototype, "y", {
  2999. get: function () { return this._data[1]; },
  3000. set: function (value) {
  3001. this._data[1] = value;
  3002. }
  3003. });
  3004. Object.defineProperty(Vector3.prototype, "z", {
  3005. get: function () { return this._data[2]; },
  3006. set: function (value) {
  3007. this._data[2] = value;
  3008. }
  3009. });
  3010. SIMDHelper._isEnabled = true;
  3011. };
  3012. SIMDHelper._isEnabled = false;
  3013. return SIMDHelper;
  3014. })();
  3015. BABYLON.SIMDHelper = SIMDHelper;
  3016. })(BABYLON || (BABYLON = {}));
  3017. //# sourceMappingURL=babylon.math.js.map
  3018. var BABYLON;
  3019. (function (BABYLON) {
  3020. var Database = (function () {
  3021. function Database(urlToScene, callbackManifestChecked) {
  3022. // Handling various flavors of prefixed version of IndexedDB
  3023. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3024. this.callbackManifestChecked = callbackManifestChecked;
  3025. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3026. this.db = null;
  3027. this.enableSceneOffline = false;
  3028. this.enableTexturesOffline = false;
  3029. this.manifestVersionFound = 0;
  3030. this.mustUpdateRessources = false;
  3031. this.hasReachedQuota = false;
  3032. if (!Database.IDBStorageEnabled) {
  3033. this.callbackManifestChecked(true);
  3034. }
  3035. else {
  3036. this.checkManifestFile();
  3037. }
  3038. }
  3039. Database.prototype.checkManifestFile = function () {
  3040. var _this = this;
  3041. function noManifestFile() {
  3042. that.enableSceneOffline = false;
  3043. that.enableTexturesOffline = false;
  3044. that.callbackManifestChecked(false);
  3045. }
  3046. var that = this;
  3047. var manifestURL = this.currentSceneUrl + ".manifest";
  3048. var xhr = new XMLHttpRequest();
  3049. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3050. xhr.open("GET", manifestURLTimeStamped, true);
  3051. xhr.addEventListener("load", function () {
  3052. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3053. try {
  3054. var manifestFile = JSON.parse(xhr.response);
  3055. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3056. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3057. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3058. _this.manifestVersionFound = manifestFile.version;
  3059. }
  3060. if (_this.callbackManifestChecked) {
  3061. _this.callbackManifestChecked(true);
  3062. }
  3063. }
  3064. catch (ex) {
  3065. noManifestFile();
  3066. }
  3067. }
  3068. else {
  3069. noManifestFile();
  3070. }
  3071. }, false);
  3072. xhr.addEventListener("error", function (event) {
  3073. noManifestFile();
  3074. }, false);
  3075. try {
  3076. xhr.send();
  3077. }
  3078. catch (ex) {
  3079. BABYLON.Tools.Error("Error on XHR send request.");
  3080. that.callbackManifestChecked(false);
  3081. }
  3082. };
  3083. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3084. var _this = this;
  3085. function handleError() {
  3086. that.isSupported = false;
  3087. if (errorCallback)
  3088. errorCallback();
  3089. }
  3090. var that = this;
  3091. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3092. // Your browser doesn't support IndexedDB
  3093. this.isSupported = false;
  3094. if (errorCallback)
  3095. errorCallback();
  3096. }
  3097. else {
  3098. // If the DB hasn't been opened or created yet
  3099. if (!this.db) {
  3100. this.hasReachedQuota = false;
  3101. this.isSupported = true;
  3102. var request = this.idbFactory.open("babylonjs", 1);
  3103. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3104. request.onerror = function (event) {
  3105. handleError();
  3106. };
  3107. // executes when a version change transaction cannot complete due to other active transactions
  3108. request.onblocked = function (event) {
  3109. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3110. handleError();
  3111. };
  3112. // DB has been opened successfully
  3113. request.onsuccess = function (event) {
  3114. _this.db = request.result;
  3115. successCallback();
  3116. };
  3117. // Initialization of the DB. Creating Scenes & Textures stores
  3118. request.onupgradeneeded = function (event) {
  3119. _this.db = (event.target).result;
  3120. try {
  3121. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3122. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3123. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3124. }
  3125. catch (ex) {
  3126. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3127. handleError();
  3128. }
  3129. };
  3130. }
  3131. else {
  3132. if (successCallback)
  3133. successCallback();
  3134. }
  3135. }
  3136. };
  3137. Database.prototype.loadImageFromDB = function (url, image) {
  3138. var _this = this;
  3139. var completeURL = Database.ReturnFullUrlLocation(url);
  3140. var saveAndLoadImage = function () {
  3141. if (!_this.hasReachedQuota && _this.db !== null) {
  3142. // the texture is not yet in the DB, let's try to save it
  3143. _this._saveImageIntoDBAsync(completeURL, image);
  3144. }
  3145. else {
  3146. image.src = url;
  3147. }
  3148. };
  3149. if (!this.mustUpdateRessources) {
  3150. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3151. }
  3152. else {
  3153. saveAndLoadImage();
  3154. }
  3155. };
  3156. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3157. if (this.isSupported && this.db !== null) {
  3158. var texture;
  3159. var transaction = this.db.transaction(["textures"]);
  3160. transaction.onabort = function (event) {
  3161. image.src = url;
  3162. };
  3163. transaction.oncomplete = function (event) {
  3164. var blobTextureURL;
  3165. if (texture) {
  3166. var URL = window.URL || window.webkitURL;
  3167. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3168. image.onerror = function () {
  3169. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3170. image.src = url;
  3171. };
  3172. image.src = blobTextureURL;
  3173. }
  3174. else {
  3175. notInDBCallback();
  3176. }
  3177. };
  3178. var getRequest = transaction.objectStore("textures").get(url);
  3179. getRequest.onsuccess = function (event) {
  3180. texture = (event.target).result;
  3181. };
  3182. getRequest.onerror = function (event) {
  3183. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3184. image.src = url;
  3185. };
  3186. }
  3187. else {
  3188. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3189. image.src = url;
  3190. }
  3191. };
  3192. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3193. var _this = this;
  3194. if (this.isSupported) {
  3195. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3196. var generateBlobUrl = function () {
  3197. var blobTextureURL;
  3198. if (blob) {
  3199. var URL = window.URL || window.webkitURL;
  3200. try {
  3201. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3202. }
  3203. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3204. catch (ex) {
  3205. blobTextureURL = URL.createObjectURL(blob);
  3206. }
  3207. }
  3208. image.src = blobTextureURL;
  3209. };
  3210. if (Database.IsUASupportingBlobStorage) {
  3211. var xhr = new XMLHttpRequest(), blob;
  3212. xhr.open("GET", url, true);
  3213. xhr.responseType = "blob";
  3214. xhr.addEventListener("load", function () {
  3215. if (xhr.status === 200) {
  3216. // Blob as response (XHR2)
  3217. blob = xhr.response;
  3218. var transaction = _this.db.transaction(["textures"], "readwrite");
  3219. // the transaction could abort because of a QuotaExceededError error
  3220. transaction.onabort = function (event) {
  3221. try {
  3222. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3223. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3224. this.hasReachedQuota = true;
  3225. }
  3226. }
  3227. catch (ex) { }
  3228. generateBlobUrl();
  3229. };
  3230. transaction.oncomplete = function (event) {
  3231. generateBlobUrl();
  3232. };
  3233. var newTexture = { textureUrl: url, data: blob };
  3234. try {
  3235. // Put the blob into the dabase
  3236. var addRequest = transaction.objectStore("textures").put(newTexture);
  3237. addRequest.onsuccess = function (event) {
  3238. };
  3239. addRequest.onerror = function (event) {
  3240. generateBlobUrl();
  3241. };
  3242. }
  3243. catch (ex) {
  3244. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3245. if (ex.code === 25) {
  3246. Database.IsUASupportingBlobStorage = false;
  3247. }
  3248. image.src = url;
  3249. }
  3250. }
  3251. else {
  3252. image.src = url;
  3253. }
  3254. }, false);
  3255. xhr.addEventListener("error", function (event) {
  3256. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3257. image.src = url;
  3258. }, false);
  3259. xhr.send();
  3260. }
  3261. else {
  3262. image.src = url;
  3263. }
  3264. }
  3265. else {
  3266. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3267. image.src = url;
  3268. }
  3269. };
  3270. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3271. var _this = this;
  3272. var updateVersion = function (event) {
  3273. // the version is not yet in the DB or we need to update it
  3274. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3275. };
  3276. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3277. };
  3278. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3279. var _this = this;
  3280. if (this.isSupported) {
  3281. var version;
  3282. try {
  3283. var transaction = this.db.transaction(["versions"]);
  3284. transaction.oncomplete = function (event) {
  3285. if (version) {
  3286. // If the version in the JSON file is > than the version in DB
  3287. if (_this.manifestVersionFound > version.data) {
  3288. _this.mustUpdateRessources = true;
  3289. updateInDBCallback();
  3290. }
  3291. else {
  3292. callback(version.data);
  3293. }
  3294. }
  3295. else {
  3296. _this.mustUpdateRessources = true;
  3297. updateInDBCallback();
  3298. }
  3299. };
  3300. transaction.onabort = function (event) {
  3301. callback(-1);
  3302. };
  3303. var getRequest = transaction.objectStore("versions").get(url);
  3304. getRequest.onsuccess = function (event) {
  3305. version = (event.target).result;
  3306. };
  3307. getRequest.onerror = function (event) {
  3308. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3309. callback(-1);
  3310. };
  3311. }
  3312. catch (ex) {
  3313. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3314. callback(-1);
  3315. }
  3316. }
  3317. else {
  3318. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3319. callback(-1);
  3320. }
  3321. };
  3322. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3323. var _this = this;
  3324. if (this.isSupported && !this.hasReachedQuota) {
  3325. try {
  3326. // Open a transaction to the database
  3327. var transaction = this.db.transaction(["versions"], "readwrite");
  3328. // the transaction could abort because of a QuotaExceededError error
  3329. transaction.onabort = function (event) {
  3330. try {
  3331. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3332. _this.hasReachedQuota = true;
  3333. }
  3334. }
  3335. catch (ex) { }
  3336. callback(-1);
  3337. };
  3338. transaction.oncomplete = function (event) {
  3339. callback(_this.manifestVersionFound);
  3340. };
  3341. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3342. // Put the scene into the database
  3343. var addRequest = transaction.objectStore("versions").put(newVersion);
  3344. addRequest.onsuccess = function (event) {
  3345. };
  3346. addRequest.onerror = function (event) {
  3347. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3348. };
  3349. }
  3350. catch (ex) {
  3351. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3352. callback(-1);
  3353. }
  3354. }
  3355. else {
  3356. callback(-1);
  3357. }
  3358. };
  3359. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3360. var _this = this;
  3361. var completeUrl = Database.ReturnFullUrlLocation(url);
  3362. var saveAndLoadFile = function (event) {
  3363. // the scene is not yet in the DB, let's try to save it
  3364. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3365. };
  3366. this._checkVersionFromDB(completeUrl, function (version) {
  3367. if (version !== -1) {
  3368. if (!_this.mustUpdateRessources) {
  3369. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3370. }
  3371. else {
  3372. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3373. }
  3374. }
  3375. else {
  3376. errorCallback();
  3377. }
  3378. });
  3379. };
  3380. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3381. if (this.isSupported) {
  3382. var targetStore;
  3383. if (url.indexOf(".babylon") !== -1) {
  3384. targetStore = "scenes";
  3385. }
  3386. else {
  3387. targetStore = "textures";
  3388. }
  3389. var file;
  3390. var transaction = this.db.transaction([targetStore]);
  3391. transaction.oncomplete = function (event) {
  3392. if (file) {
  3393. callback(file.data);
  3394. }
  3395. else {
  3396. notInDBCallback();
  3397. }
  3398. };
  3399. transaction.onabort = function (event) {
  3400. notInDBCallback();
  3401. };
  3402. var getRequest = transaction.objectStore(targetStore).get(url);
  3403. getRequest.onsuccess = function (event) {
  3404. file = (event.target).result;
  3405. };
  3406. getRequest.onerror = function (event) {
  3407. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3408. notInDBCallback();
  3409. };
  3410. }
  3411. else {
  3412. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3413. callback();
  3414. }
  3415. };
  3416. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3417. var _this = this;
  3418. if (this.isSupported) {
  3419. var targetStore;
  3420. if (url.indexOf(".babylon") !== -1) {
  3421. targetStore = "scenes";
  3422. }
  3423. else {
  3424. targetStore = "textures";
  3425. }
  3426. // Create XHR
  3427. var xhr = new XMLHttpRequest(), fileData;
  3428. xhr.open("GET", url, true);
  3429. if (useArrayBuffer) {
  3430. xhr.responseType = "arraybuffer";
  3431. }
  3432. xhr.onprogress = progressCallback;
  3433. xhr.addEventListener("load", function () {
  3434. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3435. // Blob as response (XHR2)
  3436. //fileData = xhr.responseText;
  3437. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3438. if (!_this.hasReachedQuota) {
  3439. // Open a transaction to the database
  3440. var transaction = _this.db.transaction([targetStore], "readwrite");
  3441. // the transaction could abort because of a QuotaExceededError error
  3442. transaction.onabort = function (event) {
  3443. try {
  3444. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3445. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3446. this.hasReachedQuota = true;
  3447. }
  3448. }
  3449. catch (ex) { }
  3450. callback(fileData);
  3451. };
  3452. transaction.oncomplete = function (event) {
  3453. callback(fileData);
  3454. };
  3455. var newFile;
  3456. if (targetStore === "scenes") {
  3457. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3458. }
  3459. else {
  3460. newFile = { textureUrl: url, data: fileData };
  3461. }
  3462. try {
  3463. // Put the scene into the database
  3464. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3465. addRequest.onsuccess = function (event) {
  3466. };
  3467. addRequest.onerror = function (event) {
  3468. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3469. };
  3470. }
  3471. catch (ex) {
  3472. callback(fileData);
  3473. }
  3474. }
  3475. else {
  3476. callback(fileData);
  3477. }
  3478. }
  3479. else {
  3480. callback();
  3481. }
  3482. }, false);
  3483. xhr.addEventListener("error", function (event) {
  3484. BABYLON.Tools.Error("error on XHR request.");
  3485. callback();
  3486. }, false);
  3487. xhr.send();
  3488. }
  3489. else {
  3490. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3491. callback();
  3492. }
  3493. };
  3494. Database.IsUASupportingBlobStorage = true;
  3495. Database.IDBStorageEnabled = true;
  3496. Database.parseURL = function (url) {
  3497. var a = document.createElement('a');
  3498. a.href = url;
  3499. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3500. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3501. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3502. return absLocation;
  3503. };
  3504. Database.ReturnFullUrlLocation = function (url) {
  3505. if (url.indexOf("http:/") === -1) {
  3506. return (Database.parseURL(window.location.href) + url);
  3507. }
  3508. else {
  3509. return url;
  3510. }
  3511. };
  3512. return Database;
  3513. })();
  3514. BABYLON.Database = Database;
  3515. })(BABYLON || (BABYLON = {}));
  3516. //# sourceMappingURL=babylon.database.js.map
  3517. var BABYLON;
  3518. (function (BABYLON) {
  3519. var Internals;
  3520. (function (Internals) {
  3521. /*
  3522. * Based on jsTGALoader - Javascript loader for TGA file
  3523. * By Vincent Thibault
  3524. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3525. */
  3526. var TGATools = (function () {
  3527. function TGATools() {
  3528. }
  3529. TGATools.GetTGAHeader = function (data) {
  3530. var offset = 0;
  3531. var header = {
  3532. id_length: data[offset++],
  3533. colormap_type: data[offset++],
  3534. image_type: data[offset++],
  3535. colormap_index: data[offset++] | data[offset++] << 8,
  3536. colormap_length: data[offset++] | data[offset++] << 8,
  3537. colormap_size: data[offset++],
  3538. origin: [
  3539. data[offset++] | data[offset++] << 8,
  3540. data[offset++] | data[offset++] << 8
  3541. ],
  3542. width: data[offset++] | data[offset++] << 8,
  3543. height: data[offset++] | data[offset++] << 8,
  3544. pixel_size: data[offset++],
  3545. flags: data[offset++]
  3546. };
  3547. return header;
  3548. };
  3549. TGATools.UploadContent = function (gl, data) {
  3550. // Not enough data to contain header ?
  3551. if (data.length < 19) {
  3552. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3553. return;
  3554. }
  3555. // Read Header
  3556. var offset = 18;
  3557. var header = TGATools.GetTGAHeader(data);
  3558. // Assume it's a valid Targa file.
  3559. if (header.id_length + offset > data.length) {
  3560. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3561. return;
  3562. }
  3563. // Skip not needed data
  3564. offset += header.id_length;
  3565. var use_rle = false;
  3566. var use_pal = false;
  3567. var use_rgb = false;
  3568. var use_grey = false;
  3569. // Get some informations.
  3570. switch (header.image_type) {
  3571. case TGATools._TYPE_RLE_INDEXED:
  3572. use_rle = true;
  3573. case TGATools._TYPE_INDEXED:
  3574. use_pal = true;
  3575. break;
  3576. case TGATools._TYPE_RLE_RGB:
  3577. use_rle = true;
  3578. case TGATools._TYPE_RGB:
  3579. use_rgb = true;
  3580. break;
  3581. case TGATools._TYPE_RLE_GREY:
  3582. use_rle = true;
  3583. case TGATools._TYPE_GREY:
  3584. use_grey = true;
  3585. break;
  3586. }
  3587. var pixel_data;
  3588. var numAlphaBits = header.flags & 0xf;
  3589. var pixel_size = header.pixel_size >> 3;
  3590. var pixel_total = header.width * header.height * pixel_size;
  3591. // Read palettes
  3592. var palettes;
  3593. if (use_pal) {
  3594. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3595. }
  3596. // Read LRE
  3597. if (use_rle) {
  3598. pixel_data = new Uint8Array(pixel_total);
  3599. var c, count, i;
  3600. var localOffset = 0;
  3601. var pixels = new Uint8Array(pixel_size);
  3602. while (offset < pixel_total && localOffset < pixel_total) {
  3603. c = data[offset++];
  3604. count = (c & 0x7f) + 1;
  3605. // RLE pixels
  3606. if (c & 0x80) {
  3607. // Bind pixel tmp array
  3608. for (i = 0; i < pixel_size; ++i) {
  3609. pixels[i] = data[offset++];
  3610. }
  3611. // Copy pixel array
  3612. for (i = 0; i < count; ++i) {
  3613. pixel_data.set(pixels, localOffset + i * pixel_size);
  3614. }
  3615. localOffset += pixel_size * count;
  3616. }
  3617. else {
  3618. count *= pixel_size;
  3619. for (i = 0; i < count; ++i) {
  3620. pixel_data[localOffset + i] = data[offset++];
  3621. }
  3622. localOffset += count;
  3623. }
  3624. }
  3625. }
  3626. else {
  3627. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3628. }
  3629. // Load to texture
  3630. var x_start, y_start, x_step, y_step, y_end, x_end;
  3631. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3632. default:
  3633. case TGATools._ORIGIN_UL:
  3634. x_start = 0;
  3635. x_step = 1;
  3636. x_end = header.width;
  3637. y_start = 0;
  3638. y_step = 1;
  3639. y_end = header.height;
  3640. break;
  3641. case TGATools._ORIGIN_BL:
  3642. x_start = 0;
  3643. x_step = 1;
  3644. x_end = header.width;
  3645. y_start = header.height - 1;
  3646. y_step = -1;
  3647. y_end = -1;
  3648. break;
  3649. case TGATools._ORIGIN_UR:
  3650. x_start = header.width - 1;
  3651. x_step = -1;
  3652. x_end = -1;
  3653. y_start = 0;
  3654. y_step = 1;
  3655. y_end = header.height;
  3656. break;
  3657. case TGATools._ORIGIN_BR:
  3658. x_start = header.width - 1;
  3659. x_step = -1;
  3660. x_end = -1;
  3661. y_start = header.height - 1;
  3662. y_step = -1;
  3663. y_end = -1;
  3664. break;
  3665. }
  3666. // Load the specify method
  3667. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3668. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3669. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3670. };
  3671. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3672. var image = pixel_data, colormap = palettes;
  3673. var width = header.width, height = header.height;
  3674. var color, i = 0, x, y;
  3675. var imageData = new Uint8Array(width * height * 4);
  3676. for (y = y_start; y !== y_end; y += y_step) {
  3677. for (x = x_start; x !== x_end; x += x_step, i++) {
  3678. color = image[i];
  3679. imageData[(x + width * y) * 4 + 3] = 255;
  3680. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3681. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3682. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3683. }
  3684. }
  3685. return imageData;
  3686. };
  3687. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3688. var image = pixel_data;
  3689. var width = header.width, height = header.height;
  3690. var color, i = 0, x, y;
  3691. var imageData = new Uint8Array(width * height * 4);
  3692. for (y = y_start; y !== y_end; y += y_step) {
  3693. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3694. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3695. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3696. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3697. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3698. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3699. }
  3700. }
  3701. return imageData;
  3702. };
  3703. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3704. var image = pixel_data;
  3705. var width = header.width, height = header.height;
  3706. var i = 0, x, y;
  3707. var imageData = new Uint8Array(width * height * 4);
  3708. for (y = y_start; y !== y_end; y += y_step) {
  3709. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3710. imageData[(x + width * y) * 4 + 3] = 255;
  3711. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3712. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3713. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3714. }
  3715. }
  3716. return imageData;
  3717. };
  3718. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3719. var image = pixel_data;
  3720. var width = header.width, height = header.height;
  3721. var i = 0, x, y;
  3722. var imageData = new Uint8Array(width * height * 4);
  3723. for (y = y_start; y !== y_end; y += y_step) {
  3724. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3725. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3726. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3727. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3728. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3729. }
  3730. }
  3731. return imageData;
  3732. };
  3733. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3734. var image = pixel_data;
  3735. var width = header.width, height = header.height;
  3736. var color, i = 0, x, y;
  3737. var imageData = new Uint8Array(width * height * 4);
  3738. for (y = y_start; y !== y_end; y += y_step) {
  3739. for (x = x_start; x !== x_end; x += x_step, i++) {
  3740. color = image[i];
  3741. imageData[(x + width * y) * 4 + 0] = color;
  3742. imageData[(x + width * y) * 4 + 1] = color;
  3743. imageData[(x + width * y) * 4 + 2] = color;
  3744. imageData[(x + width * y) * 4 + 3] = 255;
  3745. }
  3746. }
  3747. return imageData;
  3748. };
  3749. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3750. var image = pixel_data;
  3751. var width = header.width, height = header.height;
  3752. var i = 0, x, y;
  3753. var imageData = new Uint8Array(width * height * 4);
  3754. for (y = y_start; y !== y_end; y += y_step) {
  3755. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3756. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3757. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3758. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3759. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3760. }
  3761. }
  3762. return imageData;
  3763. };
  3764. TGATools._TYPE_NO_DATA = 0;
  3765. TGATools._TYPE_INDEXED = 1;
  3766. TGATools._TYPE_RGB = 2;
  3767. TGATools._TYPE_GREY = 3;
  3768. TGATools._TYPE_RLE_INDEXED = 9;
  3769. TGATools._TYPE_RLE_RGB = 10;
  3770. TGATools._TYPE_RLE_GREY = 11;
  3771. TGATools._ORIGIN_MASK = 0x30;
  3772. TGATools._ORIGIN_SHIFT = 0x04;
  3773. TGATools._ORIGIN_BL = 0x00;
  3774. TGATools._ORIGIN_BR = 0x01;
  3775. TGATools._ORIGIN_UL = 0x02;
  3776. TGATools._ORIGIN_UR = 0x03;
  3777. return TGATools;
  3778. })();
  3779. Internals.TGATools = TGATools;
  3780. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3781. })(BABYLON || (BABYLON = {}));
  3782. //# sourceMappingURL=babylon.tools.tga.js.map
  3783. var BABYLON;
  3784. (function (BABYLON) {
  3785. var Internals;
  3786. (function (Internals) {
  3787. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3788. // All values and structures referenced from:
  3789. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3790. var DDS_MAGIC = 0x20534444;
  3791. 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;
  3792. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3793. 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;
  3794. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3795. function FourCCToInt32(value) {
  3796. return value.charCodeAt(0) +
  3797. (value.charCodeAt(1) << 8) +
  3798. (value.charCodeAt(2) << 16) +
  3799. (value.charCodeAt(3) << 24);
  3800. }
  3801. function Int32ToFourCC(value) {
  3802. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3803. }
  3804. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3805. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3806. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3807. var headerLengthInt = 31; // The header length in 32 bit ints
  3808. // Offsets into the header array
  3809. var off_magic = 0;
  3810. var off_size = 1;
  3811. var off_flags = 2;
  3812. var off_height = 3;
  3813. var off_width = 4;
  3814. var off_mipmapCount = 7;
  3815. var off_pfFlags = 20;
  3816. var off_pfFourCC = 21;
  3817. var off_RGBbpp = 22;
  3818. var off_RMask = 23;
  3819. var off_GMask = 24;
  3820. var off_BMask = 25;
  3821. var off_AMask = 26;
  3822. var off_caps1 = 27;
  3823. var off_caps2 = 28;
  3824. ;
  3825. var DDSTools = (function () {
  3826. function DDSTools() {
  3827. }
  3828. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3829. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3830. var mipmapCount = 1;
  3831. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3832. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3833. }
  3834. return {
  3835. width: header[off_width],
  3836. height: header[off_height],
  3837. mipmapCount: mipmapCount,
  3838. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3839. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3840. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3841. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3842. };
  3843. };
  3844. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3845. var byteArray = new Uint8Array(dataLength);
  3846. var srcData = new Uint8Array(arrayBuffer);
  3847. var index = 0;
  3848. for (var y = height - 1; y >= 0; y--) {
  3849. for (var x = 0; x < width; x++) {
  3850. var srcPos = dataOffset + (x + y * width) * 4;
  3851. byteArray[index + 2] = srcData[srcPos];
  3852. byteArray[index + 1] = srcData[srcPos + 1];
  3853. byteArray[index] = srcData[srcPos + 2];
  3854. byteArray[index + 3] = srcData[srcPos + 3];
  3855. index += 4;
  3856. }
  3857. }
  3858. return byteArray;
  3859. };
  3860. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3861. var byteArray = new Uint8Array(dataLength);
  3862. var srcData = new Uint8Array(arrayBuffer);
  3863. var index = 0;
  3864. for (var y = height - 1; y >= 0; y--) {
  3865. for (var x = 0; x < width; x++) {
  3866. var srcPos = dataOffset + (x + y * width) * 3;
  3867. byteArray[index + 2] = srcData[srcPos];
  3868. byteArray[index + 1] = srcData[srcPos + 1];
  3869. byteArray[index] = srcData[srcPos + 2];
  3870. index += 3;
  3871. }
  3872. }
  3873. return byteArray;
  3874. };
  3875. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3876. var byteArray = new Uint8Array(dataLength);
  3877. var srcData = new Uint8Array(arrayBuffer);
  3878. var index = 0;
  3879. for (var y = height - 1; y >= 0; y--) {
  3880. for (var x = 0; x < width; x++) {
  3881. var srcPos = dataOffset + (x + y * width);
  3882. byteArray[index] = srcData[srcPos];
  3883. index++;
  3884. }
  3885. }
  3886. return byteArray;
  3887. };
  3888. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3889. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3890. if (header[off_magic] != DDS_MAGIC) {
  3891. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3892. return;
  3893. }
  3894. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3895. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3896. return;
  3897. }
  3898. if (info.isFourCC) {
  3899. fourCC = header[off_pfFourCC];
  3900. switch (fourCC) {
  3901. case FOURCC_DXT1:
  3902. blockBytes = 8;
  3903. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3904. break;
  3905. case FOURCC_DXT3:
  3906. blockBytes = 16;
  3907. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3908. break;
  3909. case FOURCC_DXT5:
  3910. blockBytes = 16;
  3911. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3912. break;
  3913. default:
  3914. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3915. return;
  3916. }
  3917. }
  3918. mipmapCount = 1;
  3919. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3920. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3921. }
  3922. var bpp = header[off_RGBbpp];
  3923. for (var face = 0; face < faces; face++) {
  3924. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3925. width = header[off_width];
  3926. height = header[off_height];
  3927. dataOffset = header[off_size] + 4;
  3928. for (i = 0; i < mipmapCount; ++i) {
  3929. if (info.isRGB) {
  3930. if (bpp == 24) {
  3931. dataLength = width * height * 3;
  3932. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3933. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3934. }
  3935. else {
  3936. dataLength = width * height * 4;
  3937. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3938. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3939. }
  3940. }
  3941. else if (info.isLuminance) {
  3942. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3943. var unpaddedRowSize = width;
  3944. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3945. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3946. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3947. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3948. }
  3949. else {
  3950. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3951. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3952. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3953. }
  3954. dataOffset += dataLength;
  3955. width *= 0.5;
  3956. height *= 0.5;
  3957. width = Math.max(1.0, width);
  3958. height = Math.max(1.0, height);
  3959. }
  3960. }
  3961. };
  3962. return DDSTools;
  3963. })();
  3964. Internals.DDSTools = DDSTools;
  3965. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3966. })(BABYLON || (BABYLON = {}));
  3967. //# sourceMappingURL=babylon.tools.dds.js.map
  3968. var BABYLON;
  3969. (function (BABYLON) {
  3970. var SmartArray = (function () {
  3971. function SmartArray(capacity) {
  3972. this.length = 0;
  3973. this._duplicateId = 0;
  3974. this.data = new Array(capacity);
  3975. this._id = SmartArray._GlobalId++;
  3976. }
  3977. SmartArray.prototype.push = function (value) {
  3978. this.data[this.length++] = value;
  3979. if (this.length > this.data.length) {
  3980. this.data.length *= 2;
  3981. }
  3982. if (!value.__smartArrayFlags) {
  3983. value.__smartArrayFlags = {};
  3984. }
  3985. value.__smartArrayFlags[this._id] = this._duplicateId;
  3986. };
  3987. SmartArray.prototype.pushNoDuplicate = function (value) {
  3988. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3989. return;
  3990. }
  3991. this.push(value);
  3992. };
  3993. SmartArray.prototype.sort = function (compareFn) {
  3994. this.data.sort(compareFn);
  3995. };
  3996. SmartArray.prototype.reset = function () {
  3997. this.length = 0;
  3998. this._duplicateId++;
  3999. };
  4000. SmartArray.prototype.concat = function (array) {
  4001. if (array.length === 0) {
  4002. return;
  4003. }
  4004. if (this.length + array.length > this.data.length) {
  4005. this.data.length = (this.length + array.length) * 2;
  4006. }
  4007. for (var index = 0; index < array.length; index++) {
  4008. this.data[this.length++] = (array.data || array)[index];
  4009. }
  4010. };
  4011. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4012. if (array.length === 0) {
  4013. return;
  4014. }
  4015. if (this.length + array.length > this.data.length) {
  4016. this.data.length = (this.length + array.length) * 2;
  4017. }
  4018. for (var index = 0; index < array.length; index++) {
  4019. var item = (array.data || array)[index];
  4020. this.pushNoDuplicate(item);
  4021. }
  4022. };
  4023. SmartArray.prototype.indexOf = function (value) {
  4024. var position = this.data.indexOf(value);
  4025. if (position >= this.length) {
  4026. return -1;
  4027. }
  4028. return position;
  4029. };
  4030. // Statics
  4031. SmartArray._GlobalId = 0;
  4032. return SmartArray;
  4033. })();
  4034. BABYLON.SmartArray = SmartArray;
  4035. })(BABYLON || (BABYLON = {}));
  4036. //# sourceMappingURL=babylon.smartArray.js.map
  4037. var BABYLON;
  4038. (function (BABYLON) {
  4039. var SmartCollection = (function () {
  4040. function SmartCollection(capacity) {
  4041. if (capacity === void 0) { capacity = 10; }
  4042. this.count = 0;
  4043. this._initialCapacity = capacity;
  4044. this.items = {};
  4045. this._keys = new Array(this._initialCapacity);
  4046. }
  4047. SmartCollection.prototype.add = function (key, item) {
  4048. if (this.items[key] != undefined) {
  4049. return -1;
  4050. }
  4051. this.items[key] = item;
  4052. //literal keys are always strings, but we keep source type of key in _keys array
  4053. this._keys[this.count++] = key;
  4054. if (this.count > this._keys.length) {
  4055. this._keys.length *= 2;
  4056. }
  4057. return this.count;
  4058. };
  4059. SmartCollection.prototype.remove = function (key) {
  4060. if (this.items[key] == undefined) {
  4061. return -1;
  4062. }
  4063. return this.removeItemOfIndex(this.indexOf(key));
  4064. };
  4065. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4066. if (index < this.count && index > -1) {
  4067. delete this.items[this._keys[index]];
  4068. //here, shifting by hand is better optimised than .splice
  4069. while (index < this.count) {
  4070. this._keys[index] = this._keys[index + 1];
  4071. index++;
  4072. }
  4073. }
  4074. else {
  4075. return -1;
  4076. }
  4077. return --this.count;
  4078. };
  4079. SmartCollection.prototype.indexOf = function (key) {
  4080. for (var i = 0; i !== this.count; i++) {
  4081. if (this._keys[i] === key) {
  4082. return i;
  4083. }
  4084. }
  4085. return -1;
  4086. };
  4087. SmartCollection.prototype.item = function (key) {
  4088. return this.items[key];
  4089. };
  4090. SmartCollection.prototype.getAllKeys = function () {
  4091. if (this.count > 0) {
  4092. var keys = new Array(this.count);
  4093. for (var i = 0; i < this.count; i++) {
  4094. keys[i] = this._keys[i];
  4095. }
  4096. return keys;
  4097. }
  4098. else {
  4099. return undefined;
  4100. }
  4101. };
  4102. SmartCollection.prototype.getKeyByIndex = function (index) {
  4103. if (index < this.count && index > -1) {
  4104. return this._keys[index];
  4105. }
  4106. else {
  4107. return undefined;
  4108. }
  4109. };
  4110. SmartCollection.prototype.getItemByIndex = function (index) {
  4111. if (index < this.count && index > -1) {
  4112. return this.items[this._keys[index]];
  4113. }
  4114. else {
  4115. return undefined;
  4116. }
  4117. };
  4118. SmartCollection.prototype.empty = function () {
  4119. if (this.count > 0) {
  4120. this.count = 0;
  4121. this.items = {};
  4122. this._keys = new Array(this._initialCapacity);
  4123. }
  4124. };
  4125. SmartCollection.prototype.forEach = function (block) {
  4126. var key;
  4127. for (key in this.items) {
  4128. if (this.items.hasOwnProperty(key)) {
  4129. block(this.items[key]);
  4130. }
  4131. }
  4132. };
  4133. return SmartCollection;
  4134. })();
  4135. BABYLON.SmartCollection = SmartCollection;
  4136. })(BABYLON || (BABYLON = {}));
  4137. //# sourceMappingURL=babylon.smartCollection.js.map
  4138. var BABYLON;
  4139. (function (BABYLON) {
  4140. // Screenshots
  4141. var screenshotCanvas;
  4142. var cloneValue = function (source, destinationObject) {
  4143. if (!source)
  4144. return null;
  4145. if (source instanceof BABYLON.Mesh) {
  4146. return null;
  4147. }
  4148. if (source instanceof BABYLON.SubMesh) {
  4149. return source.clone(destinationObject);
  4150. }
  4151. else if (source.clone) {
  4152. return source.clone();
  4153. }
  4154. return null;
  4155. };
  4156. var Tools = (function () {
  4157. function Tools() {
  4158. }
  4159. Tools.SetImmediate = function (action) {
  4160. if (window.setImmediate) {
  4161. window.setImmediate(action);
  4162. }
  4163. else {
  4164. setTimeout(action, 1);
  4165. }
  4166. };
  4167. Tools.IsExponantOfTwo = function (value) {
  4168. var count = 1;
  4169. do {
  4170. count *= 2;
  4171. } while (count < value);
  4172. return count === value;
  4173. };
  4174. Tools.GetExponantOfTwo = function (value, max) {
  4175. var count = 1;
  4176. do {
  4177. count *= 2;
  4178. } while (count < value);
  4179. if (count > max)
  4180. count = max;
  4181. return count;
  4182. };
  4183. Tools.GetFilename = function (path) {
  4184. var index = path.lastIndexOf("/");
  4185. if (index < 0)
  4186. return path;
  4187. return path.substring(index + 1);
  4188. };
  4189. Tools.GetDOMTextContent = function (element) {
  4190. var result = "";
  4191. var child = element.firstChild;
  4192. while (child) {
  4193. if (child.nodeType === 3) {
  4194. result += child.textContent;
  4195. }
  4196. child = child.nextSibling;
  4197. }
  4198. return result;
  4199. };
  4200. Tools.ToDegrees = function (angle) {
  4201. return angle * 180 / Math.PI;
  4202. };
  4203. Tools.ToRadians = function (angle) {
  4204. return angle * Math.PI / 180;
  4205. };
  4206. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4207. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4208. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4209. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4210. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4211. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4212. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4213. }
  4214. return {
  4215. minimum: minimum,
  4216. maximum: maximum
  4217. };
  4218. };
  4219. Tools.ExtractMinAndMax = function (positions, start, count) {
  4220. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4221. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4222. for (var index = start; index < start + count; index++) {
  4223. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4224. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4225. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4226. }
  4227. return {
  4228. minimum: minimum,
  4229. maximum: maximum
  4230. };
  4231. };
  4232. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4233. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4234. return undefined;
  4235. return Array.isArray(obj) ? obj : [obj];
  4236. };
  4237. // Misc.
  4238. Tools.GetPointerPrefix = function () {
  4239. var eventPrefix = "pointer";
  4240. // Check if hand.js is referenced or if the browser natively supports pointer events
  4241. if (!navigator.pointerEnabled) {
  4242. eventPrefix = "mouse";
  4243. }
  4244. return eventPrefix;
  4245. };
  4246. Tools.QueueNewFrame = function (func) {
  4247. if (window.requestAnimationFrame)
  4248. window.requestAnimationFrame(func);
  4249. else if (window.msRequestAnimationFrame)
  4250. window.msRequestAnimationFrame(func);
  4251. else if (window.webkitRequestAnimationFrame)
  4252. window.webkitRequestAnimationFrame(func);
  4253. else if (window.mozRequestAnimationFrame)
  4254. window.mozRequestAnimationFrame(func);
  4255. else if (window.oRequestAnimationFrame)
  4256. window.oRequestAnimationFrame(func);
  4257. else {
  4258. window.setTimeout(func, 16);
  4259. }
  4260. };
  4261. Tools.RequestFullscreen = function (element) {
  4262. if (element.requestFullscreen)
  4263. element.requestFullscreen();
  4264. else if (element.msRequestFullscreen)
  4265. element.msRequestFullscreen();
  4266. else if (element.webkitRequestFullscreen)
  4267. element.webkitRequestFullscreen();
  4268. else if (element.mozRequestFullScreen)
  4269. element.mozRequestFullScreen();
  4270. };
  4271. Tools.ExitFullscreen = function () {
  4272. if (document.exitFullscreen) {
  4273. document.exitFullscreen();
  4274. }
  4275. else if (document.mozCancelFullScreen) {
  4276. document.mozCancelFullScreen();
  4277. }
  4278. else if (document.webkitCancelFullScreen) {
  4279. document.webkitCancelFullScreen();
  4280. }
  4281. else if (document.msCancelFullScreen) {
  4282. document.msCancelFullScreen();
  4283. }
  4284. };
  4285. // External files
  4286. Tools.CleanUrl = function (url) {
  4287. url = url.replace(/#/mg, "%23");
  4288. return url;
  4289. };
  4290. Tools.LoadImage = function (url, onload, onerror, database) {
  4291. url = Tools.CleanUrl(url);
  4292. var img = new Image();
  4293. if (url.substr(0, 5) !== "data:")
  4294. img.crossOrigin = 'anonymous';
  4295. img.onload = function () {
  4296. onload(img);
  4297. };
  4298. img.onerror = function (err) {
  4299. onerror(img, err);
  4300. };
  4301. var noIndexedDB = function () {
  4302. img.src = url;
  4303. };
  4304. var loadFromIndexedDB = function () {
  4305. database.loadImageFromDB(url, img);
  4306. };
  4307. //ANY database to do!
  4308. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4309. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4310. }
  4311. else {
  4312. if (url.indexOf("file:") === -1) {
  4313. noIndexedDB();
  4314. }
  4315. else {
  4316. try {
  4317. var textureName = url.substring(5);
  4318. var blobURL;
  4319. try {
  4320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4321. }
  4322. catch (ex) {
  4323. // Chrome doesn't support oneTimeOnly parameter
  4324. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4325. }
  4326. img.src = blobURL;
  4327. }
  4328. catch (e) {
  4329. Tools.Log("Error while trying to load texture: " + textureName);
  4330. img.src = null;
  4331. }
  4332. }
  4333. }
  4334. return img;
  4335. };
  4336. //ANY
  4337. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4338. url = Tools.CleanUrl(url);
  4339. var noIndexedDB = function () {
  4340. var request = new XMLHttpRequest();
  4341. var loadUrl = Tools.BaseUrl + url;
  4342. request.open('GET', loadUrl, true);
  4343. if (useArrayBuffer) {
  4344. request.responseType = "arraybuffer";
  4345. }
  4346. request.onprogress = progressCallBack;
  4347. request.onreadystatechange = function () {
  4348. if (request.readyState === 4) {
  4349. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4350. callback(!useArrayBuffer ? request.responseText : request.response);
  4351. }
  4352. else {
  4353. if (onError) {
  4354. onError();
  4355. }
  4356. else {
  4357. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4358. }
  4359. }
  4360. }
  4361. };
  4362. request.send(null);
  4363. };
  4364. var loadFromIndexedDB = function () {
  4365. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4366. };
  4367. if (url.indexOf("file:") !== -1) {
  4368. var fileName = url.substring(5);
  4369. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4370. }
  4371. else {
  4372. // Caching all files
  4373. if (database && database.enableSceneOffline) {
  4374. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4375. }
  4376. else {
  4377. noIndexedDB();
  4378. }
  4379. }
  4380. };
  4381. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4382. var reader = new FileReader();
  4383. reader.onload = function (e) {
  4384. //target doesn't have result from ts 1.3
  4385. callback(e.target['result']);
  4386. };
  4387. reader.onprogress = progressCallback;
  4388. reader.readAsDataURL(fileToLoad);
  4389. };
  4390. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4391. var reader = new FileReader();
  4392. reader.onerror = function (e) {
  4393. Tools.Log("Error while reading file: " + fileToLoad.name);
  4394. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4395. };
  4396. reader.onload = function (e) {
  4397. //target doesn't have result from ts 1.3
  4398. callback(e.target['result']);
  4399. };
  4400. reader.onprogress = progressCallBack;
  4401. if (!useArrayBuffer) {
  4402. // Asynchronous read
  4403. reader.readAsText(fileToLoad);
  4404. }
  4405. else {
  4406. reader.readAsArrayBuffer(fileToLoad);
  4407. }
  4408. };
  4409. // Misc.
  4410. Tools.Clamp = function (value, min, max) {
  4411. if (min === void 0) { min = 0; }
  4412. if (max === void 0) { max = 1; }
  4413. return Math.min(max, Math.max(min, value));
  4414. };
  4415. // Returns -1 when value is a negative number and
  4416. // +1 when value is a positive number.
  4417. Tools.Sign = function (value) {
  4418. value = +value; // convert to a number
  4419. if (value === 0 || isNaN(value))
  4420. return value;
  4421. return value > 0 ? 1 : -1;
  4422. };
  4423. Tools.Format = function (value, decimals) {
  4424. if (decimals === void 0) { decimals = 2; }
  4425. return value.toFixed(decimals);
  4426. };
  4427. Tools.CheckExtends = function (v, min, max) {
  4428. if (v.x < min.x)
  4429. min.x = v.x;
  4430. if (v.y < min.y)
  4431. min.y = v.y;
  4432. if (v.z < min.z)
  4433. min.z = v.z;
  4434. if (v.x > max.x)
  4435. max.x = v.x;
  4436. if (v.y > max.y)
  4437. max.y = v.y;
  4438. if (v.z > max.z)
  4439. max.z = v.z;
  4440. };
  4441. Tools.WithinEpsilon = function (a, b, epsilon) {
  4442. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4443. var num = a - b;
  4444. return -epsilon <= num && num <= epsilon;
  4445. };
  4446. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4447. for (var prop in source) {
  4448. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4449. continue;
  4450. }
  4451. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4452. continue;
  4453. }
  4454. var sourceValue = source[prop];
  4455. var typeOfSourceValue = typeof sourceValue;
  4456. if (typeOfSourceValue === "function") {
  4457. continue;
  4458. }
  4459. if (typeOfSourceValue === "object") {
  4460. if (sourceValue instanceof Array) {
  4461. destination[prop] = [];
  4462. if (sourceValue.length > 0) {
  4463. if (typeof sourceValue[0] == "object") {
  4464. for (var index = 0; index < sourceValue.length; index++) {
  4465. var clonedValue = cloneValue(sourceValue[index], destination);
  4466. if (destination[prop].indexOf(clonedValue) === -1) {
  4467. destination[prop].push(clonedValue);
  4468. }
  4469. }
  4470. }
  4471. else {
  4472. destination[prop] = sourceValue.slice(0);
  4473. }
  4474. }
  4475. }
  4476. else {
  4477. destination[prop] = cloneValue(sourceValue, destination);
  4478. }
  4479. }
  4480. else {
  4481. destination[prop] = sourceValue;
  4482. }
  4483. }
  4484. };
  4485. Tools.IsEmpty = function (obj) {
  4486. for (var i in obj) {
  4487. return false;
  4488. }
  4489. return true;
  4490. };
  4491. Tools.RegisterTopRootEvents = function (events) {
  4492. for (var index = 0; index < events.length; index++) {
  4493. var event = events[index];
  4494. window.addEventListener(event.name, event.handler, false);
  4495. try {
  4496. if (window.parent) {
  4497. window.parent.addEventListener(event.name, event.handler, false);
  4498. }
  4499. }
  4500. catch (e) {
  4501. }
  4502. }
  4503. };
  4504. Tools.UnregisterTopRootEvents = function (events) {
  4505. for (var index = 0; index < events.length; index++) {
  4506. var event = events[index];
  4507. window.removeEventListener(event.name, event.handler);
  4508. try {
  4509. if (window.parent) {
  4510. window.parent.removeEventListener(event.name, event.handler);
  4511. }
  4512. }
  4513. catch (e) {
  4514. }
  4515. }
  4516. };
  4517. Tools.DumpFramebuffer = function (width, height, engine) {
  4518. // Read the contents of the framebuffer
  4519. var numberOfChannelsByLine = width * 4;
  4520. var halfHeight = height / 2;
  4521. //Reading datas from WebGL
  4522. var data = engine.readPixels(0, 0, width, height);
  4523. //To flip image on Y axis.
  4524. for (var i = 0; i < halfHeight; i++) {
  4525. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4526. var currentCell = j + i * numberOfChannelsByLine;
  4527. var targetLine = height - i - 1;
  4528. var targetCell = j + targetLine * numberOfChannelsByLine;
  4529. var temp = data[currentCell];
  4530. data[currentCell] = data[targetCell];
  4531. data[targetCell] = temp;
  4532. }
  4533. }
  4534. // Create a 2D canvas to store the result
  4535. if (!screenshotCanvas) {
  4536. screenshotCanvas = document.createElement('canvas');
  4537. }
  4538. screenshotCanvas.width = width;
  4539. screenshotCanvas.height = height;
  4540. var context = screenshotCanvas.getContext('2d');
  4541. // Copy the pixels to a 2D canvas
  4542. var imageData = context.createImageData(width, height);
  4543. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4544. var castData = imageData.data;
  4545. castData.set(data);
  4546. context.putImageData(imageData, 0, 0);
  4547. var base64Image = screenshotCanvas.toDataURL();
  4548. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4549. if (("download" in document.createElement("a"))) {
  4550. var a = window.document.createElement("a");
  4551. a.href = base64Image;
  4552. var date = new Date();
  4553. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4554. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4555. window.document.body.appendChild(a);
  4556. a.addEventListener("click", function () {
  4557. a.parentElement.removeChild(a);
  4558. });
  4559. a.click();
  4560. }
  4561. else {
  4562. var newWindow = window.open("");
  4563. var img = newWindow.document.createElement("img");
  4564. img.src = base64Image;
  4565. newWindow.document.body.appendChild(img);
  4566. }
  4567. };
  4568. Tools.CreateScreenshot = function (engine, camera, size) {
  4569. var width;
  4570. var height;
  4571. var scene = camera.getScene();
  4572. var previousCamera = null;
  4573. if (scene.activeCamera !== camera) {
  4574. previousCamera = scene.activeCamera;
  4575. scene.activeCamera = camera;
  4576. }
  4577. //If a precision value is specified
  4578. if (size.precision) {
  4579. width = Math.round(engine.getRenderWidth() * size.precision);
  4580. height = Math.round(width / engine.getAspectRatio(camera));
  4581. size = { width: width, height: height };
  4582. }
  4583. else if (size.width && size.height) {
  4584. width = size.width;
  4585. height = size.height;
  4586. }
  4587. else if (size.width && !size.height) {
  4588. width = size.width;
  4589. height = Math.round(width / engine.getAspectRatio(camera));
  4590. size = { width: width, height: height };
  4591. }
  4592. else if (size.height && !size.width) {
  4593. height = size.height;
  4594. width = Math.round(height * engine.getAspectRatio(camera));
  4595. size = { width: width, height: height };
  4596. }
  4597. else if (!isNaN(size)) {
  4598. height = size;
  4599. width = size;
  4600. }
  4601. else {
  4602. Tools.Error("Invalid 'size' parameter !");
  4603. return;
  4604. }
  4605. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4606. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4607. texture.renderList = scene.meshes;
  4608. texture.onAfterRender = function () {
  4609. Tools.DumpFramebuffer(width, height, engine);
  4610. };
  4611. scene.incrementRenderId();
  4612. texture.render(true);
  4613. texture.dispose();
  4614. if (previousCamera) {
  4615. scene.activeCamera = previousCamera;
  4616. }
  4617. };
  4618. // XHR response validator for local file scenario
  4619. Tools.ValidateXHRData = function (xhr, dataType) {
  4620. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4621. if (dataType === void 0) { dataType = 7; }
  4622. try {
  4623. if (dataType & 1) {
  4624. if (xhr.responseText && xhr.responseText.length > 0) {
  4625. return true;
  4626. }
  4627. else if (dataType === 1) {
  4628. return false;
  4629. }
  4630. }
  4631. if (dataType & 2) {
  4632. // Check header width and height since there is no "TGA" magic number
  4633. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4634. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4635. return true;
  4636. }
  4637. else if (dataType === 2) {
  4638. return false;
  4639. }
  4640. }
  4641. if (dataType & 4) {
  4642. // Check for the "DDS" magic number
  4643. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4644. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4645. return true;
  4646. }
  4647. else {
  4648. return false;
  4649. }
  4650. }
  4651. }
  4652. catch (e) {
  4653. }
  4654. return false;
  4655. };
  4656. Object.defineProperty(Tools, "NoneLogLevel", {
  4657. get: function () {
  4658. return Tools._NoneLogLevel;
  4659. },
  4660. enumerable: true,
  4661. configurable: true
  4662. });
  4663. Object.defineProperty(Tools, "MessageLogLevel", {
  4664. get: function () {
  4665. return Tools._MessageLogLevel;
  4666. },
  4667. enumerable: true,
  4668. configurable: true
  4669. });
  4670. Object.defineProperty(Tools, "WarningLogLevel", {
  4671. get: function () {
  4672. return Tools._WarningLogLevel;
  4673. },
  4674. enumerable: true,
  4675. configurable: true
  4676. });
  4677. Object.defineProperty(Tools, "ErrorLogLevel", {
  4678. get: function () {
  4679. return Tools._ErrorLogLevel;
  4680. },
  4681. enumerable: true,
  4682. configurable: true
  4683. });
  4684. Object.defineProperty(Tools, "AllLogLevel", {
  4685. get: function () {
  4686. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4687. },
  4688. enumerable: true,
  4689. configurable: true
  4690. });
  4691. Tools._AddLogEntry = function (entry) {
  4692. Tools._LogCache = entry + Tools._LogCache;
  4693. if (Tools.OnNewCacheEntry) {
  4694. Tools.OnNewCacheEntry(entry);
  4695. }
  4696. };
  4697. Tools._FormatMessage = function (message) {
  4698. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4699. var date = new Date();
  4700. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4701. };
  4702. Tools._LogDisabled = function (message) {
  4703. // nothing to do
  4704. };
  4705. Tools._LogEnabled = function (message) {
  4706. var formattedMessage = Tools._FormatMessage(message);
  4707. console.log("BJS - " + formattedMessage);
  4708. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4709. Tools._AddLogEntry(entry);
  4710. };
  4711. Tools._WarnDisabled = function (message) {
  4712. // nothing to do
  4713. };
  4714. Tools._WarnEnabled = function (message) {
  4715. var formattedMessage = Tools._FormatMessage(message);
  4716. console.warn("BJS - " + formattedMessage);
  4717. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4718. Tools._AddLogEntry(entry);
  4719. };
  4720. Tools._ErrorDisabled = function (message) {
  4721. // nothing to do
  4722. };
  4723. Tools._ErrorEnabled = function (message) {
  4724. var formattedMessage = Tools._FormatMessage(message);
  4725. console.error("BJS - " + formattedMessage);
  4726. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4727. Tools._AddLogEntry(entry);
  4728. };
  4729. Object.defineProperty(Tools, "LogCache", {
  4730. get: function () {
  4731. return Tools._LogCache;
  4732. },
  4733. enumerable: true,
  4734. configurable: true
  4735. });
  4736. Object.defineProperty(Tools, "LogLevels", {
  4737. set: function (level) {
  4738. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4739. Tools.Log = Tools._LogEnabled;
  4740. }
  4741. else {
  4742. Tools.Log = Tools._LogDisabled;
  4743. }
  4744. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4745. Tools.Warn = Tools._WarnEnabled;
  4746. }
  4747. else {
  4748. Tools.Warn = Tools._WarnDisabled;
  4749. }
  4750. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4751. Tools.Error = Tools._ErrorEnabled;
  4752. }
  4753. else {
  4754. Tools.Error = Tools._ErrorDisabled;
  4755. }
  4756. },
  4757. enumerable: true,
  4758. configurable: true
  4759. });
  4760. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4761. get: function () {
  4762. return Tools._PerformanceNoneLogLevel;
  4763. },
  4764. enumerable: true,
  4765. configurable: true
  4766. });
  4767. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4768. get: function () {
  4769. return Tools._PerformanceUserMarkLogLevel;
  4770. },
  4771. enumerable: true,
  4772. configurable: true
  4773. });
  4774. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4775. get: function () {
  4776. return Tools._PerformanceConsoleLogLevel;
  4777. },
  4778. enumerable: true,
  4779. configurable: true
  4780. });
  4781. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4782. set: function (level) {
  4783. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4784. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4785. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4786. return;
  4787. }
  4788. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4789. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4790. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4791. return;
  4792. }
  4793. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4794. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4795. },
  4796. enumerable: true,
  4797. configurable: true
  4798. });
  4799. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4800. };
  4801. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4802. };
  4803. Tools._StartUserMark = function (counterName, condition) {
  4804. if (condition === void 0) { condition = true; }
  4805. if (!condition || !Tools._performance.mark) {
  4806. return;
  4807. }
  4808. Tools._performance.mark(counterName + "-Begin");
  4809. };
  4810. Tools._EndUserMark = function (counterName, condition) {
  4811. if (condition === void 0) { condition = true; }
  4812. if (!condition || !Tools._performance.mark) {
  4813. return;
  4814. }
  4815. Tools._performance.mark(counterName + "-End");
  4816. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4817. };
  4818. Tools._StartPerformanceConsole = function (counterName, condition) {
  4819. if (condition === void 0) { condition = true; }
  4820. if (!condition) {
  4821. return;
  4822. }
  4823. Tools._StartUserMark(counterName, condition);
  4824. if (console.time) {
  4825. console.time(counterName);
  4826. }
  4827. };
  4828. Tools._EndPerformanceConsole = function (counterName, condition) {
  4829. if (condition === void 0) { condition = true; }
  4830. if (!condition) {
  4831. return;
  4832. }
  4833. Tools._EndUserMark(counterName, condition);
  4834. if (console.time) {
  4835. console.timeEnd(counterName);
  4836. }
  4837. };
  4838. Object.defineProperty(Tools, "Now", {
  4839. get: function () {
  4840. if (window.performance && window.performance.now) {
  4841. return window.performance.now();
  4842. }
  4843. return new Date().getTime();
  4844. },
  4845. enumerable: true,
  4846. configurable: true
  4847. });
  4848. // Deprecated
  4849. Tools.GetFps = function () {
  4850. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4851. return 0;
  4852. };
  4853. Tools.BaseUrl = "";
  4854. // Logs
  4855. Tools._NoneLogLevel = 0;
  4856. Tools._MessageLogLevel = 1;
  4857. Tools._WarningLogLevel = 2;
  4858. Tools._ErrorLogLevel = 4;
  4859. Tools._LogCache = "";
  4860. Tools.Log = Tools._LogEnabled;
  4861. Tools.Warn = Tools._WarnEnabled;
  4862. Tools.Error = Tools._ErrorEnabled;
  4863. // Performances
  4864. Tools._PerformanceNoneLogLevel = 0;
  4865. Tools._PerformanceUserMarkLogLevel = 1;
  4866. Tools._PerformanceConsoleLogLevel = 2;
  4867. Tools._performance = window.performance;
  4868. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4869. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4870. return Tools;
  4871. })();
  4872. BABYLON.Tools = Tools;
  4873. /**
  4874. * An implementation of a loop for asynchronous functions.
  4875. */
  4876. var AsyncLoop = (function () {
  4877. /**
  4878. * Constroctor.
  4879. * @param iterations the number of iterations.
  4880. * @param _fn the function to run each iteration
  4881. * @param _successCallback the callback that will be called upon succesful execution
  4882. * @param offset starting offset.
  4883. */
  4884. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4885. if (offset === void 0) { offset = 0; }
  4886. this.iterations = iterations;
  4887. this._fn = _fn;
  4888. this._successCallback = _successCallback;
  4889. this.index = offset - 1;
  4890. this._done = false;
  4891. }
  4892. /**
  4893. * Execute the next iteration. Must be called after the last iteration was finished.
  4894. */
  4895. AsyncLoop.prototype.executeNext = function () {
  4896. if (!this._done) {
  4897. if (this.index + 1 < this.iterations) {
  4898. ++this.index;
  4899. this._fn(this);
  4900. }
  4901. else {
  4902. this.breakLoop();
  4903. }
  4904. }
  4905. };
  4906. /**
  4907. * Break the loop and run the success callback.
  4908. */
  4909. AsyncLoop.prototype.breakLoop = function () {
  4910. this._done = true;
  4911. this._successCallback();
  4912. };
  4913. /**
  4914. * Helper function
  4915. */
  4916. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4917. if (offset === void 0) { offset = 0; }
  4918. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4919. loop.executeNext();
  4920. return loop;
  4921. };
  4922. /**
  4923. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4924. * @param iterations total number of iterations
  4925. * @param syncedIterations number of synchronous iterations in each async iteration.
  4926. * @param fn the function to call each iteration.
  4927. * @param callback a success call back that will be called when iterating stops.
  4928. * @param breakFunction a break condition (optional)
  4929. * @param timeout timeout settings for the setTimeout function. default - 0.
  4930. * @constructor
  4931. */
  4932. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4933. if (timeout === void 0) { timeout = 0; }
  4934. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4935. if (breakFunction && breakFunction())
  4936. loop.breakLoop();
  4937. else {
  4938. setTimeout(function () {
  4939. for (var i = 0; i < syncedIterations; ++i) {
  4940. var iteration = (loop.index * syncedIterations) + i;
  4941. if (iteration >= iterations)
  4942. break;
  4943. fn(iteration);
  4944. if (breakFunction && breakFunction()) {
  4945. loop.breakLoop();
  4946. break;
  4947. }
  4948. }
  4949. loop.executeNext();
  4950. }, timeout);
  4951. }
  4952. }, callback);
  4953. };
  4954. return AsyncLoop;
  4955. })();
  4956. BABYLON.AsyncLoop = AsyncLoop;
  4957. })(BABYLON || (BABYLON = {}));
  4958. //# sourceMappingURL=babylon.tools.js.map
  4959. var BABYLON;
  4960. (function (BABYLON) {
  4961. var _DepthCullingState = (function () {
  4962. function _DepthCullingState() {
  4963. this._isDepthTestDirty = false;
  4964. this._isDepthMaskDirty = false;
  4965. this._isDepthFuncDirty = false;
  4966. this._isCullFaceDirty = false;
  4967. this._isCullDirty = false;
  4968. this._isZOffsetDirty = false;
  4969. }
  4970. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4971. get: function () {
  4972. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4973. },
  4974. enumerable: true,
  4975. configurable: true
  4976. });
  4977. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4978. get: function () {
  4979. return this._zOffset;
  4980. },
  4981. set: function (value) {
  4982. if (this._zOffset === value) {
  4983. return;
  4984. }
  4985. this._zOffset = value;
  4986. this._isZOffsetDirty = true;
  4987. },
  4988. enumerable: true,
  4989. configurable: true
  4990. });
  4991. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4992. get: function () {
  4993. return this._cullFace;
  4994. },
  4995. set: function (value) {
  4996. if (this._cullFace === value) {
  4997. return;
  4998. }
  4999. this._cullFace = value;
  5000. this._isCullFaceDirty = true;
  5001. },
  5002. enumerable: true,
  5003. configurable: true
  5004. });
  5005. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5006. get: function () {
  5007. return this._cull;
  5008. },
  5009. set: function (value) {
  5010. if (this._cull === value) {
  5011. return;
  5012. }
  5013. this._cull = value;
  5014. this._isCullDirty = true;
  5015. },
  5016. enumerable: true,
  5017. configurable: true
  5018. });
  5019. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5020. get: function () {
  5021. return this._depthFunc;
  5022. },
  5023. set: function (value) {
  5024. if (this._depthFunc === value) {
  5025. return;
  5026. }
  5027. this._depthFunc = value;
  5028. this._isDepthFuncDirty = true;
  5029. },
  5030. enumerable: true,
  5031. configurable: true
  5032. });
  5033. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5034. get: function () {
  5035. return this._depthMask;
  5036. },
  5037. set: function (value) {
  5038. if (this._depthMask === value) {
  5039. return;
  5040. }
  5041. this._depthMask = value;
  5042. this._isDepthMaskDirty = true;
  5043. },
  5044. enumerable: true,
  5045. configurable: true
  5046. });
  5047. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5048. get: function () {
  5049. return this._depthTest;
  5050. },
  5051. set: function (value) {
  5052. if (this._depthTest === value) {
  5053. return;
  5054. }
  5055. this._depthTest = value;
  5056. this._isDepthTestDirty = true;
  5057. },
  5058. enumerable: true,
  5059. configurable: true
  5060. });
  5061. _DepthCullingState.prototype.reset = function () {
  5062. this._depthMask = true;
  5063. this._depthTest = true;
  5064. this._depthFunc = null;
  5065. this._cull = null;
  5066. this._cullFace = null;
  5067. this._zOffset = 0;
  5068. this._isDepthTestDirty = true;
  5069. this._isDepthMaskDirty = true;
  5070. this._isDepthFuncDirty = false;
  5071. this._isCullFaceDirty = false;
  5072. this._isCullDirty = false;
  5073. this._isZOffsetDirty = false;
  5074. };
  5075. _DepthCullingState.prototype.apply = function (gl) {
  5076. if (!this.isDirty) {
  5077. return;
  5078. }
  5079. // Cull
  5080. if (this._isCullDirty) {
  5081. if (this.cull) {
  5082. gl.enable(gl.CULL_FACE);
  5083. }
  5084. else {
  5085. gl.disable(gl.CULL_FACE);
  5086. }
  5087. this._isCullDirty = false;
  5088. }
  5089. // Cull face
  5090. if (this._isCullFaceDirty) {
  5091. gl.cullFace(this.cullFace);
  5092. this._isCullFaceDirty = false;
  5093. }
  5094. // Depth mask
  5095. if (this._isDepthMaskDirty) {
  5096. gl.depthMask(this.depthMask);
  5097. this._isDepthMaskDirty = false;
  5098. }
  5099. // Depth test
  5100. if (this._isDepthTestDirty) {
  5101. if (this.depthTest) {
  5102. gl.enable(gl.DEPTH_TEST);
  5103. }
  5104. else {
  5105. gl.disable(gl.DEPTH_TEST);
  5106. }
  5107. this._isDepthTestDirty = false;
  5108. }
  5109. // Depth func
  5110. if (this._isDepthFuncDirty) {
  5111. gl.depthFunc(this.depthFunc);
  5112. this._isDepthFuncDirty = false;
  5113. }
  5114. // zOffset
  5115. if (this._isZOffsetDirty) {
  5116. if (this.zOffset) {
  5117. gl.enable(gl.POLYGON_OFFSET_FILL);
  5118. gl.polygonOffset(this.zOffset, 0);
  5119. }
  5120. else {
  5121. gl.disable(gl.POLYGON_OFFSET_FILL);
  5122. }
  5123. this._isZOffsetDirty = false;
  5124. }
  5125. };
  5126. return _DepthCullingState;
  5127. })();
  5128. BABYLON._DepthCullingState = _DepthCullingState;
  5129. var _AlphaState = (function () {
  5130. function _AlphaState() {
  5131. this._isAlphaBlendDirty = false;
  5132. this._isBlendFunctionParametersDirty = false;
  5133. this._alphaBlend = false;
  5134. this._blendFunctionParameters = new Array(4);
  5135. }
  5136. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5137. get: function () {
  5138. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5139. },
  5140. enumerable: true,
  5141. configurable: true
  5142. });
  5143. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5144. get: function () {
  5145. return this._alphaBlend;
  5146. },
  5147. set: function (value) {
  5148. if (this._alphaBlend === value) {
  5149. return;
  5150. }
  5151. this._alphaBlend = value;
  5152. this._isAlphaBlendDirty = true;
  5153. },
  5154. enumerable: true,
  5155. configurable: true
  5156. });
  5157. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5158. if (this._blendFunctionParameters[0] === value0 &&
  5159. this._blendFunctionParameters[1] === value1 &&
  5160. this._blendFunctionParameters[2] === value2 &&
  5161. this._blendFunctionParameters[3] === value3) {
  5162. return;
  5163. }
  5164. this._blendFunctionParameters[0] = value0;
  5165. this._blendFunctionParameters[1] = value1;
  5166. this._blendFunctionParameters[2] = value2;
  5167. this._blendFunctionParameters[3] = value3;
  5168. this._isBlendFunctionParametersDirty = true;
  5169. };
  5170. _AlphaState.prototype.reset = function () {
  5171. this._alphaBlend = false;
  5172. this._blendFunctionParameters[0] = null;
  5173. this._blendFunctionParameters[1] = null;
  5174. this._blendFunctionParameters[2] = null;
  5175. this._blendFunctionParameters[3] = null;
  5176. this._isAlphaBlendDirty = true;
  5177. this._isBlendFunctionParametersDirty = false;
  5178. };
  5179. _AlphaState.prototype.apply = function (gl) {
  5180. if (!this.isDirty) {
  5181. return;
  5182. }
  5183. // Alpha blend
  5184. if (this._isAlphaBlendDirty) {
  5185. if (this._alphaBlend) {
  5186. gl.enable(gl.BLEND);
  5187. }
  5188. else {
  5189. gl.disable(gl.BLEND);
  5190. }
  5191. this._isAlphaBlendDirty = false;
  5192. }
  5193. // Alpha function
  5194. if (this._isBlendFunctionParametersDirty) {
  5195. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5196. this._isBlendFunctionParametersDirty = false;
  5197. }
  5198. };
  5199. return _AlphaState;
  5200. })();
  5201. BABYLON._AlphaState = _AlphaState;
  5202. var compileShader = function (gl, source, type, defines) {
  5203. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5204. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5205. gl.compileShader(shader);
  5206. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5207. throw new Error(gl.getShaderInfoLog(shader));
  5208. }
  5209. return shader;
  5210. };
  5211. var getWebGLTextureType = function (gl, type) {
  5212. var textureType = gl.UNSIGNED_BYTE;
  5213. if (type === Engine.TEXTURETYPE_FLOAT)
  5214. textureType = gl.FLOAT;
  5215. return textureType;
  5216. };
  5217. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5218. var magFilter = gl.NEAREST;
  5219. var minFilter = gl.NEAREST;
  5220. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5221. magFilter = gl.LINEAR;
  5222. if (generateMipMaps) {
  5223. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5224. }
  5225. else {
  5226. minFilter = gl.LINEAR;
  5227. }
  5228. }
  5229. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5230. magFilter = gl.LINEAR;
  5231. if (generateMipMaps) {
  5232. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5233. }
  5234. else {
  5235. minFilter = gl.LINEAR;
  5236. }
  5237. }
  5238. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5239. magFilter = gl.NEAREST;
  5240. if (generateMipMaps) {
  5241. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5242. }
  5243. else {
  5244. minFilter = gl.NEAREST;
  5245. }
  5246. }
  5247. return {
  5248. min: minFilter,
  5249. mag: magFilter
  5250. };
  5251. };
  5252. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5253. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5254. var engine = scene.getEngine();
  5255. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5256. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5257. gl.bindTexture(gl.TEXTURE_2D, texture);
  5258. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5259. texture._baseWidth = width;
  5260. texture._baseHeight = height;
  5261. texture._width = potWidth;
  5262. texture._height = potHeight;
  5263. texture.isReady = true;
  5264. processFunction(potWidth, potHeight);
  5265. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5267. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5268. if (!noMipmap && !isCompressed) {
  5269. gl.generateMipmap(gl.TEXTURE_2D);
  5270. }
  5271. gl.bindTexture(gl.TEXTURE_2D, null);
  5272. engine._activeTexturesCache = [];
  5273. scene._removePendingData(texture);
  5274. };
  5275. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5276. var onload = function () {
  5277. loadedImages[index] = img;
  5278. loadedImages._internalCount++;
  5279. scene._removePendingData(img);
  5280. if (loadedImages._internalCount === 6) {
  5281. onfinish(loadedImages);
  5282. }
  5283. };
  5284. var onerror = function () {
  5285. scene._removePendingData(img);
  5286. };
  5287. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5288. scene._addPendingData(img);
  5289. };
  5290. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5291. var loadedImages = [];
  5292. loadedImages._internalCount = 0;
  5293. for (var index = 0; index < 6; index++) {
  5294. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5295. }
  5296. };
  5297. var EngineCapabilities = (function () {
  5298. function EngineCapabilities() {
  5299. }
  5300. return EngineCapabilities;
  5301. })();
  5302. BABYLON.EngineCapabilities = EngineCapabilities;
  5303. /**
  5304. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5305. */
  5306. var Engine = (function () {
  5307. /**
  5308. * @constructor
  5309. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5310. * @param {boolean} [antialias] - enable antialias
  5311. * @param options - further options to be sent to the getContext function
  5312. */
  5313. function Engine(canvas, antialias, options) {
  5314. var _this = this;
  5315. // Public members
  5316. this.isFullscreen = false;
  5317. this.isPointerLock = false;
  5318. this.cullBackFaces = true;
  5319. this.renderEvenInBackground = true;
  5320. this.scenes = new Array();
  5321. this._windowIsBackground = false;
  5322. this._loadingDivBackgroundColor = "black";
  5323. this._drawCalls = 0;
  5324. this._renderingQueueLaunched = false;
  5325. this._activeRenderLoops = [];
  5326. // FPS
  5327. this.fpsRange = 60;
  5328. this.previousFramesDuration = [];
  5329. this.fps = 60;
  5330. this.deltaTime = 0;
  5331. // States
  5332. this._depthCullingState = new _DepthCullingState();
  5333. this._alphaState = new _AlphaState();
  5334. this._alphaMode = Engine.ALPHA_DISABLE;
  5335. // Cache
  5336. this._loadedTexturesCache = new Array();
  5337. this._activeTexturesCache = new Array();
  5338. this._compiledEffects = {};
  5339. this._uintIndicesCurrentlySet = false;
  5340. this._renderingCanvas = canvas;
  5341. options = options || {};
  5342. options.antialias = antialias;
  5343. if (options.preserveDrawingBuffer === undefined) {
  5344. options.preserveDrawingBuffer = false;
  5345. }
  5346. // GL
  5347. try {
  5348. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5349. }
  5350. catch (e) {
  5351. throw new Error("WebGL not supported");
  5352. }
  5353. if (!this._gl) {
  5354. throw new Error("WebGL not supported");
  5355. }
  5356. this._onBlur = function () {
  5357. _this._windowIsBackground = true;
  5358. };
  5359. this._onFocus = function () {
  5360. _this._windowIsBackground = false;
  5361. };
  5362. window.addEventListener("blur", this._onBlur);
  5363. window.addEventListener("focus", this._onFocus);
  5364. // Viewport
  5365. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5366. this.resize();
  5367. // Caps
  5368. this._caps = new EngineCapabilities();
  5369. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5370. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5371. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5372. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5373. // Infos
  5374. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5375. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5376. if (rendererInfo != null) {
  5377. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5378. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5379. }
  5380. if (!this._glVendor) {
  5381. this._glVendor = "Unknown vendor";
  5382. }
  5383. if (!this._glRenderer) {
  5384. this._glRenderer = "Unknown renderer";
  5385. }
  5386. // Extensions
  5387. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5388. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5389. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5390. 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');
  5391. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5392. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5393. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5394. this._caps.highPrecisionShaderSupported = true;
  5395. if (this._gl.getShaderPrecisionFormat) {
  5396. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5397. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5398. }
  5399. // Depth buffer
  5400. this.setDepthBuffer(true);
  5401. this.setDepthFunctionToLessOrEqual();
  5402. this.setDepthWrite(true);
  5403. // Fullscreen
  5404. this._onFullscreenChange = function () {
  5405. if (document.fullscreen !== undefined) {
  5406. _this.isFullscreen = document.fullscreen;
  5407. }
  5408. else if (document.mozFullScreen !== undefined) {
  5409. _this.isFullscreen = document.mozFullScreen;
  5410. }
  5411. else if (document.webkitIsFullScreen !== undefined) {
  5412. _this.isFullscreen = document.webkitIsFullScreen;
  5413. }
  5414. else if (document.msIsFullScreen !== undefined) {
  5415. _this.isFullscreen = document.msIsFullScreen;
  5416. }
  5417. // Pointer lock
  5418. if (_this.isFullscreen && _this._pointerLockRequested) {
  5419. canvas.requestPointerLock = canvas.requestPointerLock ||
  5420. canvas.msRequestPointerLock ||
  5421. canvas.mozRequestPointerLock ||
  5422. canvas.webkitRequestPointerLock;
  5423. if (canvas.requestPointerLock) {
  5424. canvas.requestPointerLock();
  5425. }
  5426. }
  5427. };
  5428. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5429. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5430. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5431. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5432. // Pointer lock
  5433. this._onPointerLockChange = function () {
  5434. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5435. document.webkitPointerLockElement === canvas ||
  5436. document.msPointerLockElement === canvas ||
  5437. document.pointerLockElement === canvas);
  5438. };
  5439. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5440. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5441. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5442. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5443. if (!Engine.audioEngine) {
  5444. Engine.audioEngine = new BABYLON.AudioEngine();
  5445. }
  5446. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5447. }
  5448. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5449. get: function () {
  5450. return Engine._ALPHA_DISABLE;
  5451. },
  5452. enumerable: true,
  5453. configurable: true
  5454. });
  5455. Object.defineProperty(Engine, "ALPHA_ADD", {
  5456. get: function () {
  5457. return Engine._ALPHA_ADD;
  5458. },
  5459. enumerable: true,
  5460. configurable: true
  5461. });
  5462. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5463. get: function () {
  5464. return Engine._ALPHA_COMBINE;
  5465. },
  5466. enumerable: true,
  5467. configurable: true
  5468. });
  5469. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5470. get: function () {
  5471. return Engine._DELAYLOADSTATE_NONE;
  5472. },
  5473. enumerable: true,
  5474. configurable: true
  5475. });
  5476. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5477. get: function () {
  5478. return Engine._DELAYLOADSTATE_LOADED;
  5479. },
  5480. enumerable: true,
  5481. configurable: true
  5482. });
  5483. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5484. get: function () {
  5485. return Engine._DELAYLOADSTATE_LOADING;
  5486. },
  5487. enumerable: true,
  5488. configurable: true
  5489. });
  5490. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5491. get: function () {
  5492. return Engine._DELAYLOADSTATE_NOTLOADED;
  5493. },
  5494. enumerable: true,
  5495. configurable: true
  5496. });
  5497. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5498. get: function () {
  5499. return Engine._TEXTUREFORMAT_ALPHA;
  5500. },
  5501. enumerable: true,
  5502. configurable: true
  5503. });
  5504. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5505. get: function () {
  5506. return Engine._TEXTUREFORMAT_LUMINANCE;
  5507. },
  5508. enumerable: true,
  5509. configurable: true
  5510. });
  5511. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5512. get: function () {
  5513. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5514. },
  5515. enumerable: true,
  5516. configurable: true
  5517. });
  5518. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5519. get: function () {
  5520. return Engine._TEXTUREFORMAT_RGB;
  5521. },
  5522. enumerable: true,
  5523. configurable: true
  5524. });
  5525. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5526. get: function () {
  5527. return Engine._TEXTUREFORMAT_RGBA;
  5528. },
  5529. enumerable: true,
  5530. configurable: true
  5531. });
  5532. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5533. get: function () {
  5534. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5535. },
  5536. enumerable: true,
  5537. configurable: true
  5538. });
  5539. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5540. get: function () {
  5541. return Engine._TEXTURETYPE_FLOAT;
  5542. },
  5543. enumerable: true,
  5544. configurable: true
  5545. });
  5546. Object.defineProperty(Engine, "Version", {
  5547. get: function () {
  5548. return "2.2.0-alpha";
  5549. },
  5550. enumerable: true,
  5551. configurable: true
  5552. });
  5553. Engine.prototype._prepareWorkingCanvas = function () {
  5554. if (this._workingCanvas) {
  5555. return;
  5556. }
  5557. this._workingCanvas = document.createElement("canvas");
  5558. this._workingContext = this._workingCanvas.getContext("2d");
  5559. };
  5560. Engine.prototype.getGlInfo = function () {
  5561. return {
  5562. vendor: this._glVendor,
  5563. renderer: this._glRenderer,
  5564. version: this._glVersion
  5565. };
  5566. };
  5567. Engine.prototype.getAspectRatio = function (camera) {
  5568. var viewport = camera.viewport;
  5569. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5570. };
  5571. Engine.prototype.getRenderWidth = function () {
  5572. if (this._currentRenderTarget) {
  5573. return this._currentRenderTarget._width;
  5574. }
  5575. return this._renderingCanvas.width;
  5576. };
  5577. Engine.prototype.getRenderHeight = function () {
  5578. if (this._currentRenderTarget) {
  5579. return this._currentRenderTarget._height;
  5580. }
  5581. return this._renderingCanvas.height;
  5582. };
  5583. Engine.prototype.getRenderingCanvas = function () {
  5584. return this._renderingCanvas;
  5585. };
  5586. Engine.prototype.getRenderingCanvasClientRect = function () {
  5587. return this._renderingCanvas.getBoundingClientRect();
  5588. };
  5589. Engine.prototype.setHardwareScalingLevel = function (level) {
  5590. this._hardwareScalingLevel = level;
  5591. this.resize();
  5592. };
  5593. Engine.prototype.getHardwareScalingLevel = function () {
  5594. return this._hardwareScalingLevel;
  5595. };
  5596. Engine.prototype.getLoadedTexturesCache = function () {
  5597. return this._loadedTexturesCache;
  5598. };
  5599. Engine.prototype.getCaps = function () {
  5600. return this._caps;
  5601. };
  5602. Object.defineProperty(Engine.prototype, "drawCalls", {
  5603. get: function () {
  5604. return this._drawCalls;
  5605. },
  5606. enumerable: true,
  5607. configurable: true
  5608. });
  5609. // Methods
  5610. Engine.prototype.resetDrawCalls = function () {
  5611. this._drawCalls = 0;
  5612. };
  5613. Engine.prototype.setDepthFunctionToGreater = function () {
  5614. this._depthCullingState.depthFunc = this._gl.GREATER;
  5615. };
  5616. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5617. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5618. };
  5619. Engine.prototype.setDepthFunctionToLess = function () {
  5620. this._depthCullingState.depthFunc = this._gl.LESS;
  5621. };
  5622. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5623. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5624. };
  5625. /**
  5626. * stop executing a render loop function and remove it from the execution array
  5627. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5628. */
  5629. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5630. if (!renderFunction) {
  5631. this._activeRenderLoops = [];
  5632. return;
  5633. }
  5634. var index = this._activeRenderLoops.indexOf(renderFunction);
  5635. if (index >= 0) {
  5636. this._activeRenderLoops.splice(index, 1);
  5637. }
  5638. };
  5639. Engine.prototype._renderLoop = function () {
  5640. var _this = this;
  5641. var shouldRender = true;
  5642. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5643. shouldRender = false;
  5644. }
  5645. if (shouldRender) {
  5646. // Start new frame
  5647. this.beginFrame();
  5648. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5649. var renderFunction = this._activeRenderLoops[index];
  5650. renderFunction();
  5651. }
  5652. // Present
  5653. this.endFrame();
  5654. }
  5655. if (this._activeRenderLoops.length > 0) {
  5656. // Register new frame
  5657. BABYLON.Tools.QueueNewFrame(function () {
  5658. _this._renderLoop();
  5659. });
  5660. }
  5661. else {
  5662. this._renderingQueueLaunched = false;
  5663. }
  5664. };
  5665. /**
  5666. * Register and execute a render loop. The engine can have more than one render function.
  5667. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5668. * @example
  5669. * engine.runRenderLoop(function () {
  5670. * scene.render()
  5671. * })
  5672. */
  5673. Engine.prototype.runRenderLoop = function (renderFunction) {
  5674. var _this = this;
  5675. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5676. return;
  5677. }
  5678. this._activeRenderLoops.push(renderFunction);
  5679. if (!this._renderingQueueLaunched) {
  5680. this._renderingQueueLaunched = true;
  5681. BABYLON.Tools.QueueNewFrame(function () {
  5682. _this._renderLoop();
  5683. });
  5684. }
  5685. };
  5686. /**
  5687. * Toggle full screen mode.
  5688. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5689. */
  5690. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5691. if (this.isFullscreen) {
  5692. BABYLON.Tools.ExitFullscreen();
  5693. }
  5694. else {
  5695. this._pointerLockRequested = requestPointerLock;
  5696. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5697. }
  5698. };
  5699. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5700. this.applyStates();
  5701. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5702. if (this._depthCullingState.depthMask) {
  5703. this._gl.clearDepth(1.0);
  5704. }
  5705. var mode = 0;
  5706. if (backBuffer)
  5707. mode |= this._gl.COLOR_BUFFER_BIT;
  5708. if (depthStencil && this._depthCullingState.depthMask)
  5709. mode |= this._gl.DEPTH_BUFFER_BIT;
  5710. this._gl.clear(mode);
  5711. };
  5712. /**
  5713. * Set the WebGL's viewport
  5714. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5715. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5716. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5717. */
  5718. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5719. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5720. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5721. var x = viewport.x || 0;
  5722. var y = viewport.y || 0;
  5723. this._cachedViewport = viewport;
  5724. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5725. };
  5726. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5727. this._cachedViewport = null;
  5728. this._gl.viewport(x, y, width, height);
  5729. };
  5730. Engine.prototype.beginFrame = function () {
  5731. this._measureFps();
  5732. };
  5733. Engine.prototype.endFrame = function () {
  5734. //this.flushFramebuffer();
  5735. };
  5736. /**
  5737. * resize the view according to the canvas' size.
  5738. * @example
  5739. * window.addEventListener("resize", function () {
  5740. * engine.resize();
  5741. * });
  5742. */
  5743. Engine.prototype.resize = function () {
  5744. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5745. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5746. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5747. };
  5748. /**
  5749. * force a specific size of the canvas
  5750. * @param {number} width - the new canvas' width
  5751. * @param {number} height - the new canvas' height
  5752. */
  5753. Engine.prototype.setSize = function (width, height) {
  5754. this._renderingCanvas.width = width;
  5755. this._renderingCanvas.height = height;
  5756. for (var index = 0; index < this.scenes.length; index++) {
  5757. var scene = this.scenes[index];
  5758. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5759. var cam = scene.cameras[camIndex];
  5760. cam._currentRenderId = 0;
  5761. }
  5762. }
  5763. };
  5764. Engine.prototype.bindFramebuffer = function (texture) {
  5765. this._currentRenderTarget = texture;
  5766. var gl = this._gl;
  5767. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5768. this._gl.viewport(0, 0, texture._width, texture._height);
  5769. this.wipeCaches();
  5770. };
  5771. Engine.prototype.unBindFramebuffer = function (texture) {
  5772. this._currentRenderTarget = null;
  5773. if (texture.generateMipMaps) {
  5774. var gl = this._gl;
  5775. gl.bindTexture(gl.TEXTURE_2D, texture);
  5776. gl.generateMipmap(gl.TEXTURE_2D);
  5777. gl.bindTexture(gl.TEXTURE_2D, null);
  5778. }
  5779. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5780. };
  5781. Engine.prototype.flushFramebuffer = function () {
  5782. this._gl.flush();
  5783. };
  5784. Engine.prototype.restoreDefaultFramebuffer = function () {
  5785. this._currentRenderTarget = null;
  5786. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5787. this.setViewport(this._cachedViewport);
  5788. this.wipeCaches();
  5789. };
  5790. // VBOs
  5791. Engine.prototype._resetVertexBufferBinding = function () {
  5792. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5793. this._cachedVertexBuffers = null;
  5794. };
  5795. Engine.prototype.createVertexBuffer = function (vertices) {
  5796. var vbo = this._gl.createBuffer();
  5797. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5798. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5799. this._resetVertexBufferBinding();
  5800. vbo.references = 1;
  5801. return vbo;
  5802. };
  5803. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5804. var vbo = this._gl.createBuffer();
  5805. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5806. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5807. this._resetVertexBufferBinding();
  5808. vbo.references = 1;
  5809. return vbo;
  5810. };
  5811. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5812. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5813. if (offset === undefined) {
  5814. offset = 0;
  5815. }
  5816. if (vertices instanceof Float32Array) {
  5817. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5818. }
  5819. else {
  5820. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5821. }
  5822. this._resetVertexBufferBinding();
  5823. };
  5824. Engine.prototype._resetIndexBufferBinding = function () {
  5825. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5826. this._cachedIndexBuffer = null;
  5827. };
  5828. Engine.prototype.createIndexBuffer = function (indices) {
  5829. var vbo = this._gl.createBuffer();
  5830. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5831. // Check for 32 bits indices
  5832. var arrayBuffer;
  5833. var need32Bits = false;
  5834. if (this._caps.uintIndices) {
  5835. for (var index = 0; index < indices.length; index++) {
  5836. if (indices[index] > 65535) {
  5837. need32Bits = true;
  5838. break;
  5839. }
  5840. }
  5841. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5842. }
  5843. else {
  5844. arrayBuffer = new Uint16Array(indices);
  5845. }
  5846. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5847. this._resetIndexBufferBinding();
  5848. vbo.references = 1;
  5849. vbo.is32Bits = need32Bits;
  5850. return vbo;
  5851. };
  5852. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5853. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5854. this._cachedVertexBuffers = vertexBuffer;
  5855. this._cachedEffectForVertexBuffers = effect;
  5856. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5857. var offset = 0;
  5858. for (var index = 0; index < vertexDeclaration.length; index++) {
  5859. var order = effect.getAttributeLocation(index);
  5860. if (order >= 0) {
  5861. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5862. }
  5863. offset += vertexDeclaration[index] * 4;
  5864. }
  5865. }
  5866. if (this._cachedIndexBuffer !== indexBuffer) {
  5867. this._cachedIndexBuffer = indexBuffer;
  5868. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5869. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5870. }
  5871. };
  5872. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5873. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5874. this._cachedVertexBuffers = vertexBuffers;
  5875. this._cachedEffectForVertexBuffers = effect;
  5876. var attributes = effect.getAttributesNames();
  5877. for (var index = 0; index < attributes.length; index++) {
  5878. var order = effect.getAttributeLocation(index);
  5879. if (order >= 0) {
  5880. var vertexBuffer = vertexBuffers[attributes[index]];
  5881. if (!vertexBuffer) {
  5882. continue;
  5883. }
  5884. var stride = vertexBuffer.getStrideSize();
  5885. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5886. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5887. }
  5888. }
  5889. }
  5890. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5891. this._cachedIndexBuffer = indexBuffer;
  5892. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5893. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5894. }
  5895. };
  5896. Engine.prototype._releaseBuffer = function (buffer) {
  5897. buffer.references--;
  5898. if (buffer.references === 0) {
  5899. this._gl.deleteBuffer(buffer);
  5900. return true;
  5901. }
  5902. return false;
  5903. };
  5904. Engine.prototype.createInstancesBuffer = function (capacity) {
  5905. var buffer = this._gl.createBuffer();
  5906. buffer.capacity = capacity;
  5907. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5908. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5909. return buffer;
  5910. };
  5911. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5912. this._gl.deleteBuffer(buffer);
  5913. };
  5914. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5915. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5916. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5917. for (var index = 0; index < 4; index++) {
  5918. var offsetLocation = offsetLocations[index];
  5919. this._gl.enableVertexAttribArray(offsetLocation);
  5920. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5921. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5922. }
  5923. };
  5924. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5925. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5926. for (var index = 0; index < 4; index++) {
  5927. var offsetLocation = offsetLocations[index];
  5928. this._gl.disableVertexAttribArray(offsetLocation);
  5929. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5930. }
  5931. };
  5932. Engine.prototype.applyStates = function () {
  5933. this._depthCullingState.apply(this._gl);
  5934. this._alphaState.apply(this._gl);
  5935. };
  5936. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5937. // Apply states
  5938. this.applyStates();
  5939. this._drawCalls++;
  5940. // Render
  5941. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5942. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5943. if (instancesCount) {
  5944. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5945. return;
  5946. }
  5947. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5948. };
  5949. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5950. // Apply states
  5951. this.applyStates();
  5952. this._drawCalls++;
  5953. if (instancesCount) {
  5954. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5955. return;
  5956. }
  5957. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5958. };
  5959. // Shaders
  5960. Engine.prototype._releaseEffect = function (effect) {
  5961. if (this._compiledEffects[effect._key]) {
  5962. delete this._compiledEffects[effect._key];
  5963. if (effect.getProgram()) {
  5964. this._gl.deleteProgram(effect.getProgram());
  5965. }
  5966. }
  5967. };
  5968. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5969. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5970. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5971. var name = vertex + "+" + fragment + "@" + defines;
  5972. if (this._compiledEffects[name]) {
  5973. return this._compiledEffects[name];
  5974. }
  5975. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5976. effect._key = name;
  5977. this._compiledEffects[name] = effect;
  5978. return effect;
  5979. };
  5980. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5981. if (uniformsNames === void 0) { uniformsNames = []; }
  5982. if (samplers === void 0) { samplers = []; }
  5983. if (defines === void 0) { defines = ""; }
  5984. return this.createEffect({
  5985. vertex: "particles",
  5986. fragmentElement: fragmentName
  5987. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5988. };
  5989. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5990. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5991. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5992. var shaderProgram = this._gl.createProgram();
  5993. this._gl.attachShader(shaderProgram, vertexShader);
  5994. this._gl.attachShader(shaderProgram, fragmentShader);
  5995. this._gl.linkProgram(shaderProgram);
  5996. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5997. if (!linked) {
  5998. var error = this._gl.getProgramInfoLog(shaderProgram);
  5999. if (error) {
  6000. throw new Error(error);
  6001. }
  6002. }
  6003. this._gl.deleteShader(vertexShader);
  6004. this._gl.deleteShader(fragmentShader);
  6005. return shaderProgram;
  6006. };
  6007. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6008. var results = [];
  6009. for (var index = 0; index < uniformsNames.length; index++) {
  6010. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6011. }
  6012. return results;
  6013. };
  6014. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6015. var results = [];
  6016. for (var index = 0; index < attributesNames.length; index++) {
  6017. try {
  6018. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6019. }
  6020. catch (e) {
  6021. results.push(-1);
  6022. }
  6023. }
  6024. return results;
  6025. };
  6026. Engine.prototype.enableEffect = function (effect) {
  6027. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6028. if (effect && effect.onBind) {
  6029. effect.onBind(effect);
  6030. }
  6031. return;
  6032. }
  6033. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6034. // Use program
  6035. this._gl.useProgram(effect.getProgram());
  6036. for (var i in this._vertexAttribArrays) {
  6037. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6038. continue;
  6039. }
  6040. this._vertexAttribArrays[i] = false;
  6041. this._gl.disableVertexAttribArray(i);
  6042. }
  6043. var attributesCount = effect.getAttributesCount();
  6044. for (var index = 0; index < attributesCount; index++) {
  6045. // Attributes
  6046. var order = effect.getAttributeLocation(index);
  6047. if (order >= 0) {
  6048. this._vertexAttribArrays[order] = true;
  6049. this._gl.enableVertexAttribArray(order);
  6050. }
  6051. }
  6052. this._currentEffect = effect;
  6053. if (effect.onBind) {
  6054. effect.onBind(effect);
  6055. }
  6056. };
  6057. Engine.prototype.setArray = function (uniform, array) {
  6058. if (!uniform)
  6059. return;
  6060. this._gl.uniform1fv(uniform, array);
  6061. };
  6062. Engine.prototype.setArray2 = function (uniform, array) {
  6063. if (!uniform || array.length % 2 !== 0)
  6064. return;
  6065. this._gl.uniform2fv(uniform, array);
  6066. };
  6067. Engine.prototype.setArray3 = function (uniform, array) {
  6068. if (!uniform || array.length % 3 !== 0)
  6069. return;
  6070. this._gl.uniform3fv(uniform, array);
  6071. };
  6072. Engine.prototype.setArray4 = function (uniform, array) {
  6073. if (!uniform || array.length % 4 !== 0)
  6074. return;
  6075. this._gl.uniform4fv(uniform, array);
  6076. };
  6077. Engine.prototype.setMatrices = function (uniform, matrices) {
  6078. if (!uniform)
  6079. return;
  6080. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6081. };
  6082. Engine.prototype.setMatrix = function (uniform, matrix) {
  6083. if (!uniform)
  6084. return;
  6085. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6086. };
  6087. Engine.prototype.setFloat = function (uniform, value) {
  6088. if (!uniform)
  6089. return;
  6090. this._gl.uniform1f(uniform, value);
  6091. };
  6092. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6093. if (!uniform)
  6094. return;
  6095. this._gl.uniform2f(uniform, x, y);
  6096. };
  6097. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6098. if (!uniform)
  6099. return;
  6100. this._gl.uniform3f(uniform, x, y, z);
  6101. };
  6102. Engine.prototype.setBool = function (uniform, bool) {
  6103. if (!uniform)
  6104. return;
  6105. this._gl.uniform1i(uniform, bool);
  6106. };
  6107. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6108. if (!uniform)
  6109. return;
  6110. this._gl.uniform4f(uniform, x, y, z, w);
  6111. };
  6112. Engine.prototype.setColor3 = function (uniform, color3) {
  6113. if (!uniform)
  6114. return;
  6115. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6116. };
  6117. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6118. if (!uniform)
  6119. return;
  6120. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6121. };
  6122. // States
  6123. Engine.prototype.setState = function (culling, zOffset, force) {
  6124. if (zOffset === void 0) { zOffset = 0; }
  6125. // Culling
  6126. if (this._depthCullingState.cull !== culling || force) {
  6127. if (culling) {
  6128. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6129. this._depthCullingState.cull = true;
  6130. }
  6131. else {
  6132. this._depthCullingState.cull = false;
  6133. }
  6134. }
  6135. // Z offset
  6136. this._depthCullingState.zOffset = zOffset;
  6137. };
  6138. Engine.prototype.setDepthBuffer = function (enable) {
  6139. this._depthCullingState.depthTest = enable;
  6140. };
  6141. Engine.prototype.getDepthWrite = function () {
  6142. return this._depthCullingState.depthMask;
  6143. };
  6144. Engine.prototype.setDepthWrite = function (enable) {
  6145. this._depthCullingState.depthMask = enable;
  6146. };
  6147. Engine.prototype.setColorWrite = function (enable) {
  6148. this._gl.colorMask(enable, enable, enable, enable);
  6149. };
  6150. Engine.prototype.setAlphaMode = function (mode) {
  6151. switch (mode) {
  6152. case Engine.ALPHA_DISABLE:
  6153. this.setDepthWrite(true);
  6154. this._alphaState.alphaBlend = false;
  6155. break;
  6156. case Engine.ALPHA_COMBINE:
  6157. this.setDepthWrite(false);
  6158. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6159. this._alphaState.alphaBlend = true;
  6160. break;
  6161. case Engine.ALPHA_ADD:
  6162. this.setDepthWrite(false);
  6163. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6164. this._alphaState.alphaBlend = true;
  6165. break;
  6166. }
  6167. this._alphaMode = mode;
  6168. };
  6169. Engine.prototype.getAlphaMode = function () {
  6170. return this._alphaMode;
  6171. };
  6172. Engine.prototype.setAlphaTesting = function (enable) {
  6173. this._alphaTest = enable;
  6174. };
  6175. Engine.prototype.getAlphaTesting = function () {
  6176. return this._alphaTest;
  6177. };
  6178. // Textures
  6179. Engine.prototype.wipeCaches = function () {
  6180. this._activeTexturesCache = [];
  6181. this._currentEffect = null;
  6182. this._depthCullingState.reset();
  6183. this._alphaState.reset();
  6184. this._cachedVertexBuffers = null;
  6185. this._cachedIndexBuffer = null;
  6186. this._cachedEffectForVertexBuffers = null;
  6187. };
  6188. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6189. var gl = this._gl;
  6190. gl.bindTexture(gl.TEXTURE_2D, texture);
  6191. var magFilter = gl.NEAREST;
  6192. var minFilter = gl.NEAREST;
  6193. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6194. magFilter = gl.LINEAR;
  6195. minFilter = gl.LINEAR;
  6196. }
  6197. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6198. magFilter = gl.LINEAR;
  6199. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6200. }
  6201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6202. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6203. gl.bindTexture(gl.TEXTURE_2D, null);
  6204. texture.samplingMode = samplingMode;
  6205. };
  6206. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6207. var _this = this;
  6208. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6209. if (onLoad === void 0) { onLoad = null; }
  6210. if (onError === void 0) { onError = null; }
  6211. if (buffer === void 0) { buffer = null; }
  6212. var texture = this._gl.createTexture();
  6213. var extension;
  6214. var fromData = false;
  6215. if (url.substr(0, 5) === "data:") {
  6216. fromData = true;
  6217. }
  6218. if (!fromData)
  6219. extension = url.substr(url.length - 4, 4).toLowerCase();
  6220. else {
  6221. var oldUrl = url;
  6222. fromData = oldUrl.split(':');
  6223. url = oldUrl;
  6224. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6225. }
  6226. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6227. var isTGA = (extension === ".tga");
  6228. scene._addPendingData(texture);
  6229. texture.url = url;
  6230. texture.noMipmap = noMipmap;
  6231. texture.references = 1;
  6232. texture.samplingMode = samplingMode;
  6233. this._loadedTexturesCache.push(texture);
  6234. var onerror = function () {
  6235. scene._removePendingData(texture);
  6236. if (onError) {
  6237. onError();
  6238. }
  6239. };
  6240. if (isTGA) {
  6241. var callback = function (arrayBuffer) {
  6242. var data = new Uint8Array(arrayBuffer);
  6243. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6244. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6245. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6246. if (onLoad) {
  6247. onLoad();
  6248. }
  6249. }, samplingMode);
  6250. };
  6251. if (!(fromData instanceof Array))
  6252. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6253. callback(arrayBuffer);
  6254. }, onerror, scene.database, true);
  6255. else
  6256. callback(buffer);
  6257. }
  6258. else if (isDDS) {
  6259. callback = function (data) {
  6260. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6261. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6262. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6263. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6264. if (onLoad) {
  6265. onLoad();
  6266. }
  6267. }, samplingMode);
  6268. };
  6269. if (!(fromData instanceof Array))
  6270. BABYLON.Tools.LoadFile(url, function (data) {
  6271. callback(data);
  6272. }, onerror, scene.database, true);
  6273. else
  6274. callback(buffer);
  6275. }
  6276. else {
  6277. var onload = function (img) {
  6278. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6279. var isPot = (img.width === potWidth && img.height === potHeight);
  6280. if (!isPot) {
  6281. _this._prepareWorkingCanvas();
  6282. _this._workingCanvas.width = potWidth;
  6283. _this._workingCanvas.height = potHeight;
  6284. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6285. _this._workingContext.imageSmoothingEnabled = false;
  6286. _this._workingContext.mozImageSmoothingEnabled = false;
  6287. _this._workingContext.oImageSmoothingEnabled = false;
  6288. _this._workingContext.webkitImageSmoothingEnabled = false;
  6289. _this._workingContext.msImageSmoothingEnabled = false;
  6290. }
  6291. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6292. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6293. _this._workingContext.imageSmoothingEnabled = true;
  6294. _this._workingContext.mozImageSmoothingEnabled = true;
  6295. _this._workingContext.oImageSmoothingEnabled = true;
  6296. _this._workingContext.webkitImageSmoothingEnabled = true;
  6297. _this._workingContext.msImageSmoothingEnabled = true;
  6298. }
  6299. }
  6300. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6301. if (onLoad) {
  6302. onLoad();
  6303. }
  6304. }, samplingMode);
  6305. };
  6306. if (!(fromData instanceof Array))
  6307. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6308. else
  6309. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6310. }
  6311. return texture;
  6312. };
  6313. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6314. var texture = this._gl.createTexture();
  6315. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6316. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6317. // Format
  6318. var internalFormat = this._gl.RGBA;
  6319. switch (format) {
  6320. case Engine.TEXTUREFORMAT_ALPHA:
  6321. internalFormat = this._gl.ALPHA;
  6322. break;
  6323. case Engine.TEXTUREFORMAT_LUMINANCE:
  6324. internalFormat = this._gl.LUMINANCE;
  6325. break;
  6326. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6327. internalFormat = this._gl.LUMINANCE_ALPHA;
  6328. break;
  6329. case Engine.TEXTUREFORMAT_RGB:
  6330. internalFormat = this._gl.RGB;
  6331. break;
  6332. case Engine.TEXTUREFORMAT_RGBA:
  6333. internalFormat = this._gl.RGBA;
  6334. break;
  6335. }
  6336. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6337. if (generateMipMaps) {
  6338. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6339. }
  6340. // Filters
  6341. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6342. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6343. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6344. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6345. this._activeTexturesCache = [];
  6346. texture._baseWidth = width;
  6347. texture._baseHeight = height;
  6348. texture._width = width;
  6349. texture._height = height;
  6350. texture.isReady = true;
  6351. texture.references = 1;
  6352. texture.samplingMode = samplingMode;
  6353. this._loadedTexturesCache.push(texture);
  6354. return texture;
  6355. };
  6356. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6357. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6358. var texture = this._gl.createTexture();
  6359. texture._baseWidth = width;
  6360. texture._baseHeight = height;
  6361. if (forceExponantOfTwo) {
  6362. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6363. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6364. }
  6365. this._activeTexturesCache = [];
  6366. texture._width = width;
  6367. texture._height = height;
  6368. texture.isReady = false;
  6369. texture.generateMipMaps = generateMipMaps;
  6370. texture.references = 1;
  6371. texture.samplingMode = samplingMode;
  6372. this.updateTextureSamplingMode(samplingMode, texture);
  6373. this._loadedTexturesCache.push(texture);
  6374. return texture;
  6375. };
  6376. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6377. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6378. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6379. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6380. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6381. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6382. };
  6383. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6384. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6385. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6386. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6387. if (texture.generateMipMaps) {
  6388. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6389. }
  6390. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6391. this._activeTexturesCache = [];
  6392. texture.isReady = true;
  6393. };
  6394. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6395. if (texture._isDisabled) {
  6396. return;
  6397. }
  6398. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6399. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6400. try {
  6401. // Testing video texture support
  6402. if (this._videoTextureSupported === undefined) {
  6403. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6404. if (this._gl.getError() !== 0) {
  6405. this._videoTextureSupported = false;
  6406. }
  6407. else {
  6408. this._videoTextureSupported = true;
  6409. }
  6410. }
  6411. // Copy video through the current working canvas if video texture is not supported
  6412. if (!this._videoTextureSupported) {
  6413. if (!texture._workingCanvas) {
  6414. texture._workingCanvas = document.createElement("canvas");
  6415. texture._workingContext = texture._workingCanvas.getContext("2d");
  6416. texture._workingCanvas.width = texture._width;
  6417. texture._workingCanvas.height = texture._height;
  6418. }
  6419. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6420. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6421. }
  6422. else {
  6423. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6424. }
  6425. if (texture.generateMipMaps) {
  6426. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6427. }
  6428. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6429. this._activeTexturesCache = [];
  6430. texture.isReady = true;
  6431. }
  6432. catch (ex) {
  6433. // Something unexpected
  6434. // Let's disable the texture
  6435. texture._isDisabled = true;
  6436. }
  6437. };
  6438. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6439. // old version had a "generateMipMaps" arg instead of options.
  6440. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6441. // in the same way, generateDepthBuffer is defaulted to true
  6442. var generateMipMaps = false;
  6443. var generateDepthBuffer = true;
  6444. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6445. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6446. if (options !== undefined) {
  6447. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6448. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6449. type = options.type === undefined ? type : options.type;
  6450. if (options.samplingMode !== undefined) {
  6451. samplingMode = options.samplingMode;
  6452. }
  6453. if (type === Engine.TEXTURETYPE_FLOAT) {
  6454. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6455. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6456. }
  6457. }
  6458. var gl = this._gl;
  6459. var texture = gl.createTexture();
  6460. gl.bindTexture(gl.TEXTURE_2D, texture);
  6461. var width = size.width || size;
  6462. var height = size.height || size;
  6463. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6464. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6465. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6466. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6467. }
  6468. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6469. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6470. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6471. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6472. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6473. var depthBuffer;
  6474. // Create the depth buffer
  6475. if (generateDepthBuffer) {
  6476. depthBuffer = gl.createRenderbuffer();
  6477. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6478. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6479. }
  6480. // Create the framebuffer
  6481. var framebuffer = gl.createFramebuffer();
  6482. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6483. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6484. if (generateDepthBuffer) {
  6485. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6486. }
  6487. if (generateMipMaps) {
  6488. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6489. }
  6490. // Unbind
  6491. gl.bindTexture(gl.TEXTURE_2D, null);
  6492. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6493. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6494. texture._framebuffer = framebuffer;
  6495. if (generateDepthBuffer) {
  6496. texture._depthBuffer = depthBuffer;
  6497. }
  6498. texture._width = width;
  6499. texture._height = height;
  6500. texture.isReady = true;
  6501. texture.generateMipMaps = generateMipMaps;
  6502. texture.references = 1;
  6503. texture.samplingMode = samplingMode;
  6504. this._activeTexturesCache = [];
  6505. this._loadedTexturesCache.push(texture);
  6506. return texture;
  6507. };
  6508. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6509. var _this = this;
  6510. var gl = this._gl;
  6511. var texture = gl.createTexture();
  6512. texture.isCube = true;
  6513. texture.url = rootUrl;
  6514. texture.references = 1;
  6515. this._loadedTexturesCache.push(texture);
  6516. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6517. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6518. if (isDDS) {
  6519. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6520. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6521. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6522. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6523. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6524. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6525. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6526. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6527. }
  6528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6529. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6530. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6531. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6532. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6533. _this._activeTexturesCache = [];
  6534. texture._width = info.width;
  6535. texture._height = info.height;
  6536. texture.isReady = true;
  6537. }, null, null, true);
  6538. }
  6539. else {
  6540. cascadeLoad(rootUrl, scene, function (imgs) {
  6541. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6542. var height = width;
  6543. _this._prepareWorkingCanvas();
  6544. _this._workingCanvas.width = width;
  6545. _this._workingCanvas.height = height;
  6546. var faces = [
  6547. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6548. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6549. ];
  6550. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6551. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6552. for (var index = 0; index < faces.length; index++) {
  6553. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6554. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6555. }
  6556. if (!noMipmap) {
  6557. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6558. }
  6559. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6560. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6561. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6562. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6563. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6564. _this._activeTexturesCache = [];
  6565. texture._width = width;
  6566. texture._height = height;
  6567. texture.isReady = true;
  6568. }, extensions);
  6569. }
  6570. return texture;
  6571. };
  6572. Engine.prototype._releaseTexture = function (texture) {
  6573. var gl = this._gl;
  6574. if (texture._framebuffer) {
  6575. gl.deleteFramebuffer(texture._framebuffer);
  6576. }
  6577. if (texture._depthBuffer) {
  6578. gl.deleteRenderbuffer(texture._depthBuffer);
  6579. }
  6580. gl.deleteTexture(texture);
  6581. // Unbind channels
  6582. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6583. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6584. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6585. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6586. this._activeTexturesCache[channel] = null;
  6587. }
  6588. var index = this._loadedTexturesCache.indexOf(texture);
  6589. if (index !== -1) {
  6590. this._loadedTexturesCache.splice(index, 1);
  6591. }
  6592. };
  6593. Engine.prototype.bindSamplers = function (effect) {
  6594. this._gl.useProgram(effect.getProgram());
  6595. var samplers = effect.getSamplers();
  6596. for (var index = 0; index < samplers.length; index++) {
  6597. var uniform = effect.getUniform(samplers[index]);
  6598. this._gl.uniform1i(uniform, index);
  6599. }
  6600. this._currentEffect = null;
  6601. };
  6602. Engine.prototype._bindTexture = function (channel, texture) {
  6603. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6604. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6605. this._activeTexturesCache[channel] = null;
  6606. };
  6607. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6608. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6609. };
  6610. Engine.prototype.setTexture = function (channel, texture) {
  6611. if (channel < 0) {
  6612. return;
  6613. }
  6614. // Not ready?
  6615. if (!texture || !texture.isReady()) {
  6616. if (this._activeTexturesCache[channel] != null) {
  6617. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6618. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6619. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6620. this._activeTexturesCache[channel] = null;
  6621. }
  6622. return;
  6623. }
  6624. // Video
  6625. if (texture instanceof BABYLON.VideoTexture) {
  6626. if (texture.update()) {
  6627. this._activeTexturesCache[channel] = null;
  6628. }
  6629. }
  6630. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6631. texture.delayLoad();
  6632. return;
  6633. }
  6634. if (this._activeTexturesCache[channel] === texture) {
  6635. return;
  6636. }
  6637. this._activeTexturesCache[channel] = texture;
  6638. var internalTexture = texture.getInternalTexture();
  6639. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6640. if (internalTexture.isCube) {
  6641. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6642. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6643. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6644. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6645. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6646. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6647. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6648. }
  6649. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6650. }
  6651. else {
  6652. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6653. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6654. internalTexture._cachedWrapU = texture.wrapU;
  6655. switch (texture.wrapU) {
  6656. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6657. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6658. break;
  6659. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6660. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6661. break;
  6662. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6663. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6664. break;
  6665. }
  6666. }
  6667. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6668. internalTexture._cachedWrapV = texture.wrapV;
  6669. switch (texture.wrapV) {
  6670. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6671. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6672. break;
  6673. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6674. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6675. break;
  6676. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6677. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6678. break;
  6679. }
  6680. }
  6681. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6682. }
  6683. };
  6684. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6685. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6686. var value = texture.anisotropicFilteringLevel;
  6687. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6688. value = 1;
  6689. }
  6690. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6691. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6692. texture._cachedAnisotropicFilteringLevel = value;
  6693. }
  6694. };
  6695. Engine.prototype.readPixels = function (x, y, width, height) {
  6696. var data = new Uint8Array(height * width * 4);
  6697. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6698. return data;
  6699. };
  6700. // Dispose
  6701. Engine.prototype.dispose = function () {
  6702. this.hideLoadingUI();
  6703. this.stopRenderLoop();
  6704. // Release scenes
  6705. while (this.scenes.length) {
  6706. this.scenes[0].dispose();
  6707. }
  6708. // Release audio engine
  6709. Engine.audioEngine.dispose();
  6710. // Release effects
  6711. for (var name in this._compiledEffects) {
  6712. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6713. }
  6714. // Unbind
  6715. for (var i in this._vertexAttribArrays) {
  6716. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6717. continue;
  6718. }
  6719. this._gl.disableVertexAttribArray(i);
  6720. }
  6721. this._gl = null;
  6722. // Events
  6723. window.removeEventListener("blur", this._onBlur);
  6724. window.removeEventListener("focus", this._onFocus);
  6725. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6726. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6727. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6728. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6729. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6730. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6731. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6732. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6733. };
  6734. // Loading screen
  6735. Engine.prototype.displayLoadingUI = function () {
  6736. var _this = this;
  6737. this._loadingDiv = document.createElement("div");
  6738. this._loadingDiv.style.opacity = "0";
  6739. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6740. // Loading text
  6741. this._loadingTextDiv = document.createElement("div");
  6742. this._loadingTextDiv.style.position = "absolute";
  6743. this._loadingTextDiv.style.left = "0";
  6744. this._loadingTextDiv.style.top = "50%";
  6745. this._loadingTextDiv.style.marginTop = "80px";
  6746. this._loadingTextDiv.style.width = "100%";
  6747. this._loadingTextDiv.style.height = "20px";
  6748. this._loadingTextDiv.style.fontFamily = "Arial";
  6749. this._loadingTextDiv.style.fontSize = "14px";
  6750. this._loadingTextDiv.style.color = "white";
  6751. this._loadingTextDiv.style.textAlign = "center";
  6752. this._loadingTextDiv.innerHTML = "Loading";
  6753. this._loadingDiv.appendChild(this._loadingTextDiv);
  6754. // Loading img
  6755. var imgBack = new Image();
  6756. 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==";
  6757. imgBack.style.position = "absolute";
  6758. imgBack.style.left = "50%";
  6759. imgBack.style.top = "50%";
  6760. imgBack.style.marginLeft = "-50px";
  6761. imgBack.style.marginTop = "-50px";
  6762. imgBack.style.transition = "transform 1.0s ease";
  6763. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6764. var deg = 360;
  6765. var onTransitionEnd = function () {
  6766. deg += 360;
  6767. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6768. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6769. };
  6770. imgBack.addEventListener("transitionend", onTransitionEnd);
  6771. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6772. this._loadingDiv.appendChild(imgBack);
  6773. // front image
  6774. var imgFront = new Image();
  6775. 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=";
  6776. imgFront.style.position = "absolute";
  6777. imgFront.style.left = "50%";
  6778. imgFront.style.top = "50%";
  6779. imgFront.style.marginLeft = "-50px";
  6780. imgFront.style.marginTop = "-50px";
  6781. this._loadingDiv.appendChild(imgFront);
  6782. // Resize
  6783. this._resizeLoadingUI = function () {
  6784. var canvasRect = _this.getRenderingCanvasClientRect();
  6785. _this._loadingDiv.style.position = "absolute";
  6786. _this._loadingDiv.style.left = canvasRect.left + "px";
  6787. _this._loadingDiv.style.top = canvasRect.top + "px";
  6788. _this._loadingDiv.style.width = canvasRect.width + "px";
  6789. _this._loadingDiv.style.height = canvasRect.height + "px";
  6790. };
  6791. this._resizeLoadingUI();
  6792. window.addEventListener("resize", this._resizeLoadingUI);
  6793. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6794. document.body.appendChild(this._loadingDiv);
  6795. setTimeout(function () {
  6796. _this._loadingDiv.style.opacity = "1";
  6797. imgBack.style.transform = "rotateZ(360deg)";
  6798. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6799. }, 0);
  6800. };
  6801. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6802. set: function (text) {
  6803. if (!this._loadingDiv) {
  6804. return;
  6805. }
  6806. this._loadingTextDiv.innerHTML = text;
  6807. },
  6808. enumerable: true,
  6809. configurable: true
  6810. });
  6811. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6812. get: function () {
  6813. return this._loadingDivBackgroundColor;
  6814. },
  6815. set: function (color) {
  6816. this._loadingDivBackgroundColor = color;
  6817. if (!this._loadingDiv) {
  6818. return;
  6819. }
  6820. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6821. },
  6822. enumerable: true,
  6823. configurable: true
  6824. });
  6825. Engine.prototype.hideLoadingUI = function () {
  6826. var _this = this;
  6827. if (!this._loadingDiv) {
  6828. return;
  6829. }
  6830. var onTransitionEnd = function () {
  6831. if (!_this._loadingDiv) {
  6832. return;
  6833. }
  6834. document.body.removeChild(_this._loadingDiv);
  6835. window.removeEventListener("resize", _this._resizeLoadingUI);
  6836. _this._loadingDiv = null;
  6837. };
  6838. this._loadingDiv.style.opacity = "0";
  6839. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6840. };
  6841. // FPS
  6842. Engine.prototype.getFps = function () {
  6843. return this.fps;
  6844. };
  6845. Engine.prototype.getDeltaTime = function () {
  6846. return this.deltaTime;
  6847. };
  6848. Engine.prototype._measureFps = function () {
  6849. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6850. var length = this.previousFramesDuration.length;
  6851. if (length >= 2) {
  6852. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6853. }
  6854. if (length >= this.fpsRange) {
  6855. if (length > this.fpsRange) {
  6856. this.previousFramesDuration.splice(0, 1);
  6857. length = this.previousFramesDuration.length;
  6858. }
  6859. var sum = 0;
  6860. for (var id = 0; id < length - 1; id++) {
  6861. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6862. }
  6863. this.fps = 1000.0 / (sum / (length - 1));
  6864. }
  6865. };
  6866. // Statics
  6867. Engine.isSupported = function () {
  6868. try {
  6869. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6870. if (navigator.isCocoonJS) {
  6871. return true;
  6872. }
  6873. var tempcanvas = document.createElement("canvas");
  6874. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6875. return gl != null && !!window.WebGLRenderingContext;
  6876. }
  6877. catch (e) {
  6878. return false;
  6879. }
  6880. };
  6881. // Const statics
  6882. Engine._ALPHA_DISABLE = 0;
  6883. Engine._ALPHA_ADD = 1;
  6884. Engine._ALPHA_COMBINE = 2;
  6885. Engine._DELAYLOADSTATE_NONE = 0;
  6886. Engine._DELAYLOADSTATE_LOADED = 1;
  6887. Engine._DELAYLOADSTATE_LOADING = 2;
  6888. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6889. Engine._TEXTUREFORMAT_ALPHA = 0;
  6890. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6891. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6892. Engine._TEXTUREFORMAT_RGB = 4;
  6893. Engine._TEXTUREFORMAT_RGBA = 4;
  6894. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6895. Engine._TEXTURETYPE_FLOAT = 1;
  6896. // Updatable statics so stick with vars here
  6897. Engine.Epsilon = 0.001;
  6898. Engine.CollisionsEpsilon = 0.001;
  6899. Engine.CodeRepository = "Babylon/";
  6900. Engine.ShadersRepository = "Babylon/Shaders/";
  6901. return Engine;
  6902. })();
  6903. BABYLON.Engine = Engine;
  6904. })(BABYLON || (BABYLON = {}));
  6905. //# sourceMappingURL=babylon.engine.js.map
  6906. var BABYLON;
  6907. (function (BABYLON) {
  6908. /**
  6909. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6910. */
  6911. var Node = (function () {
  6912. /**
  6913. * @constructor
  6914. * @param {string} name - the name and id to be given to this node
  6915. * @param {BABYLON.Scene} the scene this node will be added to
  6916. */
  6917. function Node(name, scene) {
  6918. this.state = "";
  6919. this.animations = new Array();
  6920. this._childrenFlag = -1;
  6921. this._isEnabled = true;
  6922. this._isReady = true;
  6923. this._currentRenderId = -1;
  6924. this._parentRenderId = -1;
  6925. this.name = name;
  6926. this.id = name;
  6927. this._scene = scene;
  6928. this._initCache();
  6929. }
  6930. Node.prototype.getScene = function () {
  6931. return this._scene;
  6932. };
  6933. Node.prototype.getEngine = function () {
  6934. return this._scene.getEngine();
  6935. };
  6936. // override it in derived class
  6937. Node.prototype.getWorldMatrix = function () {
  6938. return BABYLON.Matrix.Identity();
  6939. };
  6940. // override it in derived class if you add new variables to the cache
  6941. // and call the parent class method
  6942. Node.prototype._initCache = function () {
  6943. this._cache = {};
  6944. this._cache.parent = undefined;
  6945. };
  6946. Node.prototype.updateCache = function (force) {
  6947. if (!force && this.isSynchronized())
  6948. return;
  6949. this._cache.parent = this.parent;
  6950. this._updateCache();
  6951. };
  6952. // override it in derived class if you add new variables to the cache
  6953. // and call the parent class method if !ignoreParentClass
  6954. Node.prototype._updateCache = function (ignoreParentClass) {
  6955. };
  6956. // override it in derived class if you add new variables to the cache
  6957. Node.prototype._isSynchronized = function () {
  6958. return true;
  6959. };
  6960. Node.prototype._markSyncedWithParent = function () {
  6961. this._parentRenderId = this.parent._currentRenderId;
  6962. };
  6963. Node.prototype.isSynchronizedWithParent = function () {
  6964. if (!this.parent) {
  6965. return true;
  6966. }
  6967. if (this._parentRenderId !== this.parent._currentRenderId) {
  6968. return false;
  6969. }
  6970. return this.parent.isSynchronized();
  6971. };
  6972. Node.prototype.isSynchronized = function (updateCache) {
  6973. var check = this.hasNewParent();
  6974. check = check || !this.isSynchronizedWithParent();
  6975. check = check || !this._isSynchronized();
  6976. if (updateCache)
  6977. this.updateCache(true);
  6978. return !check;
  6979. };
  6980. Node.prototype.hasNewParent = function (update) {
  6981. if (this._cache.parent === this.parent)
  6982. return false;
  6983. if (update)
  6984. this._cache.parent = this.parent;
  6985. return true;
  6986. };
  6987. /**
  6988. * Is this node ready to be used/rendered
  6989. * @return {boolean} is it ready
  6990. */
  6991. Node.prototype.isReady = function () {
  6992. return this._isReady;
  6993. };
  6994. /**
  6995. * Is this node enabled.
  6996. * If the node has a parent and is enabled, the parent will be inspected as well.
  6997. * @return {boolean} whether this node (and its parent) is enabled.
  6998. * @see setEnabled
  6999. */
  7000. Node.prototype.isEnabled = function () {
  7001. if (!this._isEnabled) {
  7002. return false;
  7003. }
  7004. if (this.parent) {
  7005. return this.parent.isEnabled();
  7006. }
  7007. return true;
  7008. };
  7009. /**
  7010. * Set the enabled state of this node.
  7011. * @param {boolean} value - the new enabled state
  7012. * @see isEnabled
  7013. */
  7014. Node.prototype.setEnabled = function (value) {
  7015. this._isEnabled = value;
  7016. };
  7017. /**
  7018. * Is this node a descendant of the given node.
  7019. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7020. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7021. * @see parent
  7022. */
  7023. Node.prototype.isDescendantOf = function (ancestor) {
  7024. if (this.parent) {
  7025. if (this.parent === ancestor) {
  7026. return true;
  7027. }
  7028. return this.parent.isDescendantOf(ancestor);
  7029. }
  7030. return false;
  7031. };
  7032. Node.prototype._getDescendants = function (list, results) {
  7033. for (var index = 0; index < list.length; index++) {
  7034. var item = list[index];
  7035. if (item.isDescendantOf(this)) {
  7036. results.push(item);
  7037. }
  7038. }
  7039. };
  7040. /**
  7041. * Will return all nodes that have this node as parent.
  7042. * @return {BABYLON.Node[]} all children nodes of all types.
  7043. */
  7044. Node.prototype.getDescendants = function () {
  7045. var results = [];
  7046. this._getDescendants(this._scene.meshes, results);
  7047. this._getDescendants(this._scene.lights, results);
  7048. this._getDescendants(this._scene.cameras, results);
  7049. return results;
  7050. };
  7051. Node.prototype._setReady = function (state) {
  7052. if (state == this._isReady) {
  7053. return;
  7054. }
  7055. if (!state) {
  7056. this._isReady = false;
  7057. return;
  7058. }
  7059. this._isReady = true;
  7060. if (this.onReady) {
  7061. this.onReady(this);
  7062. }
  7063. };
  7064. return Node;
  7065. })();
  7066. BABYLON.Node = Node;
  7067. })(BABYLON || (BABYLON = {}));
  7068. //# sourceMappingURL=babylon.node.js.map
  7069. var BABYLON;
  7070. (function (BABYLON) {
  7071. var FilesInput = (function () {
  7072. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7073. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7074. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7075. this._engine = p_engine;
  7076. this._canvas = p_canvas;
  7077. this._currentScene = p_scene;
  7078. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7079. this._progressCallback = p_progressCallback;
  7080. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7081. this._textureLoadingCallback = p_textureLoadingCallback;
  7082. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7083. }
  7084. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7085. var _this = this;
  7086. if (p_elementToMonitor) {
  7087. this._elementToMonitor = p_elementToMonitor;
  7088. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7089. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7090. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7091. }
  7092. };
  7093. FilesInput.prototype.renderFunction = function () {
  7094. if (this._additionnalRenderLoopLogicCallback) {
  7095. this._additionnalRenderLoopLogicCallback();
  7096. }
  7097. if (this._currentScene) {
  7098. if (this._textureLoadingCallback) {
  7099. var remaining = this._currentScene.getWaitingItemsCount();
  7100. if (remaining > 0) {
  7101. this._textureLoadingCallback(remaining);
  7102. }
  7103. }
  7104. this._currentScene.render();
  7105. }
  7106. };
  7107. FilesInput.prototype.drag = function (e) {
  7108. e.stopPropagation();
  7109. e.preventDefault();
  7110. };
  7111. FilesInput.prototype.drop = function (eventDrop) {
  7112. eventDrop.stopPropagation();
  7113. eventDrop.preventDefault();
  7114. this.loadFiles(eventDrop);
  7115. };
  7116. FilesInput.prototype.loadFiles = function (event) {
  7117. if (this._startingProcessingFilesCallback)
  7118. this._startingProcessingFilesCallback();
  7119. // Handling data transfer via drag'n'drop
  7120. if (event && event.dataTransfer && event.dataTransfer.files) {
  7121. this._filesToLoad = event.dataTransfer.files;
  7122. }
  7123. // Handling files from input files
  7124. if (event && event.target && event.target.files) {
  7125. this._filesToLoad = event.target.files;
  7126. }
  7127. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7128. for (var i = 0; i < this._filesToLoad.length; i++) {
  7129. switch (this._filesToLoad[i].type) {
  7130. case "image/jpeg":
  7131. case "image/png":
  7132. case "image/bmp":
  7133. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7134. break;
  7135. case "image/targa":
  7136. case "image/vnd.ms-dds":
  7137. case "audio/wav":
  7138. case "audio/x-wav":
  7139. case "audio/mp3":
  7140. case "audio/mpeg":
  7141. case "audio/mpeg3":
  7142. case "audio/x-mpeg-3":
  7143. case "audio/ogg":
  7144. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7145. break;
  7146. default:
  7147. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7148. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7149. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  7150. this._sceneFileToLoad = this._filesToLoad[i];
  7151. }
  7152. break;
  7153. }
  7154. }
  7155. this.reload();
  7156. }
  7157. };
  7158. FilesInput.prototype.reload = function () {
  7159. var _this = this;
  7160. var that = this;
  7161. // If a ".babylon" file has been provided
  7162. if (this._sceneFileToLoad) {
  7163. if (this._currentScene) {
  7164. this._engine.stopRenderLoop();
  7165. this._currentScene.dispose();
  7166. }
  7167. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7168. that._currentScene = newScene;
  7169. // Wait for textures and shaders to be ready
  7170. that._currentScene.executeWhenReady(function () {
  7171. // Attach camera to canvas inputs
  7172. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7173. that._currentScene.createDefaultCameraOrLight();
  7174. }
  7175. that._currentScene.activeCamera.attachControl(that._canvas);
  7176. if (that._sceneLoadedCallback) {
  7177. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7178. }
  7179. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7180. });
  7181. }, function (progress) {
  7182. if (_this._progressCallback) {
  7183. _this._progressCallback(progress);
  7184. }
  7185. });
  7186. }
  7187. else {
  7188. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7189. }
  7190. };
  7191. FilesInput.FilesTextures = new Array();
  7192. FilesInput.FilesToLoad = new Array();
  7193. return FilesInput;
  7194. })();
  7195. BABYLON.FilesInput = FilesInput;
  7196. })(BABYLON || (BABYLON = {}));
  7197. //# sourceMappingURL=babylon.filesInput.js.map
  7198. var BABYLON;
  7199. (function (BABYLON) {
  7200. var IntersectionInfo = (function () {
  7201. function IntersectionInfo(bu, bv, distance) {
  7202. this.bu = bu;
  7203. this.bv = bv;
  7204. this.distance = distance;
  7205. this.faceId = 0;
  7206. this.subMeshId = 0;
  7207. }
  7208. return IntersectionInfo;
  7209. })();
  7210. BABYLON.IntersectionInfo = IntersectionInfo;
  7211. var PickingInfo = (function () {
  7212. function PickingInfo() {
  7213. this.hit = false;
  7214. this.distance = 0;
  7215. this.pickedPoint = null;
  7216. this.pickedMesh = null;
  7217. this.bu = 0;
  7218. this.bv = 0;
  7219. this.faceId = -1;
  7220. this.subMeshId = 0;
  7221. }
  7222. // Methods
  7223. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7224. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7225. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7226. return null;
  7227. }
  7228. var indices = this.pickedMesh.getIndices();
  7229. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7230. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7231. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7232. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7233. normal0 = normal0.scale(this.bu);
  7234. normal1 = normal1.scale(this.bv);
  7235. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7236. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7237. if (useWorldCoordinates) {
  7238. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7239. }
  7240. return result;
  7241. };
  7242. PickingInfo.prototype.getTextureCoordinates = function () {
  7243. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7244. return null;
  7245. }
  7246. var indices = this.pickedMesh.getIndices();
  7247. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7248. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7249. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7250. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7251. uv0 = uv0.scale(this.bu);
  7252. uv1 = uv1.scale(this.bv);
  7253. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7254. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7255. };
  7256. return PickingInfo;
  7257. })();
  7258. BABYLON.PickingInfo = PickingInfo;
  7259. })(BABYLON || (BABYLON = {}));
  7260. //# sourceMappingURL=babylon.pickingInfo.js.map
  7261. var BABYLON;
  7262. (function (BABYLON) {
  7263. var BoundingSphere = (function () {
  7264. function BoundingSphere(minimum, maximum) {
  7265. this.minimum = minimum;
  7266. this.maximum = maximum;
  7267. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7268. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7269. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7270. this.radius = distance * 0.5;
  7271. this.centerWorld = BABYLON.Vector3.Zero();
  7272. this._update(BABYLON.Matrix.Identity());
  7273. }
  7274. // Methods
  7275. BoundingSphere.prototype._update = function (world) {
  7276. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7277. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7278. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7279. };
  7280. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7281. for (var i = 0; i < 6; i++) {
  7282. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7283. return false;
  7284. }
  7285. return true;
  7286. };
  7287. BoundingSphere.prototype.intersectsPoint = function (point) {
  7288. var x = this.centerWorld.x - point.x;
  7289. var y = this.centerWorld.y - point.y;
  7290. var z = this.centerWorld.z - point.z;
  7291. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7292. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7293. return false;
  7294. return true;
  7295. };
  7296. // Statics
  7297. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7298. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7299. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7300. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7301. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7302. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7303. return false;
  7304. return true;
  7305. };
  7306. return BoundingSphere;
  7307. })();
  7308. BABYLON.BoundingSphere = BoundingSphere;
  7309. })(BABYLON || (BABYLON = {}));
  7310. //# sourceMappingURL=babylon.boundingSphere.js.map
  7311. var BABYLON;
  7312. (function (BABYLON) {
  7313. var BoundingBox = (function () {
  7314. function BoundingBox(minimum, maximum) {
  7315. this.minimum = minimum;
  7316. this.maximum = maximum;
  7317. this.vectors = new Array();
  7318. this.vectorsWorld = new Array();
  7319. // Bounding vectors
  7320. this.vectors.push(this.minimum.clone());
  7321. this.vectors.push(this.maximum.clone());
  7322. this.vectors.push(this.minimum.clone());
  7323. this.vectors[2].x = this.maximum.x;
  7324. this.vectors.push(this.minimum.clone());
  7325. this.vectors[3].y = this.maximum.y;
  7326. this.vectors.push(this.minimum.clone());
  7327. this.vectors[4].z = this.maximum.z;
  7328. this.vectors.push(this.maximum.clone());
  7329. this.vectors[5].z = this.minimum.z;
  7330. this.vectors.push(this.maximum.clone());
  7331. this.vectors[6].x = this.minimum.x;
  7332. this.vectors.push(this.maximum.clone());
  7333. this.vectors[7].y = this.minimum.y;
  7334. // OBB
  7335. this.center = this.maximum.add(this.minimum).scale(0.5);
  7336. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7337. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7338. // World
  7339. for (var index = 0; index < this.vectors.length; index++) {
  7340. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7341. }
  7342. this.minimumWorld = BABYLON.Vector3.Zero();
  7343. this.maximumWorld = BABYLON.Vector3.Zero();
  7344. this._update(BABYLON.Matrix.Identity());
  7345. }
  7346. // Methods
  7347. BoundingBox.prototype.getWorldMatrix = function () {
  7348. return this._worldMatrix;
  7349. };
  7350. BoundingBox.prototype._update = function (world) {
  7351. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7352. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7353. for (var index = 0; index < this.vectors.length; index++) {
  7354. var v = this.vectorsWorld[index];
  7355. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7356. if (v.x < this.minimumWorld.x)
  7357. this.minimumWorld.x = v.x;
  7358. if (v.y < this.minimumWorld.y)
  7359. this.minimumWorld.y = v.y;
  7360. if (v.z < this.minimumWorld.z)
  7361. this.minimumWorld.z = v.z;
  7362. if (v.x > this.maximumWorld.x)
  7363. this.maximumWorld.x = v.x;
  7364. if (v.y > this.maximumWorld.y)
  7365. this.maximumWorld.y = v.y;
  7366. if (v.z > this.maximumWorld.z)
  7367. this.maximumWorld.z = v.z;
  7368. }
  7369. // OBB
  7370. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7371. this.center.scaleInPlace(0.5);
  7372. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7373. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7374. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7375. this._worldMatrix = world;
  7376. };
  7377. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7378. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7379. };
  7380. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7381. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7382. };
  7383. BoundingBox.prototype.intersectsPoint = function (point) {
  7384. var delta = -BABYLON.Engine.Epsilon;
  7385. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7386. return false;
  7387. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7388. return false;
  7389. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7390. return false;
  7391. return true;
  7392. };
  7393. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7394. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7395. };
  7396. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7397. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7398. return false;
  7399. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7400. return false;
  7401. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7402. return false;
  7403. return true;
  7404. };
  7405. // Statics
  7406. BoundingBox.Intersects = function (box0, box1) {
  7407. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7408. return false;
  7409. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7410. return false;
  7411. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7412. return false;
  7413. return true;
  7414. };
  7415. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7416. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7417. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7418. return (num <= (sphereRadius * sphereRadius));
  7419. };
  7420. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7421. for (var p = 0; p < 6; p++) {
  7422. for (var i = 0; i < 8; i++) {
  7423. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7424. return false;
  7425. }
  7426. }
  7427. }
  7428. return true;
  7429. };
  7430. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7431. for (var p = 0; p < 6; p++) {
  7432. var inCount = 8;
  7433. for (var i = 0; i < 8; i++) {
  7434. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7435. --inCount;
  7436. }
  7437. else {
  7438. break;
  7439. }
  7440. }
  7441. if (inCount === 0)
  7442. return false;
  7443. }
  7444. return true;
  7445. };
  7446. return BoundingBox;
  7447. })();
  7448. BABYLON.BoundingBox = BoundingBox;
  7449. })(BABYLON || (BABYLON = {}));
  7450. //# sourceMappingURL=babylon.boundingBox.js.map
  7451. var BABYLON;
  7452. (function (BABYLON) {
  7453. var computeBoxExtents = function (axis, box) {
  7454. var p = BABYLON.Vector3.Dot(box.center, axis);
  7455. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7456. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7457. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7458. var r = r0 + r1 + r2;
  7459. return {
  7460. min: p - r,
  7461. max: p + r
  7462. };
  7463. };
  7464. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7465. var axisOverlap = function (axis, box0, box1) {
  7466. var result0 = computeBoxExtents(axis, box0);
  7467. var result1 = computeBoxExtents(axis, box1);
  7468. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7469. };
  7470. var BoundingInfo = (function () {
  7471. function BoundingInfo(minimum, maximum) {
  7472. this.minimum = minimum;
  7473. this.maximum = maximum;
  7474. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7475. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7476. }
  7477. // Methods
  7478. BoundingInfo.prototype._update = function (world) {
  7479. this.boundingBox._update(world);
  7480. this.boundingSphere._update(world);
  7481. };
  7482. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7483. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7484. return false;
  7485. return this.boundingBox.isInFrustum(frustumPlanes);
  7486. };
  7487. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7488. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7489. };
  7490. BoundingInfo.prototype._checkCollision = function (collider) {
  7491. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7492. };
  7493. BoundingInfo.prototype.intersectsPoint = function (point) {
  7494. if (!this.boundingSphere.centerWorld) {
  7495. return false;
  7496. }
  7497. if (!this.boundingSphere.intersectsPoint(point)) {
  7498. return false;
  7499. }
  7500. if (!this.boundingBox.intersectsPoint(point)) {
  7501. return false;
  7502. }
  7503. return true;
  7504. };
  7505. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7506. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7507. return false;
  7508. }
  7509. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7510. return false;
  7511. }
  7512. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7513. return false;
  7514. }
  7515. if (!precise) {
  7516. return true;
  7517. }
  7518. var box0 = this.boundingBox;
  7519. var box1 = boundingInfo.boundingBox;
  7520. if (!axisOverlap(box0.directions[0], box0, box1))
  7521. return false;
  7522. if (!axisOverlap(box0.directions[1], box0, box1))
  7523. return false;
  7524. if (!axisOverlap(box0.directions[2], box0, box1))
  7525. return false;
  7526. if (!axisOverlap(box1.directions[0], box0, box1))
  7527. return false;
  7528. if (!axisOverlap(box1.directions[1], box0, box1))
  7529. return false;
  7530. if (!axisOverlap(box1.directions[2], box0, box1))
  7531. return false;
  7532. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7533. return false;
  7534. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7535. return false;
  7536. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7537. return false;
  7538. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7539. return false;
  7540. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7541. return false;
  7542. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7543. return false;
  7544. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7545. return false;
  7546. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7547. return false;
  7548. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7549. return false;
  7550. return true;
  7551. };
  7552. return BoundingInfo;
  7553. })();
  7554. BABYLON.BoundingInfo = BoundingInfo;
  7555. })(BABYLON || (BABYLON = {}));
  7556. //# sourceMappingURL=babylon.boundingInfo.js.map
  7557. var BABYLON;
  7558. (function (BABYLON) {
  7559. var AbstractMesh = (function (_super) {
  7560. __extends(AbstractMesh, _super);
  7561. function AbstractMesh(name, scene) {
  7562. var _this = this;
  7563. _super.call(this, name, scene);
  7564. // Properties
  7565. this.definedFacingForward = true; // orientation for POV movement & rotation
  7566. this.position = new BABYLON.Vector3(0, 0, 0);
  7567. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7568. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7569. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7570. this.visibility = 1.0;
  7571. this.alphaIndex = Number.MAX_VALUE;
  7572. this.infiniteDistance = false;
  7573. this.isVisible = true;
  7574. this.isPickable = true;
  7575. this.showBoundingBox = false;
  7576. this.showSubMeshesBoundingBox = false;
  7577. this.onDispose = null;
  7578. this.isBlocker = false;
  7579. this.renderingGroupId = 0;
  7580. this.receiveShadows = false;
  7581. this.renderOutline = false;
  7582. this.outlineColor = BABYLON.Color3.Red();
  7583. this.outlineWidth = 0.02;
  7584. this.renderOverlay = false;
  7585. this.overlayColor = BABYLON.Color3.Red();
  7586. this.overlayAlpha = 0.5;
  7587. this.hasVertexAlpha = false;
  7588. this.useVertexColors = true;
  7589. this.applyFog = true;
  7590. this.useOctreeForRenderingSelection = true;
  7591. this.useOctreeForPicking = true;
  7592. this.useOctreeForCollisions = true;
  7593. this.layerMask = 0x0FFFFFFF;
  7594. this.alwaysSelectAsActiveMesh = false;
  7595. // Physics
  7596. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7597. // Collisions
  7598. this._checkCollisions = false;
  7599. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7600. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7601. this._collider = new BABYLON.Collider();
  7602. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7603. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7604. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7605. // Cache
  7606. this._localScaling = BABYLON.Matrix.Zero();
  7607. this._localRotation = BABYLON.Matrix.Zero();
  7608. this._localTranslation = BABYLON.Matrix.Zero();
  7609. this._localBillboard = BABYLON.Matrix.Zero();
  7610. this._localPivotScaling = BABYLON.Matrix.Zero();
  7611. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7612. this._localWorld = BABYLON.Matrix.Zero();
  7613. this._worldMatrix = BABYLON.Matrix.Zero();
  7614. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7615. this._absolutePosition = BABYLON.Vector3.Zero();
  7616. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7617. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7618. this._isDirty = false;
  7619. this._pivotMatrix = BABYLON.Matrix.Identity();
  7620. this._isDisposed = false;
  7621. this._renderId = 0;
  7622. this._intersectionsInProgress = new Array();
  7623. this._onAfterWorldMatrixUpdate = new Array();
  7624. this._isWorldMatrixFrozen = false;
  7625. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7626. if (collidedMesh === void 0) { collidedMesh = null; }
  7627. //TODO move this to the collision coordinator!
  7628. if (_this.getScene().workerCollisions)
  7629. newPosition.multiplyInPlace(_this._collider.radius);
  7630. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7631. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7632. _this.position.addInPlace(_this._diffPositionForCollisions);
  7633. }
  7634. };
  7635. scene.addMesh(this);
  7636. }
  7637. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7638. get: function () {
  7639. return AbstractMesh._BILLBOARDMODE_NONE;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7645. get: function () {
  7646. return AbstractMesh._BILLBOARDMODE_X;
  7647. },
  7648. enumerable: true,
  7649. configurable: true
  7650. });
  7651. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7652. get: function () {
  7653. return AbstractMesh._BILLBOARDMODE_Y;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7659. get: function () {
  7660. return AbstractMesh._BILLBOARDMODE_Z;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7666. get: function () {
  7667. return AbstractMesh._BILLBOARDMODE_ALL;
  7668. },
  7669. enumerable: true,
  7670. configurable: true
  7671. });
  7672. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7673. // Methods
  7674. get: function () {
  7675. return false;
  7676. },
  7677. enumerable: true,
  7678. configurable: true
  7679. });
  7680. AbstractMesh.prototype.getLOD = function (camera) {
  7681. return this;
  7682. };
  7683. AbstractMesh.prototype.getTotalVertices = function () {
  7684. return 0;
  7685. };
  7686. AbstractMesh.prototype.getIndices = function () {
  7687. return null;
  7688. };
  7689. AbstractMesh.prototype.getVerticesData = function (kind) {
  7690. return null;
  7691. };
  7692. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7693. return false;
  7694. };
  7695. AbstractMesh.prototype.getBoundingInfo = function () {
  7696. if (this._masterMesh) {
  7697. return this._masterMesh.getBoundingInfo();
  7698. }
  7699. if (!this._boundingInfo) {
  7700. this._updateBoundingInfo();
  7701. }
  7702. return this._boundingInfo;
  7703. };
  7704. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7705. get: function () {
  7706. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7707. },
  7708. enumerable: true,
  7709. configurable: true
  7710. });
  7711. AbstractMesh.prototype._preActivate = function () {
  7712. };
  7713. AbstractMesh.prototype._activate = function (renderId) {
  7714. this._renderId = renderId;
  7715. };
  7716. AbstractMesh.prototype.getWorldMatrix = function () {
  7717. if (this._masterMesh) {
  7718. return this._masterMesh.getWorldMatrix();
  7719. }
  7720. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7721. this.computeWorldMatrix();
  7722. }
  7723. return this._worldMatrix;
  7724. };
  7725. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7726. get: function () {
  7727. return this._worldMatrix;
  7728. },
  7729. enumerable: true,
  7730. configurable: true
  7731. });
  7732. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7733. get: function () {
  7734. return this._absolutePosition;
  7735. },
  7736. enumerable: true,
  7737. configurable: true
  7738. });
  7739. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7740. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7741. this.computeWorldMatrix(true);
  7742. this._isWorldMatrixFrozen = true;
  7743. };
  7744. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7745. this._isWorldMatrixFrozen = false;
  7746. this.computeWorldMatrix(true);
  7747. };
  7748. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7749. get: function () {
  7750. return this._isWorldMatrixFrozen;
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7756. axis.normalize();
  7757. if (!this.rotationQuaternion) {
  7758. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7759. this.rotation = BABYLON.Vector3.Zero();
  7760. }
  7761. if (!space || space === BABYLON.Space.LOCAL) {
  7762. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7763. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7764. }
  7765. else {
  7766. if (this.parent) {
  7767. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7768. invertParentWorldMatrix.invert();
  7769. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7770. }
  7771. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7772. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7773. }
  7774. };
  7775. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7776. var displacementVector = axis.scale(distance);
  7777. if (!space || space === BABYLON.Space.LOCAL) {
  7778. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7779. this.setPositionWithLocalVector(tempV3);
  7780. }
  7781. else {
  7782. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7783. }
  7784. };
  7785. AbstractMesh.prototype.getAbsolutePosition = function () {
  7786. this.computeWorldMatrix();
  7787. return this._absolutePosition;
  7788. };
  7789. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7790. if (!absolutePosition) {
  7791. return;
  7792. }
  7793. var absolutePositionX;
  7794. var absolutePositionY;
  7795. var absolutePositionZ;
  7796. if (absolutePosition.x === undefined) {
  7797. if (arguments.length < 3) {
  7798. return;
  7799. }
  7800. absolutePositionX = arguments[0];
  7801. absolutePositionY = arguments[1];
  7802. absolutePositionZ = arguments[2];
  7803. }
  7804. else {
  7805. absolutePositionX = absolutePosition.x;
  7806. absolutePositionY = absolutePosition.y;
  7807. absolutePositionZ = absolutePosition.z;
  7808. }
  7809. if (this.parent) {
  7810. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7811. invertParentWorldMatrix.invert();
  7812. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7813. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7814. }
  7815. else {
  7816. this.position.x = absolutePositionX;
  7817. this.position.y = absolutePositionY;
  7818. this.position.z = absolutePositionZ;
  7819. }
  7820. };
  7821. // ================================== Point of View Movement =================================
  7822. /**
  7823. * Perform relative position change from the point of view of behind the front of the mesh.
  7824. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7825. * Supports definition of mesh facing forward or backward.
  7826. * @param {number} amountRight
  7827. * @param {number} amountUp
  7828. * @param {number} amountForward
  7829. */
  7830. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7831. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7832. };
  7833. /**
  7834. * Calculate relative position change from the point of view of behind the front of the mesh.
  7835. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7836. * Supports definition of mesh facing forward or backward.
  7837. * @param {number} amountRight
  7838. * @param {number} amountUp
  7839. * @param {number} amountForward
  7840. */
  7841. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7842. var rotMatrix = new BABYLON.Matrix();
  7843. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7844. rotQuaternion.toRotationMatrix(rotMatrix);
  7845. var translationDelta = BABYLON.Vector3.Zero();
  7846. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7847. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7848. return translationDelta;
  7849. };
  7850. // ================================== Point of View Rotation =================================
  7851. /**
  7852. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7853. * Supports definition of mesh facing forward or backward.
  7854. * @param {number} flipBack
  7855. * @param {number} twirlClockwise
  7856. * @param {number} tiltRight
  7857. */
  7858. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7859. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7860. };
  7861. /**
  7862. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7863. * Supports definition of mesh facing forward or backward.
  7864. * @param {number} flipBack
  7865. * @param {number} twirlClockwise
  7866. * @param {number} tiltRight
  7867. */
  7868. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7869. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7870. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7871. };
  7872. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7873. this._pivotMatrix = matrix;
  7874. this._cache.pivotMatrixUpdated = true;
  7875. };
  7876. AbstractMesh.prototype.getPivotMatrix = function () {
  7877. return this._pivotMatrix;
  7878. };
  7879. AbstractMesh.prototype._isSynchronized = function () {
  7880. if (this._isDirty) {
  7881. return false;
  7882. }
  7883. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7884. return false;
  7885. if (this._cache.pivotMatrixUpdated) {
  7886. return false;
  7887. }
  7888. if (this.infiniteDistance) {
  7889. return false;
  7890. }
  7891. if (!this._cache.position.equals(this.position))
  7892. return false;
  7893. if (this.rotationQuaternion) {
  7894. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7895. return false;
  7896. }
  7897. else {
  7898. if (!this._cache.rotation.equals(this.rotation))
  7899. return false;
  7900. }
  7901. if (!this._cache.scaling.equals(this.scaling))
  7902. return false;
  7903. return true;
  7904. };
  7905. AbstractMesh.prototype._initCache = function () {
  7906. _super.prototype._initCache.call(this);
  7907. this._cache.localMatrixUpdated = false;
  7908. this._cache.position = BABYLON.Vector3.Zero();
  7909. this._cache.scaling = BABYLON.Vector3.Zero();
  7910. this._cache.rotation = BABYLON.Vector3.Zero();
  7911. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7912. };
  7913. AbstractMesh.prototype.markAsDirty = function (property) {
  7914. if (property === "rotation") {
  7915. this.rotationQuaternion = null;
  7916. }
  7917. this._currentRenderId = Number.MAX_VALUE;
  7918. this._isDirty = true;
  7919. };
  7920. AbstractMesh.prototype._updateBoundingInfo = function () {
  7921. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7922. this._boundingInfo._update(this.worldMatrixFromCache);
  7923. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7924. };
  7925. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7926. if (!this.subMeshes) {
  7927. return;
  7928. }
  7929. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7930. var subMesh = this.subMeshes[subIndex];
  7931. subMesh.updateBoundingInfo(matrix);
  7932. }
  7933. };
  7934. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7935. if (this._isWorldMatrixFrozen) {
  7936. return this._worldMatrix;
  7937. }
  7938. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7939. return this._worldMatrix;
  7940. }
  7941. this._cache.position.copyFrom(this.position);
  7942. this._cache.scaling.copyFrom(this.scaling);
  7943. this._cache.pivotMatrixUpdated = false;
  7944. this._currentRenderId = this.getScene().getRenderId();
  7945. this._isDirty = false;
  7946. // Scaling
  7947. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7948. // Rotation
  7949. if (this.rotationQuaternion) {
  7950. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7951. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7952. }
  7953. else {
  7954. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7955. this._cache.rotation.copyFrom(this.rotation);
  7956. }
  7957. // Translation
  7958. if (this.infiniteDistance && !this.parent) {
  7959. var camera = this.getScene().activeCamera;
  7960. var cameraWorldMatrix = camera.getWorldMatrix();
  7961. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7962. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7963. }
  7964. else {
  7965. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7966. }
  7967. // Composing transformations
  7968. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7969. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7970. // Billboarding
  7971. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7972. var localPosition = this.position.clone();
  7973. var zero = this.getScene().activeCamera.globalPosition.clone();
  7974. if (this.parent && this.parent.position) {
  7975. localPosition.addInPlace(this.parent.position);
  7976. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7977. }
  7978. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7979. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7980. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7981. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7982. zero.y = localPosition.y + 0.001;
  7983. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7984. zero.z = localPosition.z + 0.001;
  7985. }
  7986. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7987. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7988. this._localBillboard.invert();
  7989. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7990. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7991. }
  7992. // Local world
  7993. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7994. // Parent
  7995. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7996. this._markSyncedWithParent();
  7997. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7998. }
  7999. else {
  8000. this._worldMatrix.copyFrom(this._localWorld);
  8001. }
  8002. // Bounding info
  8003. this._updateBoundingInfo();
  8004. // Absolute position
  8005. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8006. // Callbacks
  8007. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8008. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8009. }
  8010. return this._worldMatrix;
  8011. };
  8012. /**
  8013. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8014. * @param func: callback function to add
  8015. */
  8016. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8017. this._onAfterWorldMatrixUpdate.push(func);
  8018. };
  8019. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8020. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8021. if (index > -1) {
  8022. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8023. }
  8024. };
  8025. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8026. this.computeWorldMatrix();
  8027. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8028. };
  8029. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8030. this.computeWorldMatrix();
  8031. var invLocalWorldMatrix = this._localWorld.clone();
  8032. invLocalWorldMatrix.invert();
  8033. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8034. };
  8035. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8036. this.computeWorldMatrix(true);
  8037. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8038. };
  8039. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8040. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8041. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8042. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8043. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8044. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8045. /// <returns>Mesh oriented towards targetMesh</returns>
  8046. yawCor = yawCor || 0; // default to zero if undefined
  8047. pitchCor = pitchCor || 0;
  8048. rollCor = rollCor || 0;
  8049. var dv = targetPoint.subtract(this.position);
  8050. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8051. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8052. var pitch = Math.atan2(dv.y, len);
  8053. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8054. };
  8055. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8056. return this._boundingInfo.isInFrustum(frustumPlanes);
  8057. };
  8058. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8059. if (!camera) {
  8060. camera = this.getScene().activeCamera;
  8061. }
  8062. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8063. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8064. return false;
  8065. }
  8066. return true;
  8067. };
  8068. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8069. if (!this._boundingInfo || !mesh._boundingInfo) {
  8070. return false;
  8071. }
  8072. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8073. };
  8074. AbstractMesh.prototype.intersectsPoint = function (point) {
  8075. if (!this._boundingInfo) {
  8076. return false;
  8077. }
  8078. return this._boundingInfo.intersectsPoint(point);
  8079. };
  8080. // Physics
  8081. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8082. var physicsEngine = this.getScene().getPhysicsEngine();
  8083. if (!physicsEngine) {
  8084. return;
  8085. }
  8086. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8087. if (impostor.impostor) {
  8088. // Old API
  8089. options = impostor;
  8090. impostor = impostor.impostor;
  8091. }
  8092. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8093. physicsEngine._unregisterMesh(this);
  8094. return;
  8095. }
  8096. if (!options) {
  8097. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8098. }
  8099. else {
  8100. if (!options.mass && options.mass !== 0)
  8101. options.mass = 0;
  8102. if (!options.friction && options.friction !== 0)
  8103. options.friction = 0.2;
  8104. if (!options.restitution && options.restitution !== 0)
  8105. options.restitution = 0.2;
  8106. }
  8107. this._physicImpostor = impostor;
  8108. this._physicsMass = options.mass;
  8109. this._physicsFriction = options.friction;
  8110. this._physicRestitution = options.restitution;
  8111. return physicsEngine._registerMesh(this, impostor, options);
  8112. };
  8113. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8114. if (!this._physicImpostor) {
  8115. return BABYLON.PhysicsEngine.NoImpostor;
  8116. }
  8117. return this._physicImpostor;
  8118. };
  8119. AbstractMesh.prototype.getPhysicsMass = function () {
  8120. if (!this._physicsMass) {
  8121. return 0;
  8122. }
  8123. return this._physicsMass;
  8124. };
  8125. AbstractMesh.prototype.getPhysicsFriction = function () {
  8126. if (!this._physicsFriction) {
  8127. return 0;
  8128. }
  8129. return this._physicsFriction;
  8130. };
  8131. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8132. if (!this._physicRestitution) {
  8133. return 0;
  8134. }
  8135. return this._physicRestitution;
  8136. };
  8137. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8138. if (!camera) {
  8139. camera = this.getScene().activeCamera;
  8140. }
  8141. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8142. };
  8143. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8144. if (!camera) {
  8145. camera = this.getScene().activeCamera;
  8146. }
  8147. return this.absolutePosition.subtract(camera.position).length();
  8148. };
  8149. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8150. if (!this._physicImpostor) {
  8151. return;
  8152. }
  8153. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8154. };
  8155. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8156. if (!this._physicImpostor) {
  8157. return;
  8158. }
  8159. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8160. };
  8161. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8162. if (!this._physicImpostor) {
  8163. return;
  8164. }
  8165. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8166. };
  8167. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8168. // Collisions
  8169. get: function () {
  8170. return this._checkCollisions;
  8171. },
  8172. set: function (collisionEnabled) {
  8173. this._checkCollisions = collisionEnabled;
  8174. if (this.getScene().workerCollisions) {
  8175. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8176. }
  8177. },
  8178. enumerable: true,
  8179. configurable: true
  8180. });
  8181. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8182. var globalPosition = this.getAbsolutePosition();
  8183. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8184. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8185. this._collider.radius = this.ellipsoid;
  8186. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8187. };
  8188. // Submeshes octree
  8189. /**
  8190. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8191. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8192. */
  8193. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8194. if (maxCapacity === void 0) { maxCapacity = 64; }
  8195. if (maxDepth === void 0) { maxDepth = 2; }
  8196. if (!this._submeshesOctree) {
  8197. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8198. }
  8199. this.computeWorldMatrix(true);
  8200. // Update octree
  8201. var bbox = this.getBoundingInfo().boundingBox;
  8202. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8203. return this._submeshesOctree;
  8204. };
  8205. // Collisions
  8206. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8207. this._generatePointsArray();
  8208. // Transformation
  8209. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8210. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8211. subMesh._lastColliderWorldVertices = [];
  8212. subMesh._trianglePlanes = [];
  8213. var start = subMesh.verticesStart;
  8214. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8215. for (var i = start; i < end; i++) {
  8216. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8217. }
  8218. }
  8219. // Collide
  8220. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8221. if (collider.collisionFound) {
  8222. collider.collidedMesh = this;
  8223. }
  8224. };
  8225. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8226. var subMeshes;
  8227. var len;
  8228. // Octrees
  8229. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8230. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8231. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8232. len = intersections.length;
  8233. subMeshes = intersections.data;
  8234. }
  8235. else {
  8236. subMeshes = this.subMeshes;
  8237. len = subMeshes.length;
  8238. }
  8239. for (var index = 0; index < len; index++) {
  8240. var subMesh = subMeshes[index];
  8241. // Bounding test
  8242. if (len > 1 && !subMesh._checkCollision(collider))
  8243. continue;
  8244. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8245. }
  8246. };
  8247. AbstractMesh.prototype._checkCollision = function (collider) {
  8248. // Bounding box test
  8249. if (!this._boundingInfo._checkCollision(collider))
  8250. return;
  8251. // Transformation matrix
  8252. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8253. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8254. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8255. };
  8256. // Picking
  8257. AbstractMesh.prototype._generatePointsArray = function () {
  8258. return false;
  8259. };
  8260. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8261. var pickingInfo = new BABYLON.PickingInfo();
  8262. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8263. return pickingInfo;
  8264. }
  8265. if (!this._generatePointsArray()) {
  8266. return pickingInfo;
  8267. }
  8268. var intersectInfo = null;
  8269. // Octrees
  8270. var subMeshes;
  8271. var len;
  8272. if (this._submeshesOctree && this.useOctreeForPicking) {
  8273. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8274. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8275. len = intersections.length;
  8276. subMeshes = intersections.data;
  8277. }
  8278. else {
  8279. subMeshes = this.subMeshes;
  8280. len = subMeshes.length;
  8281. }
  8282. for (var index = 0; index < len; index++) {
  8283. var subMesh = subMeshes[index];
  8284. // Bounding test
  8285. if (len > 1 && !subMesh.canIntersects(ray))
  8286. continue;
  8287. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8288. if (currentIntersectInfo) {
  8289. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8290. intersectInfo = currentIntersectInfo;
  8291. intersectInfo.subMeshId = index;
  8292. if (fastCheck) {
  8293. break;
  8294. }
  8295. }
  8296. }
  8297. }
  8298. if (intersectInfo) {
  8299. // Get picked point
  8300. var world = this.getWorldMatrix();
  8301. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8302. var direction = ray.direction.clone();
  8303. direction = direction.scale(intersectInfo.distance);
  8304. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8305. var pickedPoint = worldOrigin.add(worldDirection);
  8306. // Return result
  8307. pickingInfo.hit = true;
  8308. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8309. pickingInfo.pickedPoint = pickedPoint;
  8310. pickingInfo.pickedMesh = this;
  8311. pickingInfo.bu = intersectInfo.bu;
  8312. pickingInfo.bv = intersectInfo.bv;
  8313. pickingInfo.faceId = intersectInfo.faceId;
  8314. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8315. return pickingInfo;
  8316. }
  8317. return pickingInfo;
  8318. };
  8319. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8320. return null;
  8321. };
  8322. AbstractMesh.prototype.releaseSubMeshes = function () {
  8323. if (this.subMeshes) {
  8324. while (this.subMeshes.length) {
  8325. this.subMeshes[0].dispose();
  8326. }
  8327. }
  8328. else {
  8329. this.subMeshes = new Array();
  8330. }
  8331. };
  8332. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8333. var index;
  8334. // Physics
  8335. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8336. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8337. }
  8338. // Intersections in progress
  8339. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8340. var other = this._intersectionsInProgress[index];
  8341. var pos = other._intersectionsInProgress.indexOf(this);
  8342. other._intersectionsInProgress.splice(pos, 1);
  8343. }
  8344. this._intersectionsInProgress = [];
  8345. // SubMeshes
  8346. this.releaseSubMeshes();
  8347. // Remove from scene
  8348. this.getScene().removeMesh(this);
  8349. if (!doNotRecurse) {
  8350. // Particles
  8351. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8352. if (this.getScene().particleSystems[index].emitter === this) {
  8353. this.getScene().particleSystems[index].dispose();
  8354. index--;
  8355. }
  8356. }
  8357. // Children
  8358. var objects = this.getScene().meshes.slice(0);
  8359. for (index = 0; index < objects.length; index++) {
  8360. if (objects[index].parent === this) {
  8361. objects[index].dispose();
  8362. }
  8363. }
  8364. }
  8365. else {
  8366. for (index = 0; index < this.getScene().meshes.length; index++) {
  8367. var obj = this.getScene().meshes[index];
  8368. if (obj.parent === this) {
  8369. obj.parent = null;
  8370. obj.computeWorldMatrix(true);
  8371. }
  8372. }
  8373. }
  8374. this._onAfterWorldMatrixUpdate = [];
  8375. this._isDisposed = true;
  8376. // Callback
  8377. if (this.onDispose) {
  8378. this.onDispose();
  8379. }
  8380. };
  8381. // Statics
  8382. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8383. AbstractMesh._BILLBOARDMODE_X = 1;
  8384. AbstractMesh._BILLBOARDMODE_Y = 2;
  8385. AbstractMesh._BILLBOARDMODE_Z = 4;
  8386. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8387. return AbstractMesh;
  8388. })(BABYLON.Node);
  8389. BABYLON.AbstractMesh = AbstractMesh;
  8390. })(BABYLON || (BABYLON = {}));
  8391. //# sourceMappingURL=babylon.abstractMesh.js.map
  8392. var BABYLON;
  8393. (function (BABYLON) {
  8394. var Light = (function (_super) {
  8395. __extends(Light, _super);
  8396. function Light(name, scene) {
  8397. _super.call(this, name, scene);
  8398. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8399. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8400. this.intensity = 1.0;
  8401. this.range = Number.MAX_VALUE;
  8402. this.includeOnlyWithLayerMask = 0;
  8403. this.includedOnlyMeshes = new Array();
  8404. this.excludedMeshes = new Array();
  8405. this.excludeWithLayerMask = 0;
  8406. this._excludedMeshesIds = new Array();
  8407. this._includedOnlyMeshesIds = new Array();
  8408. scene.addLight(this);
  8409. }
  8410. Light.prototype.getShadowGenerator = function () {
  8411. return this._shadowGenerator;
  8412. };
  8413. Light.prototype.getAbsolutePosition = function () {
  8414. return BABYLON.Vector3.Zero();
  8415. };
  8416. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8417. };
  8418. Light.prototype._getWorldMatrix = function () {
  8419. return BABYLON.Matrix.Identity();
  8420. };
  8421. Light.prototype.canAffectMesh = function (mesh) {
  8422. if (!mesh) {
  8423. return true;
  8424. }
  8425. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8426. return false;
  8427. }
  8428. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8429. return false;
  8430. }
  8431. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8432. return false;
  8433. }
  8434. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8435. return false;
  8436. }
  8437. return true;
  8438. };
  8439. Light.prototype.getWorldMatrix = function () {
  8440. this._currentRenderId = this.getScene().getRenderId();
  8441. var worldMatrix = this._getWorldMatrix();
  8442. if (this.parent && this.parent.getWorldMatrix) {
  8443. if (!this._parentedWorldMatrix) {
  8444. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8445. }
  8446. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8447. this._markSyncedWithParent();
  8448. return this._parentedWorldMatrix;
  8449. }
  8450. return worldMatrix;
  8451. };
  8452. Light.prototype.dispose = function () {
  8453. if (this._shadowGenerator) {
  8454. this._shadowGenerator.dispose();
  8455. this._shadowGenerator = null;
  8456. }
  8457. // Remove from scene
  8458. this.getScene().removeLight(this);
  8459. };
  8460. return Light;
  8461. })(BABYLON.Node);
  8462. BABYLON.Light = Light;
  8463. })(BABYLON || (BABYLON = {}));
  8464. //# sourceMappingURL=babylon.light.js.map
  8465. var BABYLON;
  8466. (function (BABYLON) {
  8467. var PointLight = (function (_super) {
  8468. __extends(PointLight, _super);
  8469. function PointLight(name, position, scene) {
  8470. _super.call(this, name, scene);
  8471. this.position = position;
  8472. }
  8473. PointLight.prototype.getAbsolutePosition = function () {
  8474. return this._transformedPosition ? this._transformedPosition : this.position;
  8475. };
  8476. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8477. if (this.parent && this.parent.getWorldMatrix) {
  8478. if (!this._transformedPosition) {
  8479. this._transformedPosition = BABYLON.Vector3.Zero();
  8480. }
  8481. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8482. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8483. return;
  8484. }
  8485. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8486. };
  8487. PointLight.prototype.getShadowGenerator = function () {
  8488. return null;
  8489. };
  8490. PointLight.prototype._getWorldMatrix = function () {
  8491. if (!this._worldMatrix) {
  8492. this._worldMatrix = BABYLON.Matrix.Identity();
  8493. }
  8494. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8495. return this._worldMatrix;
  8496. };
  8497. return PointLight;
  8498. })(BABYLON.Light);
  8499. BABYLON.PointLight = PointLight;
  8500. })(BABYLON || (BABYLON = {}));
  8501. //# sourceMappingURL=babylon.pointLight.js.map
  8502. var BABYLON;
  8503. (function (BABYLON) {
  8504. var SpotLight = (function (_super) {
  8505. __extends(SpotLight, _super);
  8506. function SpotLight(name, position, direction, angle, exponent, scene) {
  8507. _super.call(this, name, scene);
  8508. this.position = position;
  8509. this.direction = direction;
  8510. this.angle = angle;
  8511. this.exponent = exponent;
  8512. }
  8513. SpotLight.prototype.getAbsolutePosition = function () {
  8514. return this.transformedPosition ? this.transformedPosition : this.position;
  8515. };
  8516. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8517. var activeCamera = this.getScene().activeCamera;
  8518. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8519. };
  8520. SpotLight.prototype.supportsVSM = function () {
  8521. return true;
  8522. };
  8523. SpotLight.prototype.needRefreshPerFrame = function () {
  8524. return false;
  8525. };
  8526. SpotLight.prototype.setDirectionToTarget = function (target) {
  8527. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8528. return this.direction;
  8529. };
  8530. SpotLight.prototype.computeTransformedPosition = function () {
  8531. if (this.parent && this.parent.getWorldMatrix) {
  8532. if (!this.transformedPosition) {
  8533. this.transformedPosition = BABYLON.Vector3.Zero();
  8534. }
  8535. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8536. return true;
  8537. }
  8538. return false;
  8539. };
  8540. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8541. var normalizeDirection;
  8542. if (this.parent && this.parent.getWorldMatrix) {
  8543. if (!this._transformedDirection) {
  8544. this._transformedDirection = BABYLON.Vector3.Zero();
  8545. }
  8546. this.computeTransformedPosition();
  8547. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8548. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8549. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8550. }
  8551. else {
  8552. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8553. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8554. }
  8555. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8556. };
  8557. SpotLight.prototype._getWorldMatrix = function () {
  8558. if (!this._worldMatrix) {
  8559. this._worldMatrix = BABYLON.Matrix.Identity();
  8560. }
  8561. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8562. return this._worldMatrix;
  8563. };
  8564. return SpotLight;
  8565. })(BABYLON.Light);
  8566. BABYLON.SpotLight = SpotLight;
  8567. })(BABYLON || (BABYLON = {}));
  8568. //# sourceMappingURL=babylon.spotLight.js.map
  8569. var BABYLON;
  8570. (function (BABYLON) {
  8571. var HemisphericLight = (function (_super) {
  8572. __extends(HemisphericLight, _super);
  8573. function HemisphericLight(name, direction, scene) {
  8574. _super.call(this, name, scene);
  8575. this.direction = direction;
  8576. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8577. }
  8578. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8579. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8580. return this.direction;
  8581. };
  8582. HemisphericLight.prototype.getShadowGenerator = function () {
  8583. return null;
  8584. };
  8585. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8586. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8587. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8588. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8589. };
  8590. HemisphericLight.prototype._getWorldMatrix = function () {
  8591. if (!this._worldMatrix) {
  8592. this._worldMatrix = BABYLON.Matrix.Identity();
  8593. }
  8594. return this._worldMatrix;
  8595. };
  8596. return HemisphericLight;
  8597. })(BABYLON.Light);
  8598. BABYLON.HemisphericLight = HemisphericLight;
  8599. })(BABYLON || (BABYLON = {}));
  8600. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8601. var BABYLON;
  8602. (function (BABYLON) {
  8603. var DirectionalLight = (function (_super) {
  8604. __extends(DirectionalLight, _super);
  8605. function DirectionalLight(name, direction, scene) {
  8606. _super.call(this, name, scene);
  8607. this.direction = direction;
  8608. this.shadowOrthoScale = 0.5;
  8609. this.position = direction.scale(-1);
  8610. }
  8611. DirectionalLight.prototype.getAbsolutePosition = function () {
  8612. return this.transformedPosition ? this.transformedPosition : this.position;
  8613. };
  8614. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8615. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8616. return this.direction;
  8617. };
  8618. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8619. var orthoLeft = Number.MAX_VALUE;
  8620. var orthoRight = Number.MIN_VALUE;
  8621. var orthoTop = Number.MIN_VALUE;
  8622. var orthoBottom = Number.MAX_VALUE;
  8623. var tempVector3 = BABYLON.Vector3.Zero();
  8624. var activeCamera = this.getScene().activeCamera;
  8625. // Check extends
  8626. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8627. var mesh = renderList[meshIndex];
  8628. if (!mesh) {
  8629. continue;
  8630. }
  8631. var boundingInfo = mesh.getBoundingInfo();
  8632. if (!boundingInfo) {
  8633. continue;
  8634. }
  8635. var boundingBox = boundingInfo.boundingBox;
  8636. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8637. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8638. if (tempVector3.x < orthoLeft)
  8639. orthoLeft = tempVector3.x;
  8640. if (tempVector3.y < orthoBottom)
  8641. orthoBottom = tempVector3.y;
  8642. if (tempVector3.x > orthoRight)
  8643. orthoRight = tempVector3.x;
  8644. if (tempVector3.y > orthoTop)
  8645. orthoTop = tempVector3.y;
  8646. }
  8647. }
  8648. var xOffset = orthoRight - orthoLeft;
  8649. var yOffset = orthoTop - orthoBottom;
  8650. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8651. };
  8652. DirectionalLight.prototype.supportsVSM = function () {
  8653. return true;
  8654. };
  8655. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8656. return true;
  8657. };
  8658. DirectionalLight.prototype.computeTransformedPosition = function () {
  8659. if (this.parent && this.parent.getWorldMatrix) {
  8660. if (!this.transformedPosition) {
  8661. this.transformedPosition = BABYLON.Vector3.Zero();
  8662. }
  8663. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8664. return true;
  8665. }
  8666. return false;
  8667. };
  8668. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8669. if (this.parent && this.parent.getWorldMatrix) {
  8670. if (!this._transformedDirection) {
  8671. this._transformedDirection = BABYLON.Vector3.Zero();
  8672. }
  8673. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8674. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8675. return;
  8676. }
  8677. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8678. };
  8679. DirectionalLight.prototype._getWorldMatrix = function () {
  8680. if (!this._worldMatrix) {
  8681. this._worldMatrix = BABYLON.Matrix.Identity();
  8682. }
  8683. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8684. return this._worldMatrix;
  8685. };
  8686. return DirectionalLight;
  8687. })(BABYLON.Light);
  8688. BABYLON.DirectionalLight = DirectionalLight;
  8689. })(BABYLON || (BABYLON = {}));
  8690. //# sourceMappingURL=babylon.directionalLight.js.map
  8691. var BABYLON;
  8692. (function (BABYLON) {
  8693. var ShadowGenerator = (function () {
  8694. function ShadowGenerator(mapSize, light) {
  8695. var _this = this;
  8696. // Members
  8697. this._filter = ShadowGenerator.FILTER_NONE;
  8698. this.blurScale = 2;
  8699. this._blurBoxOffset = 0;
  8700. this._bias = 0.00005;
  8701. this._darkness = 0;
  8702. this._transparencyShadow = false;
  8703. this._viewMatrix = BABYLON.Matrix.Zero();
  8704. this._projectionMatrix = BABYLON.Matrix.Zero();
  8705. this._transformMatrix = BABYLON.Matrix.Zero();
  8706. this._worldViewProjection = BABYLON.Matrix.Zero();
  8707. this._light = light;
  8708. this._scene = light.getScene();
  8709. this._mapSize = mapSize;
  8710. light._shadowGenerator = this;
  8711. // Render target
  8712. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8713. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8714. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8715. this._shadowMap.anisotropicFilteringLevel = 1;
  8716. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8717. this._shadowMap.renderParticles = false;
  8718. this._shadowMap.onAfterUnbind = function () {
  8719. if (!_this.useBlurVarianceShadowMap) {
  8720. return;
  8721. }
  8722. if (!_this._shadowMap2) {
  8723. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8724. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8725. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8726. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8727. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8728. _this._downSamplePostprocess.onApply = function (effect) {
  8729. effect.setTexture("textureSampler", _this._shadowMap);
  8730. };
  8731. _this.blurBoxOffset = 1;
  8732. }
  8733. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8734. };
  8735. // Custom render function
  8736. var renderSubMesh = function (subMesh) {
  8737. var mesh = subMesh.getRenderingMesh();
  8738. var scene = _this._scene;
  8739. var engine = scene.getEngine();
  8740. // Culling
  8741. engine.setState(subMesh.getMaterial().backFaceCulling);
  8742. // Managing instances
  8743. var batch = mesh._getInstancesRenderList(subMesh._id);
  8744. if (batch.mustReturn) {
  8745. return;
  8746. }
  8747. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8748. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8749. engine.enableEffect(_this._effect);
  8750. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8751. var material = subMesh.getMaterial();
  8752. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8753. // Alpha test
  8754. if (material && material.needAlphaTesting()) {
  8755. var alphaTexture = material.getAlphaTestTexture();
  8756. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8757. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8758. }
  8759. // Bones
  8760. if (mesh.useBones) {
  8761. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8762. }
  8763. // Draw
  8764. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8765. }
  8766. else {
  8767. // Need to reset refresh rate of the shadowMap
  8768. _this._shadowMap.resetRefreshCounter();
  8769. }
  8770. };
  8771. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8772. var index;
  8773. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8774. renderSubMesh(opaqueSubMeshes.data[index]);
  8775. }
  8776. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8777. renderSubMesh(alphaTestSubMeshes.data[index]);
  8778. }
  8779. if (_this._transparencyShadow) {
  8780. for (index = 0; index < transparentSubMeshes.length; index++) {
  8781. renderSubMesh(transparentSubMeshes.data[index]);
  8782. }
  8783. }
  8784. };
  8785. this._shadowMap.onClear = function (engine) {
  8786. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8787. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8788. }
  8789. else {
  8790. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8791. }
  8792. };
  8793. }
  8794. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8795. // Static
  8796. get: function () {
  8797. return ShadowGenerator._FILTER_NONE;
  8798. },
  8799. enumerable: true,
  8800. configurable: true
  8801. });
  8802. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8803. get: function () {
  8804. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8805. },
  8806. enumerable: true,
  8807. configurable: true
  8808. });
  8809. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8810. get: function () {
  8811. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8812. },
  8813. enumerable: true,
  8814. configurable: true
  8815. });
  8816. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8817. get: function () {
  8818. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8819. },
  8820. enumerable: true,
  8821. configurable: true
  8822. });
  8823. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8824. get: function () {
  8825. return this._bias;
  8826. },
  8827. set: function (bias) {
  8828. this._bias = bias;
  8829. },
  8830. enumerable: true,
  8831. configurable: true
  8832. });
  8833. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8834. get: function () {
  8835. return this._blurBoxOffset;
  8836. },
  8837. set: function (value) {
  8838. var _this = this;
  8839. if (this._blurBoxOffset === value) {
  8840. return;
  8841. }
  8842. this._blurBoxOffset = value;
  8843. if (this._boxBlurPostprocess) {
  8844. this._boxBlurPostprocess.dispose();
  8845. }
  8846. 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);
  8847. this._boxBlurPostprocess.onApply = function (effect) {
  8848. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8849. };
  8850. },
  8851. enumerable: true,
  8852. configurable: true
  8853. });
  8854. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8855. get: function () {
  8856. return this._filter;
  8857. },
  8858. set: function (value) {
  8859. if (this._filter === value) {
  8860. return;
  8861. }
  8862. this._filter = value;
  8863. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8864. this._shadowMap.anisotropicFilteringLevel = 16;
  8865. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8866. }
  8867. else {
  8868. this._shadowMap.anisotropicFilteringLevel = 1;
  8869. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8870. }
  8871. },
  8872. enumerable: true,
  8873. configurable: true
  8874. });
  8875. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8876. get: function () {
  8877. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8878. },
  8879. set: function (value) {
  8880. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8881. },
  8882. enumerable: true,
  8883. configurable: true
  8884. });
  8885. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8886. get: function () {
  8887. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8888. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8889. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8890. },
  8891. set: function (value) {
  8892. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8893. },
  8894. enumerable: true,
  8895. configurable: true
  8896. });
  8897. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8898. get: function () {
  8899. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8900. },
  8901. set: function (value) {
  8902. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8903. },
  8904. enumerable: true,
  8905. configurable: true
  8906. });
  8907. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8908. var defines = [];
  8909. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8910. defines.push("#define VSM");
  8911. }
  8912. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8913. var mesh = subMesh.getMesh();
  8914. var material = subMesh.getMaterial();
  8915. // Alpha test
  8916. if (material && material.needAlphaTesting()) {
  8917. defines.push("#define ALPHATEST");
  8918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8919. attribs.push(BABYLON.VertexBuffer.UVKind);
  8920. defines.push("#define UV1");
  8921. }
  8922. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8923. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8924. defines.push("#define UV2");
  8925. }
  8926. }
  8927. // Bones
  8928. if (mesh.useBones) {
  8929. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8930. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8931. defines.push("#define BONES");
  8932. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8933. }
  8934. // Instances
  8935. if (useInstances) {
  8936. defines.push("#define INSTANCES");
  8937. attribs.push("world0");
  8938. attribs.push("world1");
  8939. attribs.push("world2");
  8940. attribs.push("world3");
  8941. }
  8942. // Get correct effect
  8943. var join = defines.join("\n");
  8944. if (this._cachedDefines !== join) {
  8945. this._cachedDefines = join;
  8946. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8947. }
  8948. return this._effect.isReady();
  8949. };
  8950. ShadowGenerator.prototype.getShadowMap = function () {
  8951. return this._shadowMap;
  8952. };
  8953. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8954. if (this._shadowMap2) {
  8955. return this._shadowMap2;
  8956. }
  8957. return this._shadowMap;
  8958. };
  8959. ShadowGenerator.prototype.getLight = function () {
  8960. return this._light;
  8961. };
  8962. // Methods
  8963. ShadowGenerator.prototype.getTransformMatrix = function () {
  8964. var scene = this._scene;
  8965. if (this._currentRenderID === scene.getRenderId()) {
  8966. return this._transformMatrix;
  8967. }
  8968. this._currentRenderID = scene.getRenderId();
  8969. var lightPosition = this._light.position;
  8970. var lightDirection = this._light.direction;
  8971. if (this._light.computeTransformedPosition()) {
  8972. lightPosition = this._light.transformedPosition;
  8973. }
  8974. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8975. this._cachedPosition = lightPosition.clone();
  8976. this._cachedDirection = lightDirection.clone();
  8977. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8978. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8979. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8980. }
  8981. return this._transformMatrix;
  8982. };
  8983. ShadowGenerator.prototype.getDarkness = function () {
  8984. return this._darkness;
  8985. };
  8986. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8987. if (darkness >= 1.0)
  8988. this._darkness = 1.0;
  8989. else if (darkness <= 0.0)
  8990. this._darkness = 0.0;
  8991. else
  8992. this._darkness = darkness;
  8993. };
  8994. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8995. this._transparencyShadow = hasShadow;
  8996. };
  8997. ShadowGenerator.prototype._packHalf = function (depth) {
  8998. var scale = depth * 255.0;
  8999. var fract = scale - Math.floor(scale);
  9000. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9001. };
  9002. ShadowGenerator.prototype.dispose = function () {
  9003. this._shadowMap.dispose();
  9004. if (this._shadowMap2) {
  9005. this._shadowMap2.dispose();
  9006. }
  9007. if (this._downSamplePostprocess) {
  9008. this._downSamplePostprocess.dispose();
  9009. }
  9010. if (this._boxBlurPostprocess) {
  9011. this._boxBlurPostprocess.dispose();
  9012. }
  9013. };
  9014. ShadowGenerator._FILTER_NONE = 0;
  9015. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9016. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9017. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9018. return ShadowGenerator;
  9019. })();
  9020. BABYLON.ShadowGenerator = ShadowGenerator;
  9021. })(BABYLON || (BABYLON = {}));
  9022. //# sourceMappingURL=babylon.shadowGenerator.js.map
  9023. var BABYLON;
  9024. (function (BABYLON) {
  9025. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9026. if (boxMin.x > sphereCenter.x + sphereRadius)
  9027. return false;
  9028. if (sphereCenter.x - sphereRadius > boxMax.x)
  9029. return false;
  9030. if (boxMin.y > sphereCenter.y + sphereRadius)
  9031. return false;
  9032. if (sphereCenter.y - sphereRadius > boxMax.y)
  9033. return false;
  9034. if (boxMin.z > sphereCenter.z + sphereRadius)
  9035. return false;
  9036. if (sphereCenter.z - sphereRadius > boxMax.z)
  9037. return false;
  9038. return true;
  9039. };
  9040. var getLowestRoot = function (a, b, c, maxR) {
  9041. var determinant = b * b - 4.0 * a * c;
  9042. var result = { root: 0, found: false };
  9043. if (determinant < 0)
  9044. return result;
  9045. var sqrtD = Math.sqrt(determinant);
  9046. var r1 = (-b - sqrtD) / (2.0 * a);
  9047. var r2 = (-b + sqrtD) / (2.0 * a);
  9048. if (r1 > r2) {
  9049. var temp = r2;
  9050. r2 = r1;
  9051. r1 = temp;
  9052. }
  9053. if (r1 > 0 && r1 < maxR) {
  9054. result.root = r1;
  9055. result.found = true;
  9056. return result;
  9057. }
  9058. if (r2 > 0 && r2 < maxR) {
  9059. result.root = r2;
  9060. result.found = true;
  9061. return result;
  9062. }
  9063. return result;
  9064. };
  9065. var Collider = (function () {
  9066. function Collider() {
  9067. this.radius = new BABYLON.Vector3(1, 1, 1);
  9068. this.retry = 0;
  9069. this.basePointWorld = BABYLON.Vector3.Zero();
  9070. this.velocityWorld = BABYLON.Vector3.Zero();
  9071. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9072. this._collisionPoint = BABYLON.Vector3.Zero();
  9073. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9074. this._tempVector = BABYLON.Vector3.Zero();
  9075. this._tempVector2 = BABYLON.Vector3.Zero();
  9076. this._tempVector3 = BABYLON.Vector3.Zero();
  9077. this._tempVector4 = BABYLON.Vector3.Zero();
  9078. this._edge = BABYLON.Vector3.Zero();
  9079. this._baseToVertex = BABYLON.Vector3.Zero();
  9080. this._destinationPoint = BABYLON.Vector3.Zero();
  9081. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9082. this._displacementVector = BABYLON.Vector3.Zero();
  9083. }
  9084. // Methods
  9085. Collider.prototype._initialize = function (source, dir, e) {
  9086. this.velocity = dir;
  9087. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9088. this.basePoint = source;
  9089. source.multiplyToRef(this.radius, this.basePointWorld);
  9090. dir.multiplyToRef(this.radius, this.velocityWorld);
  9091. this.velocityWorldLength = this.velocityWorld.length();
  9092. this.epsilon = e;
  9093. this.collisionFound = false;
  9094. };
  9095. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9096. pa.subtractToRef(point, this._tempVector);
  9097. pb.subtractToRef(point, this._tempVector2);
  9098. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9099. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9100. if (d < 0)
  9101. return false;
  9102. pc.subtractToRef(point, this._tempVector3);
  9103. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9104. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9105. if (d < 0)
  9106. return false;
  9107. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9108. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9109. return d >= 0;
  9110. };
  9111. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9112. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9113. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9114. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9115. return false;
  9116. }
  9117. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9118. return false;
  9119. return true;
  9120. };
  9121. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9122. var t0;
  9123. var embeddedInPlane = false;
  9124. //defensive programming, actually not needed.
  9125. if (!trianglePlaneArray) {
  9126. trianglePlaneArray = [];
  9127. }
  9128. if (!trianglePlaneArray[faceIndex]) {
  9129. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9130. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9131. }
  9132. var trianglePlane = trianglePlaneArray[faceIndex];
  9133. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9134. return;
  9135. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9136. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9137. if (normalDotVelocity == 0) {
  9138. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9139. return;
  9140. embeddedInPlane = true;
  9141. t0 = 0;
  9142. }
  9143. else {
  9144. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9145. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9146. if (t0 > t1) {
  9147. var temp = t1;
  9148. t1 = t0;
  9149. t0 = temp;
  9150. }
  9151. if (t0 > 1.0 || t1 < 0.0)
  9152. return;
  9153. if (t0 < 0)
  9154. t0 = 0;
  9155. if (t0 > 1.0)
  9156. t0 = 1.0;
  9157. }
  9158. this._collisionPoint.copyFromFloats(0, 0, 0);
  9159. var found = false;
  9160. var t = 1.0;
  9161. if (!embeddedInPlane) {
  9162. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9163. this.velocity.scaleToRef(t0, this._tempVector);
  9164. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9165. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9166. found = true;
  9167. t = t0;
  9168. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9169. }
  9170. }
  9171. if (!found) {
  9172. var velocitySquaredLength = this.velocity.lengthSquared();
  9173. var a = velocitySquaredLength;
  9174. this.basePoint.subtractToRef(p1, this._tempVector);
  9175. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9176. var c = this._tempVector.lengthSquared() - 1.0;
  9177. var lowestRoot = getLowestRoot(a, b, c, t);
  9178. if (lowestRoot.found) {
  9179. t = lowestRoot.root;
  9180. found = true;
  9181. this._collisionPoint.copyFrom(p1);
  9182. }
  9183. this.basePoint.subtractToRef(p2, this._tempVector);
  9184. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9185. c = this._tempVector.lengthSquared() - 1.0;
  9186. lowestRoot = getLowestRoot(a, b, c, t);
  9187. if (lowestRoot.found) {
  9188. t = lowestRoot.root;
  9189. found = true;
  9190. this._collisionPoint.copyFrom(p2);
  9191. }
  9192. this.basePoint.subtractToRef(p3, this._tempVector);
  9193. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9194. c = this._tempVector.lengthSquared() - 1.0;
  9195. lowestRoot = getLowestRoot(a, b, c, t);
  9196. if (lowestRoot.found) {
  9197. t = lowestRoot.root;
  9198. found = true;
  9199. this._collisionPoint.copyFrom(p3);
  9200. }
  9201. p2.subtractToRef(p1, this._edge);
  9202. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9203. var edgeSquaredLength = this._edge.lengthSquared();
  9204. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9205. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9206. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9207. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9208. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9209. lowestRoot = getLowestRoot(a, b, c, t);
  9210. if (lowestRoot.found) {
  9211. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9212. if (f >= 0.0 && f <= 1.0) {
  9213. t = lowestRoot.root;
  9214. found = true;
  9215. this._edge.scaleInPlace(f);
  9216. p1.addToRef(this._edge, this._collisionPoint);
  9217. }
  9218. }
  9219. p3.subtractToRef(p2, this._edge);
  9220. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9221. edgeSquaredLength = this._edge.lengthSquared();
  9222. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9223. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9224. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9225. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9226. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9227. lowestRoot = getLowestRoot(a, b, c, t);
  9228. if (lowestRoot.found) {
  9229. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9230. if (f >= 0.0 && f <= 1.0) {
  9231. t = lowestRoot.root;
  9232. found = true;
  9233. this._edge.scaleInPlace(f);
  9234. p2.addToRef(this._edge, this._collisionPoint);
  9235. }
  9236. }
  9237. p1.subtractToRef(p3, this._edge);
  9238. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9239. edgeSquaredLength = this._edge.lengthSquared();
  9240. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9241. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9242. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9243. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9244. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9245. lowestRoot = getLowestRoot(a, b, c, t);
  9246. if (lowestRoot.found) {
  9247. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9248. if (f >= 0.0 && f <= 1.0) {
  9249. t = lowestRoot.root;
  9250. found = true;
  9251. this._edge.scaleInPlace(f);
  9252. p3.addToRef(this._edge, this._collisionPoint);
  9253. }
  9254. }
  9255. }
  9256. if (found) {
  9257. var distToCollision = t * this.velocity.length();
  9258. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9259. if (!this.intersectionPoint) {
  9260. this.intersectionPoint = this._collisionPoint.clone();
  9261. }
  9262. else {
  9263. this.intersectionPoint.copyFrom(this._collisionPoint);
  9264. }
  9265. this.nearestDistance = distToCollision;
  9266. this.collisionFound = true;
  9267. }
  9268. }
  9269. };
  9270. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9271. for (var i = indexStart; i < indexEnd; i += 3) {
  9272. var p1 = pts[indices[i] - decal];
  9273. var p2 = pts[indices[i + 1] - decal];
  9274. var p3 = pts[indices[i + 2] - decal];
  9275. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9276. }
  9277. };
  9278. Collider.prototype._getResponse = function (pos, vel) {
  9279. pos.addToRef(vel, this._destinationPoint);
  9280. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9281. this.basePoint.addToRef(vel, pos);
  9282. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9283. this._slidePlaneNormal.normalize();
  9284. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9285. pos.addInPlace(this._displacementVector);
  9286. this.intersectionPoint.addInPlace(this._displacementVector);
  9287. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9288. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9289. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9290. };
  9291. return Collider;
  9292. })();
  9293. BABYLON.Collider = Collider;
  9294. })(BABYLON || (BABYLON = {}));
  9295. //# sourceMappingURL=babylon.collider.js.map
  9296. var BABYLON;
  9297. (function (BABYLON) {
  9298. //WebWorker code will be inserted to this variable.
  9299. BABYLON.CollisionWorker = "";
  9300. (function (WorkerTaskType) {
  9301. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9302. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9303. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9304. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9305. var WorkerTaskType = BABYLON.WorkerTaskType;
  9306. (function (WorkerReplyType) {
  9307. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9308. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9309. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9310. var WorkerReplyType = BABYLON.WorkerReplyType;
  9311. var CollisionCoordinatorWorker = (function () {
  9312. function CollisionCoordinatorWorker() {
  9313. var _this = this;
  9314. this._scaledPosition = BABYLON.Vector3.Zero();
  9315. this._scaledVelocity = BABYLON.Vector3.Zero();
  9316. this.onMeshUpdated = function (mesh) {
  9317. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9318. };
  9319. this.onGeometryUpdated = function (geometry) {
  9320. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9321. };
  9322. this._afterRender = function () {
  9323. if (!_this._init)
  9324. return;
  9325. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9326. return;
  9327. }
  9328. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9329. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9330. if (_this._runningUpdated > 4) {
  9331. return;
  9332. }
  9333. ++_this._runningUpdated;
  9334. var payload = {
  9335. updatedMeshes: _this._addUpdateMeshesList,
  9336. updatedGeometries: _this._addUpdateGeometriesList,
  9337. removedGeometries: _this._toRemoveGeometryArray,
  9338. removedMeshes: _this._toRemoveMeshesArray
  9339. };
  9340. var message = {
  9341. payload: payload,
  9342. taskType: WorkerTaskType.UPDATE
  9343. };
  9344. var serializable = [];
  9345. for (var id in payload.updatedGeometries) {
  9346. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9347. //prepare transferables
  9348. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9349. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9350. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9351. }
  9352. }
  9353. _this._worker.postMessage(message, serializable);
  9354. _this._addUpdateMeshesList = {};
  9355. _this._addUpdateGeometriesList = {};
  9356. _this._toRemoveGeometryArray = [];
  9357. _this._toRemoveMeshesArray = [];
  9358. };
  9359. this._onMessageFromWorker = function (e) {
  9360. var returnData = e.data;
  9361. if (returnData.error != WorkerReplyType.SUCCESS) {
  9362. //TODO what errors can be returned from the worker?
  9363. BABYLON.Tools.Warn("error returned from worker!");
  9364. return;
  9365. }
  9366. switch (returnData.taskType) {
  9367. case WorkerTaskType.INIT:
  9368. _this._init = true;
  9369. //Update the worked with ALL of the scene's current state
  9370. _this._scene.meshes.forEach(function (mesh) {
  9371. _this.onMeshAdded(mesh);
  9372. });
  9373. _this._scene.getGeometries().forEach(function (geometry) {
  9374. _this.onGeometryAdded(geometry);
  9375. });
  9376. break;
  9377. case WorkerTaskType.UPDATE:
  9378. _this._runningUpdated--;
  9379. break;
  9380. case WorkerTaskType.COLLIDE:
  9381. _this._runningCollisionTask = false;
  9382. var returnPayload = returnData.payload;
  9383. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9384. return;
  9385. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9386. //cleanup
  9387. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9388. break;
  9389. }
  9390. };
  9391. this._collisionsCallbackArray = [];
  9392. this._init = false;
  9393. this._runningUpdated = 0;
  9394. this._runningCollisionTask = false;
  9395. this._addUpdateMeshesList = {};
  9396. this._addUpdateGeometriesList = {};
  9397. this._toRemoveGeometryArray = [];
  9398. this._toRemoveMeshesArray = [];
  9399. }
  9400. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9401. if (!this._init)
  9402. return;
  9403. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9404. return;
  9405. position.divideToRef(collider.radius, this._scaledPosition);
  9406. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9407. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9408. var payload = {
  9409. collider: {
  9410. position: this._scaledPosition.asArray(),
  9411. velocity: this._scaledVelocity.asArray(),
  9412. radius: collider.radius.asArray()
  9413. },
  9414. collisionId: collisionIndex,
  9415. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9416. maximumRetry: maximumRetry
  9417. };
  9418. var message = {
  9419. payload: payload,
  9420. taskType: WorkerTaskType.COLLIDE
  9421. };
  9422. this._worker.postMessage(message);
  9423. };
  9424. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9425. this._scene = scene;
  9426. this._scene.registerAfterRender(this._afterRender);
  9427. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9428. this._worker = new Worker(workerUrl);
  9429. this._worker.onmessage = this._onMessageFromWorker;
  9430. var message = {
  9431. payload: {},
  9432. taskType: WorkerTaskType.INIT
  9433. };
  9434. this._worker.postMessage(message);
  9435. };
  9436. CollisionCoordinatorWorker.prototype.destroy = function () {
  9437. this._scene.unregisterAfterRender(this._afterRender);
  9438. this._worker.terminate();
  9439. };
  9440. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9441. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9442. this.onMeshUpdated(mesh);
  9443. };
  9444. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9445. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9446. };
  9447. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9448. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9449. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9450. this.onGeometryUpdated(geometry);
  9451. };
  9452. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9453. this._toRemoveGeometryArray.push(geometry.id);
  9454. };
  9455. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9456. var submeshes = [];
  9457. if (mesh.subMeshes) {
  9458. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9459. return {
  9460. position: idx,
  9461. verticesStart: sm.verticesStart,
  9462. verticesCount: sm.verticesCount,
  9463. indexStart: sm.indexStart,
  9464. indexCount: sm.indexCount,
  9465. hasMaterial: !!sm.getMaterial(),
  9466. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9467. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9468. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9469. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9470. };
  9471. });
  9472. }
  9473. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9474. return {
  9475. uniqueId: mesh.uniqueId,
  9476. id: mesh.id,
  9477. name: mesh.name,
  9478. geometryId: geometryId,
  9479. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9480. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9481. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9482. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9483. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9484. subMeshes: submeshes,
  9485. checkCollisions: mesh.checkCollisions
  9486. };
  9487. };
  9488. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9489. return {
  9490. id: geometry.id,
  9491. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9492. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9493. indices: new Int32Array(geometry.getIndices() || []),
  9494. };
  9495. };
  9496. return CollisionCoordinatorWorker;
  9497. })();
  9498. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9499. var CollisionCoordinatorLegacy = (function () {
  9500. function CollisionCoordinatorLegacy() {
  9501. this._scaledPosition = BABYLON.Vector3.Zero();
  9502. this._scaledVelocity = BABYLON.Vector3.Zero();
  9503. this._finalPosition = BABYLON.Vector3.Zero();
  9504. }
  9505. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9506. position.divideToRef(collider.radius, this._scaledPosition);
  9507. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9508. collider.collidedMesh = null;
  9509. collider.retry = 0;
  9510. collider.initialVelocity = this._scaledVelocity;
  9511. collider.initialPosition = this._scaledPosition;
  9512. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9513. this._finalPosition.multiplyInPlace(collider.radius);
  9514. //run the callback
  9515. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9516. };
  9517. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9518. this._scene = scene;
  9519. };
  9520. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9521. //Legacy need no destruction method.
  9522. };
  9523. //No update in legacy mode
  9524. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9525. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9526. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9527. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9528. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9529. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9530. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9531. if (excludedMesh === void 0) { excludedMesh = null; }
  9532. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9533. if (collider.retry >= maximumRetry) {
  9534. finalPosition.copyFrom(position);
  9535. return;
  9536. }
  9537. collider._initialize(position, velocity, closeDistance);
  9538. // Check all meshes
  9539. for (var index = 0; index < this._scene.meshes.length; index++) {
  9540. var mesh = this._scene.meshes[index];
  9541. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9542. mesh._checkCollision(collider);
  9543. }
  9544. }
  9545. if (!collider.collisionFound) {
  9546. position.addToRef(velocity, finalPosition);
  9547. return;
  9548. }
  9549. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9550. collider._getResponse(position, velocity);
  9551. }
  9552. if (velocity.length() <= closeDistance) {
  9553. finalPosition.copyFrom(position);
  9554. return;
  9555. }
  9556. collider.retry++;
  9557. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9558. };
  9559. return CollisionCoordinatorLegacy;
  9560. })();
  9561. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9562. })(BABYLON || (BABYLON = {}));
  9563. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9564. var BABYLON;
  9565. (function (BABYLON) {
  9566. var VRCameraMetrics = (function () {
  9567. function VRCameraMetrics() {
  9568. this.compensateDistorsion = true;
  9569. }
  9570. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9571. get: function () {
  9572. return this.hResolution / (2 * this.vResolution);
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9578. get: function () {
  9579. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9580. },
  9581. enumerable: true,
  9582. configurable: true
  9583. });
  9584. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9585. get: function () {
  9586. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9587. var h = (4 * meters) / this.hScreenSize;
  9588. return BABYLON.Matrix.Translation(h, 0, 0);
  9589. },
  9590. enumerable: true,
  9591. configurable: true
  9592. });
  9593. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9594. get: function () {
  9595. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9596. var h = (4 * meters) / this.hScreenSize;
  9597. return BABYLON.Matrix.Translation(-h, 0, 0);
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9603. get: function () {
  9604. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9610. get: function () {
  9611. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. VRCameraMetrics.GetDefault = function () {
  9617. var result = new VRCameraMetrics();
  9618. result.hResolution = 1280;
  9619. result.vResolution = 800;
  9620. result.hScreenSize = 0.149759993;
  9621. result.vScreenSize = 0.0935999975;
  9622. result.vScreenCenter = 0.0467999987,
  9623. result.eyeToScreenDistance = 0.0410000011;
  9624. result.lensSeparationDistance = 0.0635000020;
  9625. result.interpupillaryDistance = 0.0640000030;
  9626. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9627. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9628. result.postProcessScaleFactor = 1.714605507808412;
  9629. result.lensCenterOffset = 0.151976421;
  9630. return result;
  9631. };
  9632. return VRCameraMetrics;
  9633. })();
  9634. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9635. var Camera = (function (_super) {
  9636. __extends(Camera, _super);
  9637. function Camera(name, position, scene) {
  9638. _super.call(this, name, scene);
  9639. this.position = position;
  9640. // Members
  9641. this.upVector = BABYLON.Vector3.Up();
  9642. this.orthoLeft = null;
  9643. this.orthoRight = null;
  9644. this.orthoBottom = null;
  9645. this.orthoTop = null;
  9646. this.fov = 0.8;
  9647. this.minZ = 1.0;
  9648. this.maxZ = 10000.0;
  9649. this.inertia = 0.9;
  9650. this.mode = Camera.PERSPECTIVE_CAMERA;
  9651. this.isIntermediate = false;
  9652. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9653. this.layerMask = 0x0FFFFFFF;
  9654. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9655. // Camera rig members
  9656. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9657. this._rigCameras = new Array();
  9658. // Cache
  9659. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9660. this._projectionMatrix = new BABYLON.Matrix();
  9661. this._postProcesses = new Array();
  9662. this._postProcessesTakenIndices = [];
  9663. this._activeMeshes = new BABYLON.SmartArray(256);
  9664. this._globalPosition = BABYLON.Vector3.Zero();
  9665. scene.addCamera(this);
  9666. if (!scene.activeCamera) {
  9667. scene.activeCamera = this;
  9668. }
  9669. }
  9670. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9671. get: function () {
  9672. return Camera._PERSPECTIVE_CAMERA;
  9673. },
  9674. enumerable: true,
  9675. configurable: true
  9676. });
  9677. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9678. get: function () {
  9679. return Camera._ORTHOGRAPHIC_CAMERA;
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9685. get: function () {
  9686. return Camera._FOVMODE_VERTICAL_FIXED;
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9692. get: function () {
  9693. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9694. },
  9695. enumerable: true,
  9696. configurable: true
  9697. });
  9698. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9699. get: function () {
  9700. return Camera._RIG_MODE_NONE;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9706. get: function () {
  9707. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9713. get: function () {
  9714. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9715. },
  9716. enumerable: true,
  9717. configurable: true
  9718. });
  9719. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9720. get: function () {
  9721. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9722. },
  9723. enumerable: true,
  9724. configurable: true
  9725. });
  9726. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9727. get: function () {
  9728. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9734. get: function () {
  9735. return Camera._RIG_MODE_VR;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Object.defineProperty(Camera.prototype, "globalPosition", {
  9741. get: function () {
  9742. return this._globalPosition;
  9743. },
  9744. enumerable: true,
  9745. configurable: true
  9746. });
  9747. Camera.prototype.getActiveMeshes = function () {
  9748. return this._activeMeshes;
  9749. };
  9750. Camera.prototype.isActiveMesh = function (mesh) {
  9751. return (this._activeMeshes.indexOf(mesh) !== -1);
  9752. };
  9753. //Cache
  9754. Camera.prototype._initCache = function () {
  9755. _super.prototype._initCache.call(this);
  9756. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9757. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9758. this._cache.mode = undefined;
  9759. this._cache.minZ = undefined;
  9760. this._cache.maxZ = undefined;
  9761. this._cache.fov = undefined;
  9762. this._cache.aspectRatio = undefined;
  9763. this._cache.orthoLeft = undefined;
  9764. this._cache.orthoRight = undefined;
  9765. this._cache.orthoBottom = undefined;
  9766. this._cache.orthoTop = undefined;
  9767. this._cache.renderWidth = undefined;
  9768. this._cache.renderHeight = undefined;
  9769. };
  9770. Camera.prototype._updateCache = function (ignoreParentClass) {
  9771. if (!ignoreParentClass) {
  9772. _super.prototype._updateCache.call(this);
  9773. }
  9774. var engine = this.getEngine();
  9775. this._cache.position.copyFrom(this.position);
  9776. this._cache.upVector.copyFrom(this.upVector);
  9777. this._cache.mode = this.mode;
  9778. this._cache.minZ = this.minZ;
  9779. this._cache.maxZ = this.maxZ;
  9780. this._cache.fov = this.fov;
  9781. this._cache.aspectRatio = engine.getAspectRatio(this);
  9782. this._cache.orthoLeft = this.orthoLeft;
  9783. this._cache.orthoRight = this.orthoRight;
  9784. this._cache.orthoBottom = this.orthoBottom;
  9785. this._cache.orthoTop = this.orthoTop;
  9786. this._cache.renderWidth = engine.getRenderWidth();
  9787. this._cache.renderHeight = engine.getRenderHeight();
  9788. };
  9789. Camera.prototype._updateFromScene = function () {
  9790. this.updateCache();
  9791. this._update();
  9792. };
  9793. // Synchronized
  9794. Camera.prototype._isSynchronized = function () {
  9795. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9796. };
  9797. Camera.prototype._isSynchronizedViewMatrix = function () {
  9798. if (!_super.prototype._isSynchronized.call(this))
  9799. return false;
  9800. return this._cache.position.equals(this.position)
  9801. && this._cache.upVector.equals(this.upVector)
  9802. && this.isSynchronizedWithParent();
  9803. };
  9804. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9805. var check = this._cache.mode === this.mode
  9806. && this._cache.minZ === this.minZ
  9807. && this._cache.maxZ === this.maxZ;
  9808. if (!check) {
  9809. return false;
  9810. }
  9811. var engine = this.getEngine();
  9812. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9813. check = this._cache.fov === this.fov
  9814. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9815. }
  9816. else {
  9817. check = this._cache.orthoLeft === this.orthoLeft
  9818. && this._cache.orthoRight === this.orthoRight
  9819. && this._cache.orthoBottom === this.orthoBottom
  9820. && this._cache.orthoTop === this.orthoTop
  9821. && this._cache.renderWidth === engine.getRenderWidth()
  9822. && this._cache.renderHeight === engine.getRenderHeight();
  9823. }
  9824. return check;
  9825. };
  9826. // Controls
  9827. Camera.prototype.attachControl = function (element) {
  9828. };
  9829. Camera.prototype.detachControl = function (element) {
  9830. };
  9831. Camera.prototype._update = function () {
  9832. this._checkInputs();
  9833. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9834. this._updateRigCameras();
  9835. }
  9836. };
  9837. Camera.prototype._checkInputs = function () {
  9838. };
  9839. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9840. if (insertAt === void 0) { insertAt = null; }
  9841. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9842. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9843. return 0;
  9844. }
  9845. if (insertAt == null || insertAt < 0) {
  9846. this._postProcesses.push(postProcess);
  9847. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9848. return this._postProcesses.length - 1;
  9849. }
  9850. var add = 0;
  9851. if (this._postProcesses[insertAt]) {
  9852. var start = this._postProcesses.length - 1;
  9853. for (var i = start; i >= insertAt + 1; --i) {
  9854. this._postProcesses[i + 1] = this._postProcesses[i];
  9855. }
  9856. add = 1;
  9857. }
  9858. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9859. if (this._postProcessesTakenIndices[i] < insertAt) {
  9860. continue;
  9861. }
  9862. start = this._postProcessesTakenIndices.length - 1;
  9863. for (var j = start; j >= i; --j) {
  9864. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9865. }
  9866. this._postProcessesTakenIndices[i] = insertAt;
  9867. break;
  9868. }
  9869. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9870. this._postProcessesTakenIndices.push(insertAt);
  9871. }
  9872. var result = insertAt + add;
  9873. this._postProcesses[result] = postProcess;
  9874. return result;
  9875. };
  9876. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9877. if (atIndices === void 0) { atIndices = null; }
  9878. var result = [];
  9879. if (!atIndices) {
  9880. var length = this._postProcesses.length;
  9881. for (var i = 0; i < length; i++) {
  9882. if (this._postProcesses[i] !== postProcess) {
  9883. continue;
  9884. }
  9885. delete this._postProcesses[i];
  9886. var index = this._postProcessesTakenIndices.indexOf(i);
  9887. this._postProcessesTakenIndices.splice(index, 1);
  9888. }
  9889. }
  9890. else {
  9891. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9892. for (i = 0; i < atIndices.length; i++) {
  9893. var foundPostProcess = this._postProcesses[atIndices[i]];
  9894. if (foundPostProcess !== postProcess) {
  9895. result.push(i);
  9896. continue;
  9897. }
  9898. delete this._postProcesses[atIndices[i]];
  9899. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9900. this._postProcessesTakenIndices.splice(index, 1);
  9901. }
  9902. }
  9903. return result;
  9904. };
  9905. Camera.prototype.getWorldMatrix = function () {
  9906. if (!this._worldMatrix) {
  9907. this._worldMatrix = BABYLON.Matrix.Identity();
  9908. }
  9909. var viewMatrix = this.getViewMatrix();
  9910. viewMatrix.invertToRef(this._worldMatrix);
  9911. return this._worldMatrix;
  9912. };
  9913. Camera.prototype._getViewMatrix = function () {
  9914. return BABYLON.Matrix.Identity();
  9915. };
  9916. Camera.prototype.getViewMatrix = function (force) {
  9917. this._computedViewMatrix = this._computeViewMatrix(force);
  9918. if (!force && this._isSynchronizedViewMatrix()) {
  9919. return this._computedViewMatrix;
  9920. }
  9921. if (!this.parent || !this.parent.getWorldMatrix) {
  9922. this._globalPosition.copyFrom(this.position);
  9923. }
  9924. else {
  9925. if (!this._worldMatrix) {
  9926. this._worldMatrix = BABYLON.Matrix.Identity();
  9927. }
  9928. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9929. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9930. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9931. this._computedViewMatrix.invert();
  9932. this._markSyncedWithParent();
  9933. }
  9934. this._currentRenderId = this.getScene().getRenderId();
  9935. return this._computedViewMatrix;
  9936. };
  9937. Camera.prototype._computeViewMatrix = function (force) {
  9938. if (!force && this._isSynchronizedViewMatrix()) {
  9939. return this._computedViewMatrix;
  9940. }
  9941. this._computedViewMatrix = this._getViewMatrix();
  9942. this._currentRenderId = this.getScene().getRenderId();
  9943. return this._computedViewMatrix;
  9944. };
  9945. Camera.prototype.getProjectionMatrix = function (force) {
  9946. if (!force && this._isSynchronizedProjectionMatrix()) {
  9947. return this._projectionMatrix;
  9948. }
  9949. var engine = this.getEngine();
  9950. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9951. if (this.minZ <= 0) {
  9952. this.minZ = 0.1;
  9953. }
  9954. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9955. return this._projectionMatrix;
  9956. }
  9957. var halfWidth = engine.getRenderWidth() / 2.0;
  9958. var halfHeight = engine.getRenderHeight() / 2.0;
  9959. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9960. return this._projectionMatrix;
  9961. };
  9962. Camera.prototype.dispose = function () {
  9963. // Remove from scene
  9964. this.getScene().removeCamera(this);
  9965. while (this._rigCameras.length > 0) {
  9966. this._rigCameras.pop().dispose();
  9967. }
  9968. // Postprocesses
  9969. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9970. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9971. }
  9972. };
  9973. // ---- Camera rigs section ----
  9974. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  9975. while (this._rigCameras.length > 0) {
  9976. this._rigCameras.pop().dispose();
  9977. }
  9978. this.cameraRigMode = mode;
  9979. this._cameraRigParams = {};
  9980. switch (this.cameraRigMode) {
  9981. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9982. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  9983. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  9984. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  9985. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  9986. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  9987. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  9988. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  9989. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  9990. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  9991. break;
  9992. }
  9993. var postProcesses = new Array();
  9994. switch (this.cameraRigMode) {
  9995. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9996. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  9997. this._rigCameras[0].isIntermediate = true;
  9998. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  9999. postProcesses[1].onApply = function (effect) {
  10000. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10001. };
  10002. break;
  10003. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10004. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10005. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10006. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10007. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10008. var secondCamIndex = 1 - firstCamIndex;
  10009. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10010. this._rigCameras[firstCamIndex].isIntermediate = true;
  10011. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10012. break;
  10013. case Camera.RIG_MODE_VR:
  10014. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10015. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10016. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10017. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10018. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10019. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10020. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10021. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10022. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10023. if (metrics.compensateDistorsion) {
  10024. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10025. }
  10026. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10027. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10028. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10029. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10030. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10031. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10032. if (metrics.compensateDistorsion) {
  10033. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10034. }
  10035. break;
  10036. }
  10037. this._update();
  10038. };
  10039. Camera.prototype._getVRProjectionMatrix = function () {
  10040. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10041. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10042. return this._projectionMatrix;
  10043. };
  10044. Camera.prototype.setCameraRigParameter = function (name, value) {
  10045. this._cameraRigParams[name] = value;
  10046. //provisionnally:
  10047. if (name === "interaxialDistance") {
  10048. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10049. }
  10050. };
  10051. /**
  10052. * May needs to be overridden by children so sub has required properties to be copied
  10053. */
  10054. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10055. return null;
  10056. };
  10057. /**
  10058. * May needs to be overridden by children
  10059. */
  10060. Camera.prototype._updateRigCameras = function () {
  10061. for (var i = 0; i < this._rigCameras.length; i++) {
  10062. this._rigCameras[i].minZ = this.minZ;
  10063. this._rigCameras[i].maxZ = this.maxZ;
  10064. this._rigCameras[i].fov = this.fov;
  10065. }
  10066. // only update viewport when ANAGLYPH
  10067. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10068. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10069. }
  10070. };
  10071. // Statics
  10072. Camera._PERSPECTIVE_CAMERA = 0;
  10073. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10074. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10075. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10076. Camera._RIG_MODE_NONE = 0;
  10077. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10078. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10079. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10080. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10081. Camera._RIG_MODE_VR = 20;
  10082. return Camera;
  10083. })(BABYLON.Node);
  10084. BABYLON.Camera = Camera;
  10085. })(BABYLON || (BABYLON = {}));
  10086. //# sourceMappingURL=babylon.camera.js.map
  10087. var BABYLON;
  10088. (function (BABYLON) {
  10089. var TargetCamera = (function (_super) {
  10090. __extends(TargetCamera, _super);
  10091. function TargetCamera(name, position, scene) {
  10092. _super.call(this, name, position, scene);
  10093. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10094. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10095. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10096. this.speed = 2.0;
  10097. this.noRotationConstraint = false;
  10098. this.lockedTarget = null;
  10099. this._currentTarget = BABYLON.Vector3.Zero();
  10100. this._viewMatrix = BABYLON.Matrix.Zero();
  10101. this._camMatrix = BABYLON.Matrix.Zero();
  10102. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10103. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10104. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10105. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10106. this._lookAtTemp = BABYLON.Matrix.Zero();
  10107. this._tempMatrix = BABYLON.Matrix.Zero();
  10108. }
  10109. TargetCamera.prototype._getLockedTargetPosition = function () {
  10110. if (!this.lockedTarget) {
  10111. return null;
  10112. }
  10113. return this.lockedTarget.position || this.lockedTarget;
  10114. };
  10115. // Cache
  10116. TargetCamera.prototype._initCache = function () {
  10117. _super.prototype._initCache.call(this);
  10118. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10119. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10120. };
  10121. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10122. if (!ignoreParentClass) {
  10123. _super.prototype._updateCache.call(this);
  10124. }
  10125. var lockedTargetPosition = this._getLockedTargetPosition();
  10126. if (!lockedTargetPosition) {
  10127. this._cache.lockedTarget = null;
  10128. }
  10129. else {
  10130. if (!this._cache.lockedTarget) {
  10131. this._cache.lockedTarget = lockedTargetPosition.clone();
  10132. }
  10133. else {
  10134. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10135. }
  10136. }
  10137. this._cache.rotation.copyFrom(this.rotation);
  10138. };
  10139. // Synchronized
  10140. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10141. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10142. return false;
  10143. }
  10144. var lockedTargetPosition = this._getLockedTargetPosition();
  10145. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10146. && this._cache.rotation.equals(this.rotation);
  10147. };
  10148. // Methods
  10149. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10150. var engine = this.getEngine();
  10151. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10152. };
  10153. // Target
  10154. TargetCamera.prototype.setTarget = function (target) {
  10155. this.upVector.normalize();
  10156. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10157. this._camMatrix.invert();
  10158. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10159. var vDir = target.subtract(this.position);
  10160. if (vDir.x >= 0.0) {
  10161. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10162. }
  10163. else {
  10164. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10165. }
  10166. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10167. if (isNaN(this.rotation.x)) {
  10168. this.rotation.x = 0;
  10169. }
  10170. if (isNaN(this.rotation.y)) {
  10171. this.rotation.y = 0;
  10172. }
  10173. if (isNaN(this.rotation.z)) {
  10174. this.rotation.z = 0;
  10175. }
  10176. };
  10177. TargetCamera.prototype.getTarget = function () {
  10178. return this._currentTarget;
  10179. };
  10180. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10181. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10182. };
  10183. TargetCamera.prototype._updatePosition = function () {
  10184. this.position.addInPlace(this.cameraDirection);
  10185. };
  10186. TargetCamera.prototype._checkInputs = function () {
  10187. var needToMove = this._decideIfNeedsToMove();
  10188. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10189. // Move
  10190. if (needToMove) {
  10191. this._updatePosition();
  10192. }
  10193. // Rotate
  10194. if (needToRotate) {
  10195. this.rotation.x += this.cameraRotation.x;
  10196. this.rotation.y += this.cameraRotation.y;
  10197. if (!this.noRotationConstraint) {
  10198. var limit = (Math.PI / 2) * 0.95;
  10199. if (this.rotation.x > limit)
  10200. this.rotation.x = limit;
  10201. if (this.rotation.x < -limit)
  10202. this.rotation.x = -limit;
  10203. }
  10204. }
  10205. // Inertia
  10206. if (needToMove) {
  10207. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10208. this.cameraDirection.x = 0;
  10209. }
  10210. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10211. this.cameraDirection.y = 0;
  10212. }
  10213. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10214. this.cameraDirection.z = 0;
  10215. }
  10216. this.cameraDirection.scaleInPlace(this.inertia);
  10217. }
  10218. if (needToRotate) {
  10219. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10220. this.cameraRotation.x = 0;
  10221. }
  10222. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10223. this.cameraRotation.y = 0;
  10224. }
  10225. this.cameraRotation.scaleInPlace(this.inertia);
  10226. }
  10227. _super.prototype._checkInputs.call(this);
  10228. };
  10229. TargetCamera.prototype._getViewMatrix = function () {
  10230. if (!this.lockedTarget) {
  10231. // Compute
  10232. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10233. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10234. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10235. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10236. this._lookAtTemp.invert();
  10237. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10238. }
  10239. else {
  10240. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10241. }
  10242. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10243. // Computing target and final matrix
  10244. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10245. }
  10246. else {
  10247. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10248. }
  10249. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10250. return this._viewMatrix;
  10251. };
  10252. TargetCamera.prototype._getVRViewMatrix = function () {
  10253. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10254. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10255. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10256. // Computing target and final matrix
  10257. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10258. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10259. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10260. return this._viewMatrix;
  10261. };
  10262. /**
  10263. * @override
  10264. * Override Camera.createRigCamera
  10265. */
  10266. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10267. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10268. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10269. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10270. rigCamera._cameraRigParams = {};
  10271. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10272. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10273. }
  10274. return rigCamera;
  10275. }
  10276. return null;
  10277. };
  10278. /**
  10279. * @override
  10280. * Override Camera._updateRigCameras
  10281. */
  10282. TargetCamera.prototype._updateRigCameras = function () {
  10283. switch (this.cameraRigMode) {
  10284. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10285. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10286. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10287. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10288. case BABYLON.Camera.RIG_MODE_VR:
  10289. var camLeft = this._rigCameras[0];
  10290. var camRight = this._rigCameras[1];
  10291. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10292. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10293. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10294. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10295. camLeft.position.copyFrom(this.position);
  10296. camRight.position.copyFrom(this.position);
  10297. }
  10298. else {
  10299. camLeft.setTarget(this.getTarget());
  10300. camRight.setTarget(this.getTarget());
  10301. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10302. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10303. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10304. }
  10305. break;
  10306. }
  10307. _super.prototype._updateRigCameras.call(this);
  10308. };
  10309. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10310. if (!this._rigCamTransformMatrix) {
  10311. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10312. }
  10313. var target = this.getTarget();
  10314. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10315. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10316. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10317. };
  10318. return TargetCamera;
  10319. })(BABYLON.Camera);
  10320. BABYLON.TargetCamera = TargetCamera;
  10321. })(BABYLON || (BABYLON = {}));
  10322. //# sourceMappingURL=babylon.targetCamera.js.map
  10323. var BABYLON;
  10324. (function (BABYLON) {
  10325. var FreeCamera = (function (_super) {
  10326. __extends(FreeCamera, _super);
  10327. function FreeCamera(name, position, scene) {
  10328. var _this = this;
  10329. _super.call(this, name, position, scene);
  10330. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10331. this.keysUp = [38];
  10332. this.keysDown = [40];
  10333. this.keysLeft = [37];
  10334. this.keysRight = [39];
  10335. this.checkCollisions = false;
  10336. this.applyGravity = false;
  10337. this.angularSensibility = 2000.0;
  10338. this._keys = [];
  10339. this._collider = new BABYLON.Collider();
  10340. this._needMoveForGravity = false;
  10341. this._oldPosition = BABYLON.Vector3.Zero();
  10342. this._diffPosition = BABYLON.Vector3.Zero();
  10343. this._newPosition = BABYLON.Vector3.Zero();
  10344. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10345. if (collidedMesh === void 0) { collidedMesh = null; }
  10346. //TODO move this to the collision coordinator!
  10347. if (_this.getScene().workerCollisions)
  10348. newPosition.multiplyInPlace(_this._collider.radius);
  10349. var updatePosition = function (newPos) {
  10350. _this._newPosition.copyFrom(newPos);
  10351. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10352. var oldPosition = _this.position.clone();
  10353. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10354. _this.position.addInPlace(_this._diffPosition);
  10355. if (_this.onCollide && collidedMesh) {
  10356. _this.onCollide(collidedMesh);
  10357. }
  10358. }
  10359. };
  10360. updatePosition(newPosition);
  10361. };
  10362. }
  10363. // Controls
  10364. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10365. var _this = this;
  10366. var previousPosition;
  10367. var engine = this.getEngine();
  10368. if (this._attachedElement) {
  10369. return;
  10370. }
  10371. this._attachedElement = element;
  10372. if (this._onMouseDown === undefined) {
  10373. this._onMouseDown = function (evt) {
  10374. previousPosition = {
  10375. x: evt.clientX,
  10376. y: evt.clientY
  10377. };
  10378. if (!noPreventDefault) {
  10379. evt.preventDefault();
  10380. }
  10381. };
  10382. this._onMouseUp = function (evt) {
  10383. previousPosition = null;
  10384. if (!noPreventDefault) {
  10385. evt.preventDefault();
  10386. }
  10387. };
  10388. this._onMouseOut = function (evt) {
  10389. previousPosition = null;
  10390. _this._keys = [];
  10391. if (!noPreventDefault) {
  10392. evt.preventDefault();
  10393. }
  10394. };
  10395. this._onMouseMove = function (evt) {
  10396. if (!previousPosition && !engine.isPointerLock) {
  10397. return;
  10398. }
  10399. var offsetX;
  10400. var offsetY;
  10401. if (!engine.isPointerLock) {
  10402. offsetX = evt.clientX - previousPosition.x;
  10403. offsetY = evt.clientY - previousPosition.y;
  10404. }
  10405. else {
  10406. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10407. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10408. }
  10409. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10410. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10411. previousPosition = {
  10412. x: evt.clientX,
  10413. y: evt.clientY
  10414. };
  10415. if (!noPreventDefault) {
  10416. evt.preventDefault();
  10417. }
  10418. };
  10419. this._onKeyDown = function (evt) {
  10420. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10421. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10422. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10423. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10424. var index = _this._keys.indexOf(evt.keyCode);
  10425. if (index === -1) {
  10426. _this._keys.push(evt.keyCode);
  10427. }
  10428. if (!noPreventDefault) {
  10429. evt.preventDefault();
  10430. }
  10431. }
  10432. };
  10433. this._onKeyUp = function (evt) {
  10434. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10435. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10436. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10437. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10438. var index = _this._keys.indexOf(evt.keyCode);
  10439. if (index >= 0) {
  10440. _this._keys.splice(index, 1);
  10441. }
  10442. if (!noPreventDefault) {
  10443. evt.preventDefault();
  10444. }
  10445. }
  10446. };
  10447. this._onLostFocus = function () {
  10448. _this._keys = [];
  10449. };
  10450. this._reset = function () {
  10451. _this._keys = [];
  10452. previousPosition = null;
  10453. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10454. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10455. };
  10456. }
  10457. element.addEventListener("mousedown", this._onMouseDown, false);
  10458. element.addEventListener("mouseup", this._onMouseUp, false);
  10459. element.addEventListener("mouseout", this._onMouseOut, false);
  10460. element.addEventListener("mousemove", this._onMouseMove, false);
  10461. BABYLON.Tools.RegisterTopRootEvents([
  10462. { name: "keydown", handler: this._onKeyDown },
  10463. { name: "keyup", handler: this._onKeyUp },
  10464. { name: "blur", handler: this._onLostFocus }
  10465. ]);
  10466. };
  10467. FreeCamera.prototype.detachControl = function (element) {
  10468. if (this._attachedElement != element) {
  10469. return;
  10470. }
  10471. element.removeEventListener("mousedown", this._onMouseDown);
  10472. element.removeEventListener("mouseup", this._onMouseUp);
  10473. element.removeEventListener("mouseout", this._onMouseOut);
  10474. element.removeEventListener("mousemove", this._onMouseMove);
  10475. BABYLON.Tools.UnregisterTopRootEvents([
  10476. { name: "keydown", handler: this._onKeyDown },
  10477. { name: "keyup", handler: this._onKeyUp },
  10478. { name: "blur", handler: this._onLostFocus }
  10479. ]);
  10480. this._attachedElement = null;
  10481. if (this._reset) {
  10482. this._reset();
  10483. }
  10484. };
  10485. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10486. var globalPosition;
  10487. if (this.parent) {
  10488. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10489. }
  10490. else {
  10491. globalPosition = this.position;
  10492. }
  10493. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10494. this._collider.radius = this.ellipsoid;
  10495. //add gravity to the velocity to prevent the dual-collision checking
  10496. if (this.applyGravity) {
  10497. velocity.addInPlace(this.getScene().gravity);
  10498. }
  10499. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10500. };
  10501. FreeCamera.prototype._checkInputs = function () {
  10502. if (!this._localDirection) {
  10503. this._localDirection = BABYLON.Vector3.Zero();
  10504. this._transformedDirection = BABYLON.Vector3.Zero();
  10505. }
  10506. // Keyboard
  10507. for (var index = 0; index < this._keys.length; index++) {
  10508. var keyCode = this._keys[index];
  10509. var speed = this._computeLocalCameraSpeed();
  10510. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10511. this._localDirection.copyFromFloats(-speed, 0, 0);
  10512. }
  10513. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10514. this._localDirection.copyFromFloats(0, 0, speed);
  10515. }
  10516. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10517. this._localDirection.copyFromFloats(speed, 0, 0);
  10518. }
  10519. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10520. this._localDirection.copyFromFloats(0, 0, -speed);
  10521. }
  10522. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10523. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10524. this.cameraDirection.addInPlace(this._transformedDirection);
  10525. }
  10526. _super.prototype._checkInputs.call(this);
  10527. };
  10528. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10529. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10530. };
  10531. FreeCamera.prototype._updatePosition = function () {
  10532. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10533. this._collideWithWorld(this.cameraDirection);
  10534. }
  10535. else {
  10536. this.position.addInPlace(this.cameraDirection);
  10537. }
  10538. };
  10539. return FreeCamera;
  10540. })(BABYLON.TargetCamera);
  10541. BABYLON.FreeCamera = FreeCamera;
  10542. })(BABYLON || (BABYLON = {}));
  10543. //# sourceMappingURL=babylon.freeCamera.js.map
  10544. var BABYLON;
  10545. (function (BABYLON) {
  10546. var FollowCamera = (function (_super) {
  10547. __extends(FollowCamera, _super);
  10548. function FollowCamera(name, position, scene) {
  10549. _super.call(this, name, position, scene);
  10550. this.radius = 12;
  10551. this.rotationOffset = 0;
  10552. this.heightOffset = 4;
  10553. this.cameraAcceleration = 0.05;
  10554. this.maxCameraSpeed = 20;
  10555. }
  10556. FollowCamera.prototype.getRadians = function (degrees) {
  10557. return degrees * Math.PI / 180;
  10558. };
  10559. FollowCamera.prototype.follow = function (cameraTarget) {
  10560. if (!cameraTarget)
  10561. return;
  10562. var yRotation;
  10563. if (cameraTarget.rotationQuaternion) {
  10564. var rotMatrix = new BABYLON.Matrix();
  10565. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10566. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10567. }
  10568. else {
  10569. yRotation = cameraTarget.rotation.y;
  10570. }
  10571. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10572. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10573. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10574. var dx = targetX - this.position.x;
  10575. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10576. var dz = (targetZ) - this.position.z;
  10577. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10578. var vy = dy * this.cameraAcceleration;
  10579. var vz = dz * this.cameraAcceleration * 2;
  10580. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10581. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10582. }
  10583. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10584. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10585. }
  10586. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10587. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10588. }
  10589. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10590. this.setTarget(cameraTarget.position);
  10591. };
  10592. FollowCamera.prototype._checkInputs = function () {
  10593. _super.prototype._checkInputs.call(this);
  10594. this.follow(this.target);
  10595. };
  10596. return FollowCamera;
  10597. })(BABYLON.TargetCamera);
  10598. BABYLON.FollowCamera = FollowCamera;
  10599. })(BABYLON || (BABYLON = {}));
  10600. //# sourceMappingURL=babylon.followCamera.js.map
  10601. var BABYLON;
  10602. (function (BABYLON) {
  10603. // We're mainly based on the logic defined into the FreeCamera code
  10604. var TouchCamera = (function (_super) {
  10605. __extends(TouchCamera, _super);
  10606. function TouchCamera(name, position, scene) {
  10607. _super.call(this, name, position, scene);
  10608. this._offsetX = null;
  10609. this._offsetY = null;
  10610. this._pointerCount = 0;
  10611. this._pointerPressed = [];
  10612. this.angularSensibility = 200000.0;
  10613. this.moveSensibility = 500.0;
  10614. }
  10615. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10616. var _this = this;
  10617. var previousPosition;
  10618. if (this._attachedCanvas) {
  10619. return;
  10620. }
  10621. this._attachedCanvas = canvas;
  10622. if (this._onPointerDown === undefined) {
  10623. this._onPointerDown = function (evt) {
  10624. if (!noPreventDefault) {
  10625. evt.preventDefault();
  10626. }
  10627. _this._pointerPressed.push(evt.pointerId);
  10628. if (_this._pointerPressed.length !== 1) {
  10629. return;
  10630. }
  10631. previousPosition = {
  10632. x: evt.clientX,
  10633. y: evt.clientY
  10634. };
  10635. };
  10636. this._onPointerUp = function (evt) {
  10637. if (!noPreventDefault) {
  10638. evt.preventDefault();
  10639. }
  10640. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10641. if (index === -1) {
  10642. return;
  10643. }
  10644. _this._pointerPressed.splice(index, 1);
  10645. if (index != 0) {
  10646. return;
  10647. }
  10648. previousPosition = null;
  10649. _this._offsetX = null;
  10650. _this._offsetY = null;
  10651. };
  10652. this._onPointerMove = function (evt) {
  10653. if (!noPreventDefault) {
  10654. evt.preventDefault();
  10655. }
  10656. if (!previousPosition) {
  10657. return;
  10658. }
  10659. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10660. if (index != 0) {
  10661. return;
  10662. }
  10663. _this._offsetX = evt.clientX - previousPosition.x;
  10664. _this._offsetY = -(evt.clientY - previousPosition.y);
  10665. };
  10666. this._onLostFocus = function () {
  10667. _this._offsetX = null;
  10668. _this._offsetY = null;
  10669. };
  10670. }
  10671. canvas.addEventListener("pointerdown", this._onPointerDown);
  10672. canvas.addEventListener("pointerup", this._onPointerUp);
  10673. canvas.addEventListener("pointerout", this._onPointerUp);
  10674. canvas.addEventListener("pointermove", this._onPointerMove);
  10675. BABYLON.Tools.RegisterTopRootEvents([
  10676. { name: "blur", handler: this._onLostFocus }
  10677. ]);
  10678. };
  10679. TouchCamera.prototype.detachControl = function (canvas) {
  10680. if (this._attachedCanvas != canvas) {
  10681. return;
  10682. }
  10683. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10684. canvas.removeEventListener("pointerup", this._onPointerUp);
  10685. canvas.removeEventListener("pointerout", this._onPointerUp);
  10686. canvas.removeEventListener("pointermove", this._onPointerMove);
  10687. BABYLON.Tools.UnregisterTopRootEvents([
  10688. { name: "blur", handler: this._onLostFocus }
  10689. ]);
  10690. this._attachedCanvas = null;
  10691. };
  10692. TouchCamera.prototype._checkInputs = function () {
  10693. if (!this._offsetX) {
  10694. return;
  10695. }
  10696. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10697. if (this._pointerPressed.length > 1) {
  10698. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10699. }
  10700. else {
  10701. var speed = this._computeLocalCameraSpeed();
  10702. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10703. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10704. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10705. }
  10706. _super.prototype._checkInputs.call(this);
  10707. };
  10708. return TouchCamera;
  10709. })(BABYLON.FreeCamera);
  10710. BABYLON.TouchCamera = TouchCamera;
  10711. })(BABYLON || (BABYLON = {}));
  10712. //# sourceMappingURL=babylon.touchCamera.js.map
  10713. var BABYLON;
  10714. (function (BABYLON) {
  10715. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10716. var ArcRotateCamera = (function (_super) {
  10717. __extends(ArcRotateCamera, _super);
  10718. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10719. var _this = this;
  10720. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10721. this.alpha = alpha;
  10722. this.beta = beta;
  10723. this.radius = radius;
  10724. this.target = target;
  10725. this.inertialAlphaOffset = 0;
  10726. this.inertialBetaOffset = 0;
  10727. this.inertialRadiusOffset = 0;
  10728. this.lowerAlphaLimit = null;
  10729. this.upperAlphaLimit = null;
  10730. this.lowerBetaLimit = 0.01;
  10731. this.upperBetaLimit = Math.PI;
  10732. this.lowerRadiusLimit = null;
  10733. this.upperRadiusLimit = null;
  10734. this.angularSensibility = 1000.0;
  10735. this.wheelPrecision = 3.0;
  10736. this.pinchPrecision = 2.0;
  10737. this.keysUp = [38];
  10738. this.keysDown = [40];
  10739. this.keysLeft = [37];
  10740. this.keysRight = [39];
  10741. this.zoomOnFactor = 1;
  10742. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10743. this.pinchInwards = true;
  10744. this.allowUpsideDown = true;
  10745. this._keys = [];
  10746. this._viewMatrix = new BABYLON.Matrix();
  10747. this.checkCollisions = false;
  10748. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10749. this._collider = new BABYLON.Collider();
  10750. this._previousPosition = BABYLON.Vector3.Zero();
  10751. this._collisionVelocity = BABYLON.Vector3.Zero();
  10752. this._newPosition = BABYLON.Vector3.Zero();
  10753. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10754. if (collidedMesh === void 0) { collidedMesh = null; }
  10755. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10756. newPosition.multiplyInPlace(_this._collider.radius);
  10757. }
  10758. if (!collidedMesh) {
  10759. _this._previousPosition.copyFrom(_this.position);
  10760. }
  10761. else {
  10762. _this.setPosition(_this.position);
  10763. if (_this.onCollide) {
  10764. _this.onCollide(collidedMesh);
  10765. }
  10766. }
  10767. // Recompute because of constraints
  10768. var cosa = Math.cos(_this.alpha);
  10769. var sina = Math.sin(_this.alpha);
  10770. var cosb = Math.cos(_this.beta);
  10771. var sinb = Math.sin(_this.beta);
  10772. var target = _this._getTargetPosition();
  10773. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10774. _this.position.copyFrom(_this._newPosition);
  10775. var up = _this.upVector;
  10776. if (_this.allowUpsideDown && _this.beta < 0) {
  10777. var up = up.clone();
  10778. up = up.negate();
  10779. }
  10780. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10781. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10782. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10783. _this._collisionTriggered = false;
  10784. };
  10785. if (!this.target) {
  10786. this.target = BABYLON.Vector3.Zero();
  10787. }
  10788. this.getViewMatrix();
  10789. }
  10790. ArcRotateCamera.prototype._getTargetPosition = function () {
  10791. return this.target.position || this.target;
  10792. };
  10793. // Cache
  10794. ArcRotateCamera.prototype._initCache = function () {
  10795. _super.prototype._initCache.call(this);
  10796. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10797. this._cache.alpha = undefined;
  10798. this._cache.beta = undefined;
  10799. this._cache.radius = undefined;
  10800. this._cache.targetScreenOffset = undefined;
  10801. };
  10802. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10803. if (!ignoreParentClass) {
  10804. _super.prototype._updateCache.call(this);
  10805. }
  10806. this._cache.target.copyFrom(this._getTargetPosition());
  10807. this._cache.alpha = this.alpha;
  10808. this._cache.beta = this.beta;
  10809. this._cache.radius = this.radius;
  10810. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10811. };
  10812. // Synchronized
  10813. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10814. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10815. return false;
  10816. return this._cache.target.equals(this._getTargetPosition())
  10817. && this._cache.alpha === this.alpha
  10818. && this._cache.beta === this.beta
  10819. && this._cache.radius === this.radius
  10820. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10821. };
  10822. // Methods
  10823. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10824. var _this = this;
  10825. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10826. var previousPinchDistance = 0;
  10827. var pointers = new BABYLON.SmartCollection();
  10828. if (this._attachedElement) {
  10829. return;
  10830. }
  10831. this._attachedElement = element;
  10832. var engine = this.getEngine();
  10833. if (this._onPointerDown === undefined) {
  10834. this._onPointerDown = function (evt) {
  10835. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10836. cacheSoloPointer = pointers.item(evt.pointerId);
  10837. if (!noPreventDefault) {
  10838. evt.preventDefault();
  10839. }
  10840. };
  10841. this._onPointerUp = function (evt) {
  10842. cacheSoloPointer = null;
  10843. previousPinchDistance = 0;
  10844. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10845. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10846. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10847. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10848. pointers.empty();
  10849. if (!noPreventDefault) {
  10850. evt.preventDefault();
  10851. }
  10852. };
  10853. this._onPointerMove = function (evt) {
  10854. if (!noPreventDefault) {
  10855. evt.preventDefault();
  10856. }
  10857. switch (pointers.count) {
  10858. case 1:
  10859. var offsetX = evt.clientX - cacheSoloPointer.x;
  10860. var offsetY = evt.clientY - cacheSoloPointer.y;
  10861. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10862. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10863. cacheSoloPointer.x = evt.clientX;
  10864. cacheSoloPointer.y = evt.clientY;
  10865. break;
  10866. case 2:
  10867. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10868. pointers.item(evt.pointerId).x = evt.clientX;
  10869. pointers.item(evt.pointerId).y = evt.clientY;
  10870. var direction = _this.pinchInwards ? 1 : -1;
  10871. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10872. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10873. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10874. if (previousPinchDistance === 0) {
  10875. previousPinchDistance = pinchSquaredDistance;
  10876. return;
  10877. }
  10878. if (pinchSquaredDistance !== previousPinchDistance) {
  10879. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10880. previousPinchDistance = pinchSquaredDistance;
  10881. }
  10882. break;
  10883. default:
  10884. if (pointers.item(evt.pointerId)) {
  10885. pointers.item(evt.pointerId).x = evt.clientX;
  10886. pointers.item(evt.pointerId).y = evt.clientY;
  10887. }
  10888. }
  10889. };
  10890. this._onMouseMove = function (evt) {
  10891. if (!engine.isPointerLock) {
  10892. return;
  10893. }
  10894. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10895. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10896. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10897. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10898. if (!noPreventDefault) {
  10899. evt.preventDefault();
  10900. }
  10901. };
  10902. this._wheel = function (event) {
  10903. var delta = 0;
  10904. if (event.wheelDelta) {
  10905. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10906. }
  10907. else if (event.detail) {
  10908. delta = -event.detail / _this.wheelPrecision;
  10909. }
  10910. if (delta)
  10911. _this.inertialRadiusOffset += delta;
  10912. if (event.preventDefault) {
  10913. if (!noPreventDefault) {
  10914. event.preventDefault();
  10915. }
  10916. }
  10917. };
  10918. this._onKeyDown = function (evt) {
  10919. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10920. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10921. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10922. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10923. var index = _this._keys.indexOf(evt.keyCode);
  10924. if (index === -1) {
  10925. _this._keys.push(evt.keyCode);
  10926. }
  10927. if (evt.preventDefault) {
  10928. if (!noPreventDefault) {
  10929. evt.preventDefault();
  10930. }
  10931. }
  10932. }
  10933. };
  10934. this._onKeyUp = function (evt) {
  10935. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10936. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10937. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10938. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10939. var index = _this._keys.indexOf(evt.keyCode);
  10940. if (index >= 0) {
  10941. _this._keys.splice(index, 1);
  10942. }
  10943. if (evt.preventDefault) {
  10944. if (!noPreventDefault) {
  10945. evt.preventDefault();
  10946. }
  10947. }
  10948. }
  10949. };
  10950. this._onLostFocus = function () {
  10951. _this._keys = [];
  10952. pointers.empty();
  10953. previousPinchDistance = 0;
  10954. cacheSoloPointer = null;
  10955. };
  10956. this._onGestureStart = function (e) {
  10957. if (window.MSGesture === undefined) {
  10958. return;
  10959. }
  10960. if (!_this._MSGestureHandler) {
  10961. _this._MSGestureHandler = new MSGesture();
  10962. _this._MSGestureHandler.target = element;
  10963. }
  10964. _this._MSGestureHandler.addPointer(e.pointerId);
  10965. };
  10966. this._onGesture = function (e) {
  10967. _this.radius *= e.scale;
  10968. if (e.preventDefault) {
  10969. if (!noPreventDefault) {
  10970. e.stopPropagation();
  10971. e.preventDefault();
  10972. }
  10973. }
  10974. };
  10975. this._reset = function () {
  10976. _this._keys = [];
  10977. _this.inertialAlphaOffset = 0;
  10978. _this.inertialBetaOffset = 0;
  10979. _this.inertialRadiusOffset = 0;
  10980. pointers.empty();
  10981. previousPinchDistance = 0;
  10982. cacheSoloPointer = null;
  10983. };
  10984. }
  10985. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10986. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10987. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10988. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10989. element.addEventListener("mousemove", this._onMouseMove, false);
  10990. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10991. element.addEventListener("MSGestureChange", this._onGesture, false);
  10992. element.addEventListener('mousewheel', this._wheel, false);
  10993. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10994. BABYLON.Tools.RegisterTopRootEvents([
  10995. { name: "keydown", handler: this._onKeyDown },
  10996. { name: "keyup", handler: this._onKeyUp },
  10997. { name: "blur", handler: this._onLostFocus }
  10998. ]);
  10999. };
  11000. ArcRotateCamera.prototype.detachControl = function (element) {
  11001. if (this._attachedElement !== element) {
  11002. return;
  11003. }
  11004. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11005. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11006. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11007. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11008. element.removeEventListener("mousemove", this._onMouseMove);
  11009. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11010. element.removeEventListener("MSGestureChange", this._onGesture);
  11011. element.removeEventListener('mousewheel', this._wheel);
  11012. element.removeEventListener('DOMMouseScroll', this._wheel);
  11013. BABYLON.Tools.UnregisterTopRootEvents([
  11014. { name: "keydown", handler: this._onKeyDown },
  11015. { name: "keyup", handler: this._onKeyUp },
  11016. { name: "blur", handler: this._onLostFocus }
  11017. ]);
  11018. this._MSGestureHandler = null;
  11019. this._attachedElement = null;
  11020. if (this._reset) {
  11021. this._reset();
  11022. }
  11023. };
  11024. ArcRotateCamera.prototype._checkInputs = function () {
  11025. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11026. if (this._collisionTriggered) {
  11027. return;
  11028. }
  11029. // Keyboard
  11030. for (var index = 0; index < this._keys.length; index++) {
  11031. var keyCode = this._keys[index];
  11032. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11033. this.inertialAlphaOffset -= 0.01;
  11034. }
  11035. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11036. this.inertialBetaOffset -= 0.01;
  11037. }
  11038. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11039. this.inertialAlphaOffset += 0.01;
  11040. }
  11041. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11042. this.inertialBetaOffset += 0.01;
  11043. }
  11044. }
  11045. // Inertia
  11046. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11047. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11048. this.beta += this.inertialBetaOffset;
  11049. this.radius -= this.inertialRadiusOffset;
  11050. this.inertialAlphaOffset *= this.inertia;
  11051. this.inertialBetaOffset *= this.inertia;
  11052. this.inertialRadiusOffset *= this.inertia;
  11053. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11054. this.inertialAlphaOffset = 0;
  11055. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11056. this.inertialBetaOffset = 0;
  11057. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11058. this.inertialRadiusOffset = 0;
  11059. }
  11060. // Limits
  11061. this._checkLimits();
  11062. _super.prototype._checkInputs.call(this);
  11063. };
  11064. ArcRotateCamera.prototype._checkLimits = function () {
  11065. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11066. if (this.allowUpsideDown && this.beta > Math.PI) {
  11067. this.beta = this.beta - (2 * Math.PI);
  11068. }
  11069. }
  11070. else {
  11071. if (this.beta < this.lowerBetaLimit) {
  11072. this.beta = this.lowerBetaLimit;
  11073. }
  11074. }
  11075. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11076. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11077. this.beta = this.beta + (2 * Math.PI);
  11078. }
  11079. }
  11080. else {
  11081. if (this.beta > this.upperBetaLimit) {
  11082. this.beta = this.upperBetaLimit;
  11083. }
  11084. }
  11085. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11086. this.alpha = this.lowerAlphaLimit;
  11087. }
  11088. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11089. this.alpha = this.upperAlphaLimit;
  11090. }
  11091. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11092. this.radius = this.lowerRadiusLimit;
  11093. }
  11094. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11095. this.radius = this.upperRadiusLimit;
  11096. }
  11097. };
  11098. ArcRotateCamera.prototype.setPosition = function (position) {
  11099. var radiusv3 = position.subtract(this._getTargetPosition());
  11100. this.radius = radiusv3.length();
  11101. // Alpha
  11102. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11103. if (radiusv3.z < 0) {
  11104. this.alpha = 2 * Math.PI - this.alpha;
  11105. }
  11106. // Beta
  11107. this.beta = Math.acos(radiusv3.y / this.radius);
  11108. this._checkLimits();
  11109. };
  11110. ArcRotateCamera.prototype._getViewMatrix = function () {
  11111. // Compute
  11112. var cosa = Math.cos(this.alpha);
  11113. var sina = Math.sin(this.alpha);
  11114. var cosb = Math.cos(this.beta);
  11115. var sinb = Math.sin(this.beta);
  11116. var target = this._getTargetPosition();
  11117. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11118. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11119. this._collider.radius = this.collisionRadius;
  11120. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11121. this._collisionTriggered = true;
  11122. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11123. }
  11124. else {
  11125. this.position.copyFrom(this._newPosition);
  11126. var up = this.upVector;
  11127. if (this.allowUpsideDown && this.beta < 0) {
  11128. var up = up.clone();
  11129. up = up.negate();
  11130. }
  11131. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11132. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11133. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11134. }
  11135. return this._viewMatrix;
  11136. };
  11137. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  11138. meshes = meshes || this.getScene().meshes;
  11139. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11140. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11141. this.radius = distance * this.zoomOnFactor;
  11142. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  11143. };
  11144. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  11145. var meshesOrMinMaxVector;
  11146. var distance;
  11147. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11148. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11149. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11150. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11151. }
  11152. else {
  11153. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11154. distance = meshesOrMinMaxVectorAndDistance.distance;
  11155. }
  11156. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11157. this.maxZ = distance * 2;
  11158. };
  11159. /**
  11160. * @override
  11161. * Override Camera.createRigCamera
  11162. */
  11163. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11164. switch (this.cameraRigMode) {
  11165. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11166. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11167. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11168. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11169. case BABYLON.Camera.RIG_MODE_VR:
  11170. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11171. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11172. }
  11173. };
  11174. /**
  11175. * @override
  11176. * Override Camera._updateRigCameras
  11177. */
  11178. ArcRotateCamera.prototype._updateRigCameras = function () {
  11179. switch (this.cameraRigMode) {
  11180. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11181. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11182. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11183. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11184. case BABYLON.Camera.RIG_MODE_VR:
  11185. var camLeft = this._rigCameras[0];
  11186. var camRight = this._rigCameras[1];
  11187. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11188. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11189. camLeft.beta = camRight.beta = this.beta;
  11190. camLeft.radius = camRight.radius = this.radius;
  11191. break;
  11192. }
  11193. _super.prototype._updateRigCameras.call(this);
  11194. };
  11195. return ArcRotateCamera;
  11196. })(BABYLON.Camera);
  11197. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11198. })(BABYLON || (BABYLON = {}));
  11199. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  11200. var BABYLON;
  11201. (function (BABYLON) {
  11202. // We're mainly based on the logic defined into the FreeCamera code
  11203. var DeviceOrientationCamera = (function (_super) {
  11204. __extends(DeviceOrientationCamera, _super);
  11205. function DeviceOrientationCamera(name, position, scene) {
  11206. var _this = this;
  11207. _super.call(this, name, position, scene);
  11208. this._offsetX = null;
  11209. this._offsetY = null;
  11210. this._orientationGamma = 0;
  11211. this._orientationBeta = 0;
  11212. this._initialOrientationGamma = 0;
  11213. this._initialOrientationBeta = 0;
  11214. this.angularSensibility = 10000.0;
  11215. this.moveSensibility = 50.0;
  11216. window.addEventListener("resize", function () {
  11217. _this._initialOrientationGamma = null;
  11218. }, false);
  11219. }
  11220. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11221. var _this = this;
  11222. if (this._attachedCanvas) {
  11223. return;
  11224. }
  11225. this._attachedCanvas = canvas;
  11226. if (!this._orientationChanged) {
  11227. this._orientationChanged = function (evt) {
  11228. if (!_this._initialOrientationGamma) {
  11229. _this._initialOrientationGamma = evt.gamma;
  11230. _this._initialOrientationBeta = evt.beta;
  11231. }
  11232. _this._orientationGamma = evt.gamma;
  11233. _this._orientationBeta = evt.beta;
  11234. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11235. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11236. };
  11237. }
  11238. window.addEventListener("deviceorientation", this._orientationChanged);
  11239. };
  11240. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11241. if (this._attachedCanvas != canvas) {
  11242. return;
  11243. }
  11244. window.removeEventListener("deviceorientation", this._orientationChanged);
  11245. this._attachedCanvas = null;
  11246. this._orientationGamma = 0;
  11247. this._orientationBeta = 0;
  11248. this._initialOrientationGamma = 0;
  11249. this._initialOrientationBeta = 0;
  11250. };
  11251. DeviceOrientationCamera.prototype._checkInputs = function () {
  11252. if (!this._offsetX) {
  11253. return;
  11254. }
  11255. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11256. var speed = this._computeLocalCameraSpeed();
  11257. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11258. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11259. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11260. _super.prototype._checkInputs.call(this);
  11261. };
  11262. return DeviceOrientationCamera;
  11263. })(BABYLON.FreeCamera);
  11264. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11265. })(BABYLON || (BABYLON = {}));
  11266. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  11267. var BABYLON;
  11268. (function (BABYLON) {
  11269. var Gamepads = (function () {
  11270. function Gamepads(ongamedpadconnected) {
  11271. var _this = this;
  11272. this.babylonGamepads = [];
  11273. this.oneGamepadConnected = false;
  11274. this.isMonitoring = false;
  11275. this.gamepadEventSupported = 'GamepadEvent' in window;
  11276. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11277. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11278. 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=";
  11279. this._callbackGamepadConnected = ongamedpadconnected;
  11280. if (this.gamepadSupportAvailable) {
  11281. // Checking if the gamepad connected event is supported (like in Firefox)
  11282. if (this.gamepadEventSupported) {
  11283. window.addEventListener('gamepadconnected', function (evt) {
  11284. _this._onGamepadConnected(evt);
  11285. }, false);
  11286. window.addEventListener('gamepaddisconnected', function (evt) {
  11287. _this._onGamepadDisconnected(evt);
  11288. }, false);
  11289. }
  11290. else {
  11291. this._startMonitoringGamepads();
  11292. }
  11293. if (!this.oneGamepadConnected) {
  11294. this._insertGamepadDOMInstructions();
  11295. }
  11296. }
  11297. else {
  11298. this._insertGamepadDOMNotSupported();
  11299. }
  11300. }
  11301. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11302. Gamepads.gamepadDOMInfo = document.createElement("div");
  11303. var buttonAImage = document.createElement("img");
  11304. buttonAImage.src = this.buttonADataURL;
  11305. var spanMessage = document.createElement("span");
  11306. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11307. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11308. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11309. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11310. Gamepads.gamepadDOMInfo.style.width = "100%";
  11311. Gamepads.gamepadDOMInfo.style.height = "48px";
  11312. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11313. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11314. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11315. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11316. buttonAImage.style.position = "relative";
  11317. buttonAImage.style.bottom = "8px";
  11318. spanMessage.style.position = "relative";
  11319. spanMessage.style.fontSize = "32px";
  11320. spanMessage.style.bottom = "32px";
  11321. spanMessage.style.color = "green";
  11322. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11323. };
  11324. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11325. Gamepads.gamepadDOMInfo = document.createElement("div");
  11326. var spanMessage = document.createElement("span");
  11327. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11328. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11329. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11330. Gamepads.gamepadDOMInfo.style.width = "100%";
  11331. Gamepads.gamepadDOMInfo.style.height = "40px";
  11332. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11333. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11334. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11335. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11336. spanMessage.style.position = "relative";
  11337. spanMessage.style.fontSize = "32px";
  11338. spanMessage.style.color = "red";
  11339. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11340. };
  11341. Gamepads.prototype.dispose = function () {
  11342. if (Gamepads.gamepadDOMInfo) {
  11343. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11344. }
  11345. };
  11346. Gamepads.prototype._onGamepadConnected = function (evt) {
  11347. var newGamepad = this._addNewGamepad(evt.gamepad);
  11348. if (this._callbackGamepadConnected)
  11349. this._callbackGamepadConnected(newGamepad);
  11350. this._startMonitoringGamepads();
  11351. };
  11352. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11353. if (!this.oneGamepadConnected) {
  11354. this.oneGamepadConnected = true;
  11355. if (Gamepads.gamepadDOMInfo) {
  11356. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11357. Gamepads.gamepadDOMInfo = null;
  11358. }
  11359. }
  11360. var newGamepad;
  11361. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11362. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11363. }
  11364. else {
  11365. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11366. }
  11367. this.babylonGamepads.push(newGamepad);
  11368. return newGamepad;
  11369. };
  11370. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11371. // Remove the gamepad from the list of gamepads to monitor.
  11372. for (var i in this.babylonGamepads) {
  11373. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11374. this.babylonGamepads.splice(i, 1);
  11375. break;
  11376. }
  11377. }
  11378. // If no gamepads are left, stop the polling loop.
  11379. if (this.babylonGamepads.length == 0) {
  11380. this._stopMonitoringGamepads();
  11381. }
  11382. };
  11383. Gamepads.prototype._startMonitoringGamepads = function () {
  11384. if (!this.isMonitoring) {
  11385. this.isMonitoring = true;
  11386. this._checkGamepadsStatus();
  11387. }
  11388. };
  11389. Gamepads.prototype._stopMonitoringGamepads = function () {
  11390. this.isMonitoring = false;
  11391. };
  11392. Gamepads.prototype._checkGamepadsStatus = function () {
  11393. var _this = this;
  11394. // updating gamepad objects
  11395. this._updateGamepadObjects();
  11396. for (var i in this.babylonGamepads) {
  11397. this.babylonGamepads[i].update();
  11398. }
  11399. if (this.isMonitoring) {
  11400. if (window.requestAnimationFrame) {
  11401. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11402. }
  11403. else if (window.mozRequestAnimationFrame) {
  11404. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11405. }
  11406. else if (window.webkitRequestAnimationFrame) {
  11407. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11408. }
  11409. }
  11410. };
  11411. // This function is called only on Chrome, which does not yet support
  11412. // connection/disconnection events, but requires you to monitor
  11413. // an array for changes.
  11414. Gamepads.prototype._updateGamepadObjects = function () {
  11415. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11416. for (var i = 0; i < gamepads.length; i++) {
  11417. if (gamepads[i]) {
  11418. if (!(gamepads[i].index in this.babylonGamepads)) {
  11419. var newGamepad = this._addNewGamepad(gamepads[i]);
  11420. if (this._callbackGamepadConnected) {
  11421. this._callbackGamepadConnected(newGamepad);
  11422. }
  11423. }
  11424. else {
  11425. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11426. }
  11427. }
  11428. }
  11429. };
  11430. return Gamepads;
  11431. })();
  11432. BABYLON.Gamepads = Gamepads;
  11433. var StickValues = (function () {
  11434. function StickValues(x, y) {
  11435. this.x = x;
  11436. this.y = y;
  11437. }
  11438. return StickValues;
  11439. })();
  11440. BABYLON.StickValues = StickValues;
  11441. var Gamepad = (function () {
  11442. function Gamepad(id, index, browserGamepad) {
  11443. this.id = id;
  11444. this.index = index;
  11445. this.browserGamepad = browserGamepad;
  11446. if (this.browserGamepad.axes.length >= 2) {
  11447. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11448. }
  11449. if (this.browserGamepad.axes.length >= 4) {
  11450. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11451. }
  11452. }
  11453. Gamepad.prototype.onleftstickchanged = function (callback) {
  11454. this._onleftstickchanged = callback;
  11455. };
  11456. Gamepad.prototype.onrightstickchanged = function (callback) {
  11457. this._onrightstickchanged = callback;
  11458. };
  11459. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11460. get: function () {
  11461. return this._leftStick;
  11462. },
  11463. set: function (newValues) {
  11464. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11465. this._onleftstickchanged(newValues);
  11466. }
  11467. this._leftStick = newValues;
  11468. },
  11469. enumerable: true,
  11470. configurable: true
  11471. });
  11472. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11473. get: function () {
  11474. return this._rightStick;
  11475. },
  11476. set: function (newValues) {
  11477. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11478. this._onrightstickchanged(newValues);
  11479. }
  11480. this._rightStick = newValues;
  11481. },
  11482. enumerable: true,
  11483. configurable: true
  11484. });
  11485. Gamepad.prototype.update = function () {
  11486. if (this._leftStick) {
  11487. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11488. }
  11489. if (this._rightStick) {
  11490. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11491. }
  11492. };
  11493. return Gamepad;
  11494. })();
  11495. BABYLON.Gamepad = Gamepad;
  11496. var GenericPad = (function (_super) {
  11497. __extends(GenericPad, _super);
  11498. function GenericPad(id, index, gamepad) {
  11499. _super.call(this, id, index, gamepad);
  11500. this.id = id;
  11501. this.index = index;
  11502. this.gamepad = gamepad;
  11503. this._buttons = new Array(gamepad.buttons.length);
  11504. }
  11505. GenericPad.prototype.onbuttondown = function (callback) {
  11506. this._onbuttondown = callback;
  11507. };
  11508. GenericPad.prototype.onbuttonup = function (callback) {
  11509. this._onbuttonup = callback;
  11510. };
  11511. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11512. if (newValue !== currentValue) {
  11513. if (this._onbuttondown && newValue === 1) {
  11514. this._onbuttondown(buttonIndex);
  11515. }
  11516. if (this._onbuttonup && newValue === 0) {
  11517. this._onbuttonup(buttonIndex);
  11518. }
  11519. }
  11520. return newValue;
  11521. };
  11522. GenericPad.prototype.update = function () {
  11523. _super.prototype.update.call(this);
  11524. for (var index = 0; index < this._buttons.length; index++) {
  11525. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11526. }
  11527. };
  11528. return GenericPad;
  11529. })(Gamepad);
  11530. BABYLON.GenericPad = GenericPad;
  11531. (function (Xbox360Button) {
  11532. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11533. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11534. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11535. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11536. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11537. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11538. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11539. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11540. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11541. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11542. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11543. var Xbox360Button = BABYLON.Xbox360Button;
  11544. (function (Xbox360Dpad) {
  11545. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11546. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11547. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11548. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11549. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11550. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11551. var Xbox360Pad = (function (_super) {
  11552. __extends(Xbox360Pad, _super);
  11553. function Xbox360Pad() {
  11554. _super.apply(this, arguments);
  11555. this._leftTrigger = 0;
  11556. this._rightTrigger = 0;
  11557. this._buttonA = 0;
  11558. this._buttonB = 0;
  11559. this._buttonX = 0;
  11560. this._buttonY = 0;
  11561. this._buttonBack = 0;
  11562. this._buttonStart = 0;
  11563. this._buttonLB = 0;
  11564. this._buttonRB = 0;
  11565. this._buttonLeftStick = 0;
  11566. this._buttonRightStick = 0;
  11567. this._dPadUp = 0;
  11568. this._dPadDown = 0;
  11569. this._dPadLeft = 0;
  11570. this._dPadRight = 0;
  11571. }
  11572. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11573. this._onlefttriggerchanged = callback;
  11574. };
  11575. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11576. this._onrighttriggerchanged = callback;
  11577. };
  11578. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11579. get: function () {
  11580. return this._leftTrigger;
  11581. },
  11582. set: function (newValue) {
  11583. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11584. this._onlefttriggerchanged(newValue);
  11585. }
  11586. this._leftTrigger = newValue;
  11587. },
  11588. enumerable: true,
  11589. configurable: true
  11590. });
  11591. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11592. get: function () {
  11593. return this._rightTrigger;
  11594. },
  11595. set: function (newValue) {
  11596. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11597. this._onrighttriggerchanged(newValue);
  11598. }
  11599. this._rightTrigger = newValue;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11605. this._onbuttondown = callback;
  11606. };
  11607. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11608. this._onbuttonup = callback;
  11609. };
  11610. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11611. this._ondpaddown = callback;
  11612. };
  11613. Xbox360Pad.prototype.ondpadup = function (callback) {
  11614. this._ondpadup = callback;
  11615. };
  11616. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11617. if (newValue !== currentValue) {
  11618. if (this._onbuttondown && newValue === 1) {
  11619. this._onbuttondown(buttonType);
  11620. }
  11621. if (this._onbuttonup && newValue === 0) {
  11622. this._onbuttonup(buttonType);
  11623. }
  11624. }
  11625. return newValue;
  11626. };
  11627. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11628. if (newValue !== currentValue) {
  11629. if (this._ondpaddown && newValue === 1) {
  11630. this._ondpaddown(buttonType);
  11631. }
  11632. if (this._ondpadup && newValue === 0) {
  11633. this._ondpadup(buttonType);
  11634. }
  11635. }
  11636. return newValue;
  11637. };
  11638. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11639. get: function () {
  11640. return this._buttonA;
  11641. },
  11642. set: function (value) {
  11643. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11649. get: function () {
  11650. return this._buttonB;
  11651. },
  11652. set: function (value) {
  11653. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11654. },
  11655. enumerable: true,
  11656. configurable: true
  11657. });
  11658. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11659. get: function () {
  11660. return this._buttonX;
  11661. },
  11662. set: function (value) {
  11663. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11669. get: function () {
  11670. return this._buttonY;
  11671. },
  11672. set: function (value) {
  11673. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11679. get: function () {
  11680. return this._buttonStart;
  11681. },
  11682. set: function (value) {
  11683. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11689. get: function () {
  11690. return this._buttonBack;
  11691. },
  11692. set: function (value) {
  11693. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11699. get: function () {
  11700. return this._buttonLB;
  11701. },
  11702. set: function (value) {
  11703. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11709. get: function () {
  11710. return this._buttonRB;
  11711. },
  11712. set: function (value) {
  11713. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  11714. },
  11715. enumerable: true,
  11716. configurable: true
  11717. });
  11718. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11719. get: function () {
  11720. return this._buttonLeftStick;
  11721. },
  11722. set: function (value) {
  11723. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  11724. },
  11725. enumerable: true,
  11726. configurable: true
  11727. });
  11728. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11729. get: function () {
  11730. return this._buttonRightStick;
  11731. },
  11732. set: function (value) {
  11733. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  11739. get: function () {
  11740. return this._dPadUp;
  11741. },
  11742. set: function (value) {
  11743. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  11744. },
  11745. enumerable: true,
  11746. configurable: true
  11747. });
  11748. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  11749. get: function () {
  11750. return this._dPadDown;
  11751. },
  11752. set: function (value) {
  11753. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  11759. get: function () {
  11760. return this._dPadLeft;
  11761. },
  11762. set: function (value) {
  11763. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  11769. get: function () {
  11770. return this._dPadRight;
  11771. },
  11772. set: function (value) {
  11773. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  11774. },
  11775. enumerable: true,
  11776. configurable: true
  11777. });
  11778. Xbox360Pad.prototype.update = function () {
  11779. _super.prototype.update.call(this);
  11780. this.buttonA = this.browserGamepad.buttons[0].value;
  11781. this.buttonB = this.browserGamepad.buttons[1].value;
  11782. this.buttonX = this.browserGamepad.buttons[2].value;
  11783. this.buttonY = this.browserGamepad.buttons[3].value;
  11784. this.buttonLB = this.browserGamepad.buttons[4].value;
  11785. this.buttonRB = this.browserGamepad.buttons[5].value;
  11786. this.leftTrigger = this.browserGamepad.buttons[6].value;
  11787. this.rightTrigger = this.browserGamepad.buttons[7].value;
  11788. this.buttonBack = this.browserGamepad.buttons[8].value;
  11789. this.buttonStart = this.browserGamepad.buttons[9].value;
  11790. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  11791. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  11792. this.dPadUp = this.browserGamepad.buttons[12].value;
  11793. this.dPadDown = this.browserGamepad.buttons[13].value;
  11794. this.dPadLeft = this.browserGamepad.buttons[14].value;
  11795. this.dPadRight = this.browserGamepad.buttons[15].value;
  11796. };
  11797. return Xbox360Pad;
  11798. })(Gamepad);
  11799. BABYLON.Xbox360Pad = Xbox360Pad;
  11800. })(BABYLON || (BABYLON = {}));
  11801. //# sourceMappingURL=babylon.gamepads.js.map
  11802. var BABYLON;
  11803. (function (BABYLON) {
  11804. // We're mainly based on the logic defined into the FreeCamera code
  11805. var GamepadCamera = (function (_super) {
  11806. __extends(GamepadCamera, _super);
  11807. function GamepadCamera(name, position, scene) {
  11808. var _this = this;
  11809. _super.call(this, name, position, scene);
  11810. this.angularSensibility = 200;
  11811. this.moveSensibility = 75;
  11812. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11813. }
  11814. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  11815. // Only the first gamepad can control the camera
  11816. if (gamepad.index === 0) {
  11817. this._gamepad = gamepad;
  11818. }
  11819. };
  11820. GamepadCamera.prototype._checkInputs = function () {
  11821. if (this._gamepad) {
  11822. var LSValues = this._gamepad.leftStick;
  11823. var normalizedLX = LSValues.x / this.moveSensibility;
  11824. var normalizedLY = LSValues.y / this.moveSensibility;
  11825. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11826. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11827. var RSValues = this._gamepad.rightStick;
  11828. var normalizedRX = RSValues.x / this.angularSensibility;
  11829. var normalizedRY = RSValues.y / this.angularSensibility;
  11830. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11831. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11832. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  11833. var speed = this._computeLocalCameraSpeed() * 50.0;
  11834. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11835. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  11836. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11837. }
  11838. _super.prototype._checkInputs.call(this);
  11839. };
  11840. GamepadCamera.prototype.dispose = function () {
  11841. this._gamepads.dispose();
  11842. _super.prototype.dispose.call(this);
  11843. };
  11844. return GamepadCamera;
  11845. })(BABYLON.FreeCamera);
  11846. BABYLON.GamepadCamera = GamepadCamera;
  11847. })(BABYLON || (BABYLON = {}));
  11848. //# sourceMappingURL=babylon.gamepadCamera.js.map
  11849. var BABYLON;
  11850. (function (BABYLON) {
  11851. var RenderingManager = (function () {
  11852. function RenderingManager(scene) {
  11853. this._renderingGroups = new Array();
  11854. this._scene = scene;
  11855. }
  11856. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11857. if (this._scene._activeParticleSystems.length === 0) {
  11858. return;
  11859. }
  11860. // Particles
  11861. var beforeParticlesDate = BABYLON.Tools.Now;
  11862. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11863. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11864. if (particleSystem.renderingGroupId !== index) {
  11865. continue;
  11866. }
  11867. this._clearDepthBuffer();
  11868. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11869. this._scene._activeParticles += particleSystem.render();
  11870. }
  11871. }
  11872. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11873. };
  11874. RenderingManager.prototype._renderSprites = function (index) {
  11875. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11876. return;
  11877. }
  11878. // Sprites
  11879. var beforeSpritessDate = BABYLON.Tools.Now;
  11880. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11881. var spriteManager = this._scene.spriteManagers[id];
  11882. if (spriteManager.renderingGroupId === index) {
  11883. this._clearDepthBuffer();
  11884. spriteManager.render();
  11885. }
  11886. }
  11887. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11888. };
  11889. RenderingManager.prototype._clearDepthBuffer = function () {
  11890. if (this._depthBufferAlreadyCleaned) {
  11891. return;
  11892. }
  11893. this._scene.getEngine().clear(0, false, true);
  11894. this._depthBufferAlreadyCleaned = true;
  11895. };
  11896. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11897. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11898. this._depthBufferAlreadyCleaned = false;
  11899. var renderingGroup = this._renderingGroups[index];
  11900. var needToStepBack = false;
  11901. if (renderingGroup) {
  11902. this._clearDepthBuffer();
  11903. if (!renderingGroup.render(customRenderFunction)) {
  11904. this._renderingGroups.splice(index, 1);
  11905. needToStepBack = true;
  11906. }
  11907. }
  11908. if (renderSprites) {
  11909. this._renderSprites(index);
  11910. }
  11911. if (renderParticles) {
  11912. this._renderParticles(index, activeMeshes);
  11913. }
  11914. if (needToStepBack) {
  11915. index--;
  11916. }
  11917. }
  11918. };
  11919. RenderingManager.prototype.reset = function () {
  11920. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  11921. if (renderingGroup) {
  11922. renderingGroup.prepare();
  11923. }
  11924. });
  11925. };
  11926. RenderingManager.prototype.dispatch = function (subMesh) {
  11927. var mesh = subMesh.getMesh();
  11928. var renderingGroupId = mesh.renderingGroupId || 0;
  11929. if (!this._renderingGroups[renderingGroupId]) {
  11930. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11931. }
  11932. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11933. };
  11934. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11935. return RenderingManager;
  11936. })();
  11937. BABYLON.RenderingManager = RenderingManager;
  11938. })(BABYLON || (BABYLON = {}));
  11939. //# sourceMappingURL=babylon.renderingManager.js.map
  11940. var BABYLON;
  11941. (function (BABYLON) {
  11942. var RenderingGroup = (function () {
  11943. function RenderingGroup(index, scene) {
  11944. this.index = index;
  11945. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11946. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11947. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11948. this._scene = scene;
  11949. }
  11950. RenderingGroup.prototype.render = function (customRenderFunction) {
  11951. if (customRenderFunction) {
  11952. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11953. return true;
  11954. }
  11955. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11956. return false;
  11957. }
  11958. var engine = this._scene.getEngine();
  11959. // Opaque
  11960. var subIndex;
  11961. var submesh;
  11962. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11963. submesh = this._opaqueSubMeshes.data[subIndex];
  11964. submesh.render();
  11965. }
  11966. // Alpha test
  11967. engine.setAlphaTesting(true);
  11968. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11969. submesh = this._alphaTestSubMeshes.data[subIndex];
  11970. submesh.render();
  11971. }
  11972. engine.setAlphaTesting(false);
  11973. // Transparent
  11974. if (this._transparentSubMeshes.length) {
  11975. // Sorting
  11976. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11977. submesh = this._transparentSubMeshes.data[subIndex];
  11978. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11979. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11980. }
  11981. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11982. sortedArray.sort(function (a, b) {
  11983. // Alpha index first
  11984. if (a._alphaIndex > b._alphaIndex) {
  11985. return 1;
  11986. }
  11987. if (a._alphaIndex < b._alphaIndex) {
  11988. return -1;
  11989. }
  11990. // Then distance to camera
  11991. if (a._distanceToCamera < b._distanceToCamera) {
  11992. return 1;
  11993. }
  11994. if (a._distanceToCamera > b._distanceToCamera) {
  11995. return -1;
  11996. }
  11997. return 0;
  11998. });
  11999. // Rendering
  12000. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12001. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12002. submesh = sortedArray[subIndex];
  12003. submesh.render();
  12004. }
  12005. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12006. }
  12007. return true;
  12008. };
  12009. RenderingGroup.prototype.prepare = function () {
  12010. this._opaqueSubMeshes.reset();
  12011. this._transparentSubMeshes.reset();
  12012. this._alphaTestSubMeshes.reset();
  12013. };
  12014. RenderingGroup.prototype.dispatch = function (subMesh) {
  12015. var material = subMesh.getMaterial();
  12016. var mesh = subMesh.getMesh();
  12017. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12018. this._transparentSubMeshes.push(subMesh);
  12019. }
  12020. else if (material.needAlphaTesting()) {
  12021. this._alphaTestSubMeshes.push(subMesh);
  12022. }
  12023. else {
  12024. this._opaqueSubMeshes.push(subMesh); // Opaque
  12025. }
  12026. };
  12027. return RenderingGroup;
  12028. })();
  12029. BABYLON.RenderingGroup = RenderingGroup;
  12030. })(BABYLON || (BABYLON = {}));
  12031. //# sourceMappingURL=babylon.renderingGroup.js.map
  12032. var BABYLON;
  12033. (function (BABYLON) {
  12034. /**
  12035. * Represents a scene to be rendered by the engine.
  12036. * @see http://doc.babylonjs.com/page.php?p=21911
  12037. */
  12038. var Scene = (function () {
  12039. /**
  12040. * @constructor
  12041. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12042. */
  12043. function Scene(engine) {
  12044. // Members
  12045. this.autoClear = true;
  12046. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12047. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12048. this.forceWireframe = false;
  12049. this.forcePointsCloud = false;
  12050. this.forceShowBoundingBoxes = false;
  12051. this.animationsEnabled = true;
  12052. 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
  12053. // Fog
  12054. /**
  12055. * is fog enabled on this scene.
  12056. * @type {boolean}
  12057. */
  12058. this.fogEnabled = true;
  12059. this.fogMode = Scene.FOGMODE_NONE;
  12060. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12061. this.fogDensity = 0.1;
  12062. this.fogStart = 0;
  12063. this.fogEnd = 1000.0;
  12064. // Lights
  12065. /**
  12066. * is shadow enabled on this scene.
  12067. * @type {boolean}
  12068. */
  12069. this.shadowsEnabled = true;
  12070. /**
  12071. * is light enabled on this scene.
  12072. * @type {boolean}
  12073. */
  12074. this.lightsEnabled = true;
  12075. /**
  12076. * All of the lights added to this scene.
  12077. * @see BABYLON.Light
  12078. * @type {BABYLON.Light[]}
  12079. */
  12080. this.lights = new Array();
  12081. // Cameras
  12082. /**
  12083. * All of the cameras added to this scene.
  12084. * @see BABYLON.Camera
  12085. * @type {BABYLON.Camera[]}
  12086. */
  12087. this.cameras = new Array();
  12088. this.activeCameras = new Array();
  12089. // Meshes
  12090. /**
  12091. * All of the (abstract) meshes added to this scene.
  12092. * @see BABYLON.AbstractMesh
  12093. * @type {BABYLON.AbstractMesh[]}
  12094. */
  12095. this.meshes = new Array();
  12096. // Geometries
  12097. this._geometries = new Array();
  12098. this.materials = new Array();
  12099. this.multiMaterials = new Array();
  12100. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12101. // Textures
  12102. this.texturesEnabled = true;
  12103. this.textures = new Array();
  12104. // Particles
  12105. this.particlesEnabled = true;
  12106. this.particleSystems = new Array();
  12107. // Sprites
  12108. this.spritesEnabled = true;
  12109. this.spriteManagers = new Array();
  12110. // Layers
  12111. this.layers = new Array();
  12112. // Skeletons
  12113. this.skeletonsEnabled = true;
  12114. this.skeletons = new Array();
  12115. // Lens flares
  12116. this.lensFlaresEnabled = true;
  12117. this.lensFlareSystems = new Array();
  12118. // Collisions
  12119. this.collisionsEnabled = true;
  12120. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12121. // Postprocesses
  12122. this.postProcessesEnabled = true;
  12123. // Customs render targets
  12124. this.renderTargetsEnabled = true;
  12125. this.dumpNextRenderTargets = false;
  12126. this.customRenderTargets = new Array();
  12127. // Imported meshes
  12128. this.importedMeshesFiles = new Array();
  12129. this._actionManagers = new Array();
  12130. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12131. // Procedural textures
  12132. this.proceduralTexturesEnabled = true;
  12133. this._proceduralTextures = new Array();
  12134. this.soundTracks = new Array();
  12135. this._audioEnabled = true;
  12136. this._headphone = false;
  12137. this._totalVertices = 0;
  12138. this._activeIndices = 0;
  12139. this._activeParticles = 0;
  12140. this._lastFrameDuration = 0;
  12141. this._evaluateActiveMeshesDuration = 0;
  12142. this._renderTargetsDuration = 0;
  12143. this._particlesDuration = 0;
  12144. this._renderDuration = 0;
  12145. this._spritesDuration = 0;
  12146. this._animationRatio = 0;
  12147. this._renderId = 0;
  12148. this._executeWhenReadyTimeoutId = -1;
  12149. this._toBeDisposed = new BABYLON.SmartArray(256);
  12150. this._onReadyCallbacks = new Array();
  12151. this._pendingData = []; //ANY
  12152. this._onBeforeRenderCallbacks = new Array();
  12153. this._onAfterRenderCallbacks = new Array();
  12154. this._activeMeshes = new BABYLON.SmartArray(256);
  12155. this._processedMaterials = new BABYLON.SmartArray(256);
  12156. this._renderTargets = new BABYLON.SmartArray(256);
  12157. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12158. this._activeSkeletons = new BABYLON.SmartArray(32);
  12159. this._activeBones = 0;
  12160. this._activeAnimatables = new Array();
  12161. this._transformMatrix = BABYLON.Matrix.Zero();
  12162. this._uniqueIdCounter = 0;
  12163. this._engine = engine;
  12164. engine.scenes.push(this);
  12165. this._renderingManager = new BABYLON.RenderingManager(this);
  12166. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12167. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12168. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12169. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12170. this.attachControl();
  12171. this._debugLayer = new BABYLON.DebugLayer(this);
  12172. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12173. //simplification queue
  12174. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12175. //collision coordinator initialization. For now legacy per default.
  12176. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12177. }
  12178. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12179. get: function () {
  12180. return Scene._FOGMODE_NONE;
  12181. },
  12182. enumerable: true,
  12183. configurable: true
  12184. });
  12185. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12186. get: function () {
  12187. return Scene._FOGMODE_EXP;
  12188. },
  12189. enumerable: true,
  12190. configurable: true
  12191. });
  12192. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12193. get: function () {
  12194. return Scene._FOGMODE_EXP2;
  12195. },
  12196. enumerable: true,
  12197. configurable: true
  12198. });
  12199. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12200. get: function () {
  12201. return Scene._FOGMODE_LINEAR;
  12202. },
  12203. enumerable: true,
  12204. configurable: true
  12205. });
  12206. Object.defineProperty(Scene.prototype, "debugLayer", {
  12207. // Properties
  12208. get: function () {
  12209. return this._debugLayer;
  12210. },
  12211. enumerable: true,
  12212. configurable: true
  12213. });
  12214. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12215. get: function () {
  12216. return this._workerCollisions;
  12217. },
  12218. set: function (enabled) {
  12219. enabled = (enabled && !!Worker);
  12220. this._workerCollisions = enabled;
  12221. if (this.collisionCoordinator) {
  12222. this.collisionCoordinator.destroy();
  12223. }
  12224. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12225. this.collisionCoordinator.init(this);
  12226. },
  12227. enumerable: true,
  12228. configurable: true
  12229. });
  12230. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12231. /**
  12232. * The mesh that is currently under the pointer.
  12233. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12234. */
  12235. get: function () {
  12236. return this._meshUnderPointer;
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. Object.defineProperty(Scene.prototype, "pointerX", {
  12242. /**
  12243. * Current on-screen X position of the pointer
  12244. * @return {number} X position of the pointer
  12245. */
  12246. get: function () {
  12247. return this._pointerX;
  12248. },
  12249. enumerable: true,
  12250. configurable: true
  12251. });
  12252. Object.defineProperty(Scene.prototype, "pointerY", {
  12253. /**
  12254. * Current on-screen Y position of the pointer
  12255. * @return {number} Y position of the pointer
  12256. */
  12257. get: function () {
  12258. return this._pointerY;
  12259. },
  12260. enumerable: true,
  12261. configurable: true
  12262. });
  12263. Scene.prototype.getCachedMaterial = function () {
  12264. return this._cachedMaterial;
  12265. };
  12266. Scene.prototype.getBoundingBoxRenderer = function () {
  12267. return this._boundingBoxRenderer;
  12268. };
  12269. Scene.prototype.getOutlineRenderer = function () {
  12270. return this._outlineRenderer;
  12271. };
  12272. Scene.prototype.getEngine = function () {
  12273. return this._engine;
  12274. };
  12275. Scene.prototype.getTotalVertices = function () {
  12276. return this._totalVertices;
  12277. };
  12278. Scene.prototype.getActiveIndices = function () {
  12279. return this._activeIndices;
  12280. };
  12281. Scene.prototype.getActiveParticles = function () {
  12282. return this._activeParticles;
  12283. };
  12284. Scene.prototype.getActiveBones = function () {
  12285. return this._activeBones;
  12286. };
  12287. // Stats
  12288. Scene.prototype.getLastFrameDuration = function () {
  12289. return this._lastFrameDuration;
  12290. };
  12291. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12292. return this._evaluateActiveMeshesDuration;
  12293. };
  12294. Scene.prototype.getActiveMeshes = function () {
  12295. return this._activeMeshes;
  12296. };
  12297. Scene.prototype.getRenderTargetsDuration = function () {
  12298. return this._renderTargetsDuration;
  12299. };
  12300. Scene.prototype.getRenderDuration = function () {
  12301. return this._renderDuration;
  12302. };
  12303. Scene.prototype.getParticlesDuration = function () {
  12304. return this._particlesDuration;
  12305. };
  12306. Scene.prototype.getSpritesDuration = function () {
  12307. return this._spritesDuration;
  12308. };
  12309. Scene.prototype.getAnimationRatio = function () {
  12310. return this._animationRatio;
  12311. };
  12312. Scene.prototype.getRenderId = function () {
  12313. return this._renderId;
  12314. };
  12315. Scene.prototype.incrementRenderId = function () {
  12316. this._renderId++;
  12317. };
  12318. Scene.prototype._updatePointerPosition = function (evt) {
  12319. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12320. this._pointerX = evt.clientX - canvasRect.left;
  12321. this._pointerY = evt.clientY - canvasRect.top;
  12322. if (this.cameraToUseForPointers) {
  12323. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12324. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12325. }
  12326. };
  12327. // Pointers handling
  12328. Scene.prototype.attachControl = function () {
  12329. var _this = this;
  12330. this._onPointerMove = function (evt) {
  12331. var canvas = _this._engine.getRenderingCanvas();
  12332. _this._updatePointerPosition(evt);
  12333. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  12334. if (pickResult.hit) {
  12335. _this._meshUnderPointer = pickResult.pickedMesh;
  12336. _this.setPointerOverMesh(pickResult.pickedMesh);
  12337. canvas.style.cursor = "pointer";
  12338. }
  12339. else {
  12340. _this.setPointerOverMesh(null);
  12341. canvas.style.cursor = "";
  12342. _this._meshUnderPointer = null;
  12343. }
  12344. };
  12345. this._onPointerDown = function (evt) {
  12346. var predicate = null;
  12347. if (!_this.onPointerDown) {
  12348. predicate = function (mesh) {
  12349. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12350. };
  12351. }
  12352. _this._updatePointerPosition(evt);
  12353. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12354. if (pickResult.hit) {
  12355. if (pickResult.pickedMesh.actionManager) {
  12356. switch (evt.button) {
  12357. case 0:
  12358. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12359. break;
  12360. case 1:
  12361. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12362. break;
  12363. case 2:
  12364. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12365. break;
  12366. }
  12367. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12368. }
  12369. }
  12370. if (_this.onPointerDown) {
  12371. _this.onPointerDown(evt, pickResult);
  12372. }
  12373. };
  12374. this._onPointerUp = function (evt) {
  12375. var predicate = null;
  12376. if (!_this.onPointerUp) {
  12377. predicate = function (mesh) {
  12378. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12379. };
  12380. }
  12381. _this._updatePointerPosition(evt);
  12382. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12383. if (pickResult.hit) {
  12384. if (pickResult.pickedMesh.actionManager) {
  12385. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12386. }
  12387. }
  12388. if (_this.onPointerUp) {
  12389. _this.onPointerUp(evt, pickResult);
  12390. }
  12391. };
  12392. this._onKeyDown = function (evt) {
  12393. if (_this.actionManager) {
  12394. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12395. }
  12396. };
  12397. this._onKeyUp = function (evt) {
  12398. if (_this.actionManager) {
  12399. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12400. }
  12401. };
  12402. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12403. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12404. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12405. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12406. BABYLON.Tools.RegisterTopRootEvents([
  12407. { name: "keydown", handler: this._onKeyDown },
  12408. { name: "keyup", handler: this._onKeyUp }
  12409. ]);
  12410. };
  12411. Scene.prototype.detachControl = function () {
  12412. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12413. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12414. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12415. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12416. BABYLON.Tools.UnregisterTopRootEvents([
  12417. { name: "keydown", handler: this._onKeyDown },
  12418. { name: "keyup", handler: this._onKeyUp }
  12419. ]);
  12420. };
  12421. // Ready
  12422. Scene.prototype.isReady = function () {
  12423. if (this._pendingData.length > 0) {
  12424. return false;
  12425. }
  12426. for (var index = 0; index < this._geometries.length; index++) {
  12427. var geometry = this._geometries[index];
  12428. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12429. return false;
  12430. }
  12431. }
  12432. for (index = 0; index < this.meshes.length; index++) {
  12433. var mesh = this.meshes[index];
  12434. if (!mesh.isReady()) {
  12435. return false;
  12436. }
  12437. var mat = mesh.material;
  12438. if (mat) {
  12439. if (!mat.isReady(mesh)) {
  12440. return false;
  12441. }
  12442. }
  12443. }
  12444. return true;
  12445. };
  12446. Scene.prototype.resetCachedMaterial = function () {
  12447. this._cachedMaterial = null;
  12448. };
  12449. Scene.prototype.registerBeforeRender = function (func) {
  12450. this._onBeforeRenderCallbacks.push(func);
  12451. };
  12452. Scene.prototype.unregisterBeforeRender = function (func) {
  12453. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12454. if (index > -1) {
  12455. this._onBeforeRenderCallbacks.splice(index, 1);
  12456. }
  12457. };
  12458. Scene.prototype.registerAfterRender = function (func) {
  12459. this._onAfterRenderCallbacks.push(func);
  12460. };
  12461. Scene.prototype.unregisterAfterRender = function (func) {
  12462. var index = this._onAfterRenderCallbacks.indexOf(func);
  12463. if (index > -1) {
  12464. this._onAfterRenderCallbacks.splice(index, 1);
  12465. }
  12466. };
  12467. Scene.prototype._addPendingData = function (data) {
  12468. this._pendingData.push(data);
  12469. };
  12470. Scene.prototype._removePendingData = function (data) {
  12471. var index = this._pendingData.indexOf(data);
  12472. if (index !== -1) {
  12473. this._pendingData.splice(index, 1);
  12474. }
  12475. };
  12476. Scene.prototype.getWaitingItemsCount = function () {
  12477. return this._pendingData.length;
  12478. };
  12479. /**
  12480. * Registers a function to be executed when the scene is ready.
  12481. * @param {Function} func - the function to be executed.
  12482. */
  12483. Scene.prototype.executeWhenReady = function (func) {
  12484. var _this = this;
  12485. this._onReadyCallbacks.push(func);
  12486. if (this._executeWhenReadyTimeoutId !== -1) {
  12487. return;
  12488. }
  12489. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12490. _this._checkIsReady();
  12491. }, 150);
  12492. };
  12493. Scene.prototype._checkIsReady = function () {
  12494. var _this = this;
  12495. if (this.isReady()) {
  12496. this._onReadyCallbacks.forEach(function (func) {
  12497. func();
  12498. });
  12499. this._onReadyCallbacks = [];
  12500. this._executeWhenReadyTimeoutId = -1;
  12501. return;
  12502. }
  12503. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12504. _this._checkIsReady();
  12505. }, 150);
  12506. };
  12507. // Animations
  12508. /**
  12509. * Will start the animation sequence of a given target
  12510. * @param target - the target
  12511. * @param {number} from - from which frame should animation start
  12512. * @param {number} to - till which frame should animation run.
  12513. * @param {boolean} [loop] - should the animation loop
  12514. * @param {number} [speedRatio] - the speed in which to run the animation
  12515. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12516. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12517. * @return {BABYLON.Animatable} the animatable object created for this animation
  12518. * @see BABYLON.Animatable
  12519. * @see http://doc.babylonjs.com/page.php?p=22081
  12520. */
  12521. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12522. if (speedRatio === undefined) {
  12523. speedRatio = 1.0;
  12524. }
  12525. this.stopAnimation(target);
  12526. if (!animatable) {
  12527. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12528. }
  12529. // Local animations
  12530. if (target.animations) {
  12531. animatable.appendAnimations(target, target.animations);
  12532. }
  12533. // Children animations
  12534. if (target.getAnimatables) {
  12535. var animatables = target.getAnimatables();
  12536. for (var index = 0; index < animatables.length; index++) {
  12537. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12538. }
  12539. }
  12540. return animatable;
  12541. };
  12542. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12543. if (speedRatio === undefined) {
  12544. speedRatio = 1.0;
  12545. }
  12546. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12547. return animatable;
  12548. };
  12549. Scene.prototype.getAnimatableByTarget = function (target) {
  12550. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12551. if (this._activeAnimatables[index].target === target) {
  12552. return this._activeAnimatables[index];
  12553. }
  12554. }
  12555. return null;
  12556. };
  12557. /**
  12558. * Will stop the animation of the given target
  12559. * @param target - the target
  12560. * @see beginAnimation
  12561. */
  12562. Scene.prototype.stopAnimation = function (target) {
  12563. var animatable = this.getAnimatableByTarget(target);
  12564. if (animatable) {
  12565. animatable.stop();
  12566. }
  12567. };
  12568. Scene.prototype._animate = function () {
  12569. if (!this.animationsEnabled) {
  12570. return;
  12571. }
  12572. if (!this._animationStartDate) {
  12573. this._animationStartDate = BABYLON.Tools.Now;
  12574. }
  12575. // Getting time
  12576. var now = BABYLON.Tools.Now;
  12577. var delay = now - this._animationStartDate;
  12578. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12579. this._activeAnimatables[index]._animate(delay);
  12580. }
  12581. };
  12582. // Matrix
  12583. Scene.prototype.getViewMatrix = function () {
  12584. return this._viewMatrix;
  12585. };
  12586. Scene.prototype.getProjectionMatrix = function () {
  12587. return this._projectionMatrix;
  12588. };
  12589. Scene.prototype.getTransformMatrix = function () {
  12590. return this._transformMatrix;
  12591. };
  12592. Scene.prototype.setTransformMatrix = function (view, projection) {
  12593. this._viewMatrix = view;
  12594. this._projectionMatrix = projection;
  12595. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12596. };
  12597. // Methods
  12598. Scene.prototype.addMesh = function (newMesh) {
  12599. newMesh.uniqueId = this._uniqueIdCounter++;
  12600. var position = this.meshes.push(newMesh);
  12601. //notify the collision coordinator
  12602. this.collisionCoordinator.onMeshAdded(newMesh);
  12603. if (this.onNewMeshAdded) {
  12604. this.onNewMeshAdded(newMesh, position, this);
  12605. }
  12606. };
  12607. Scene.prototype.removeMesh = function (toRemove) {
  12608. var index = this.meshes.indexOf(toRemove);
  12609. if (index !== -1) {
  12610. // Remove from the scene if mesh found
  12611. this.meshes.splice(index, 1);
  12612. }
  12613. //notify the collision coordinator
  12614. this.collisionCoordinator.onMeshRemoved(toRemove);
  12615. if (this.onMeshRemoved) {
  12616. this.onMeshRemoved(toRemove);
  12617. }
  12618. return index;
  12619. };
  12620. Scene.prototype.removeLight = function (toRemove) {
  12621. var index = this.lights.indexOf(toRemove);
  12622. if (index !== -1) {
  12623. // Remove from the scene if mesh found
  12624. this.lights.splice(index, 1);
  12625. }
  12626. if (this.onLightRemoved) {
  12627. this.onLightRemoved(toRemove);
  12628. }
  12629. return index;
  12630. };
  12631. Scene.prototype.removeCamera = function (toRemove) {
  12632. var index = this.cameras.indexOf(toRemove);
  12633. if (index !== -1) {
  12634. // Remove from the scene if mesh found
  12635. this.cameras.splice(index, 1);
  12636. }
  12637. // Remove from activeCameras
  12638. var index2 = this.activeCameras.indexOf(toRemove);
  12639. if (index2 !== -1) {
  12640. // Remove from the scene if mesh found
  12641. this.activeCameras.splice(index2, 1);
  12642. }
  12643. // Reset the activeCamera
  12644. if (this.activeCamera === toRemove) {
  12645. if (this.cameras.length > 0) {
  12646. this.activeCamera = this.cameras[0];
  12647. }
  12648. else {
  12649. this.activeCamera = null;
  12650. }
  12651. }
  12652. if (this.onCameraRemoved) {
  12653. this.onCameraRemoved(toRemove);
  12654. }
  12655. return index;
  12656. };
  12657. Scene.prototype.addLight = function (newLight) {
  12658. newLight.uniqueId = this._uniqueIdCounter++;
  12659. var position = this.lights.push(newLight);
  12660. if (this.onNewLightAdded) {
  12661. this.onNewLightAdded(newLight, position, this);
  12662. }
  12663. };
  12664. Scene.prototype.addCamera = function (newCamera) {
  12665. newCamera.uniqueId = this._uniqueIdCounter++;
  12666. var position = this.cameras.push(newCamera);
  12667. if (this.onNewCameraAdded) {
  12668. this.onNewCameraAdded(newCamera, position, this);
  12669. }
  12670. };
  12671. /**
  12672. * sets the active camera of the scene using its ID
  12673. * @param {string} id - the camera's ID
  12674. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12675. * @see activeCamera
  12676. */
  12677. Scene.prototype.setActiveCameraByID = function (id) {
  12678. var camera = this.getCameraByID(id);
  12679. if (camera) {
  12680. this.activeCamera = camera;
  12681. return camera;
  12682. }
  12683. return null;
  12684. };
  12685. /**
  12686. * sets the active camera of the scene using its name
  12687. * @param {string} name - the camera's name
  12688. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12689. * @see activeCamera
  12690. */
  12691. Scene.prototype.setActiveCameraByName = function (name) {
  12692. var camera = this.getCameraByName(name);
  12693. if (camera) {
  12694. this.activeCamera = camera;
  12695. return camera;
  12696. }
  12697. return null;
  12698. };
  12699. /**
  12700. * get a material using its id
  12701. * @param {string} the material's ID
  12702. * @return {BABYLON.Material|null} the material or null if none found.
  12703. */
  12704. Scene.prototype.getMaterialByID = function (id) {
  12705. for (var index = 0; index < this.materials.length; index++) {
  12706. if (this.materials[index].id === id) {
  12707. return this.materials[index];
  12708. }
  12709. }
  12710. return null;
  12711. };
  12712. /**
  12713. * get a material using its name
  12714. * @param {string} the material's name
  12715. * @return {BABYLON.Material|null} the material or null if none found.
  12716. */
  12717. Scene.prototype.getMaterialByName = function (name) {
  12718. for (var index = 0; index < this.materials.length; index++) {
  12719. if (this.materials[index].name === name) {
  12720. return this.materials[index];
  12721. }
  12722. }
  12723. return null;
  12724. };
  12725. Scene.prototype.getCameraByID = function (id) {
  12726. for (var index = 0; index < this.cameras.length; index++) {
  12727. if (this.cameras[index].id === id) {
  12728. return this.cameras[index];
  12729. }
  12730. }
  12731. return null;
  12732. };
  12733. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12734. for (var index = 0; index < this.cameras.length; index++) {
  12735. if (this.cameras[index].uniqueId === uniqueId) {
  12736. return this.cameras[index];
  12737. }
  12738. }
  12739. return null;
  12740. };
  12741. /**
  12742. * get a camera using its name
  12743. * @param {string} the camera's name
  12744. * @return {BABYLON.Camera|null} the camera or null if none found.
  12745. */
  12746. Scene.prototype.getCameraByName = function (name) {
  12747. for (var index = 0; index < this.cameras.length; index++) {
  12748. if (this.cameras[index].name === name) {
  12749. return this.cameras[index];
  12750. }
  12751. }
  12752. return null;
  12753. };
  12754. /**
  12755. * get a light node using its name
  12756. * @param {string} the light's name
  12757. * @return {BABYLON.Light|null} the light or null if none found.
  12758. */
  12759. Scene.prototype.getLightByName = function (name) {
  12760. for (var index = 0; index < this.lights.length; index++) {
  12761. if (this.lights[index].name === name) {
  12762. return this.lights[index];
  12763. }
  12764. }
  12765. return null;
  12766. };
  12767. /**
  12768. * get a light node using its ID
  12769. * @param {string} the light's id
  12770. * @return {BABYLON.Light|null} the light or null if none found.
  12771. */
  12772. Scene.prototype.getLightByID = function (id) {
  12773. for (var index = 0; index < this.lights.length; index++) {
  12774. if (this.lights[index].id === id) {
  12775. return this.lights[index];
  12776. }
  12777. }
  12778. return null;
  12779. };
  12780. /**
  12781. * get a light node using its scene-generated unique ID
  12782. * @param {number} the light's unique id
  12783. * @return {BABYLON.Light|null} the light or null if none found.
  12784. */
  12785. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12786. for (var index = 0; index < this.lights.length; index++) {
  12787. if (this.lights[index].uniqueId === uniqueId) {
  12788. return this.lights[index];
  12789. }
  12790. }
  12791. return null;
  12792. };
  12793. /**
  12794. * get a geometry using its ID
  12795. * @param {string} the geometry's id
  12796. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12797. */
  12798. Scene.prototype.getGeometryByID = function (id) {
  12799. for (var index = 0; index < this._geometries.length; index++) {
  12800. if (this._geometries[index].id === id) {
  12801. return this._geometries[index];
  12802. }
  12803. }
  12804. return null;
  12805. };
  12806. /**
  12807. * add a new geometry to this scene.
  12808. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12809. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12810. * @return {boolean} was the geometry added or not
  12811. */
  12812. Scene.prototype.pushGeometry = function (geometry, force) {
  12813. if (!force && this.getGeometryByID(geometry.id)) {
  12814. return false;
  12815. }
  12816. this._geometries.push(geometry);
  12817. //notify the collision coordinator
  12818. this.collisionCoordinator.onGeometryAdded(geometry);
  12819. if (this.onGeometryAdded) {
  12820. this.onGeometryAdded(geometry);
  12821. }
  12822. return true;
  12823. };
  12824. /**
  12825. * Removes an existing geometry
  12826. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12827. * @return {boolean} was the geometry removed or not
  12828. */
  12829. Scene.prototype.removeGeometry = function (geometry) {
  12830. var index = this._geometries.indexOf(geometry);
  12831. if (index > -1) {
  12832. this._geometries.splice(index, 1);
  12833. //notify the collision coordinator
  12834. this.collisionCoordinator.onGeometryDeleted(geometry);
  12835. if (this.onGeometryRemoved) {
  12836. this.onGeometryRemoved(geometry);
  12837. }
  12838. return true;
  12839. }
  12840. return false;
  12841. };
  12842. Scene.prototype.getGeometries = function () {
  12843. return this._geometries;
  12844. };
  12845. /**
  12846. * Get the first added mesh found of a given ID
  12847. * @param {string} id - the id to search for
  12848. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12849. */
  12850. Scene.prototype.getMeshByID = function (id) {
  12851. for (var index = 0; index < this.meshes.length; index++) {
  12852. if (this.meshes[index].id === id) {
  12853. return this.meshes[index];
  12854. }
  12855. }
  12856. return null;
  12857. };
  12858. /**
  12859. * Get a mesh with its auto-generated unique id
  12860. * @param {number} uniqueId - the unique id to search for
  12861. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12862. */
  12863. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12864. for (var index = 0; index < this.meshes.length; index++) {
  12865. if (this.meshes[index].uniqueId === uniqueId) {
  12866. return this.meshes[index];
  12867. }
  12868. }
  12869. return null;
  12870. };
  12871. /**
  12872. * Get a the last added mesh found of a given ID
  12873. * @param {string} id - the id to search for
  12874. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12875. */
  12876. Scene.prototype.getLastMeshByID = function (id) {
  12877. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12878. if (this.meshes[index].id === id) {
  12879. return this.meshes[index];
  12880. }
  12881. }
  12882. return null;
  12883. };
  12884. /**
  12885. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12886. * @param {string} id - the id to search for
  12887. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12888. */
  12889. Scene.prototype.getLastEntryByID = function (id) {
  12890. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12891. if (this.meshes[index].id === id) {
  12892. return this.meshes[index];
  12893. }
  12894. }
  12895. for (index = this.cameras.length - 1; index >= 0; index--) {
  12896. if (this.cameras[index].id === id) {
  12897. return this.cameras[index];
  12898. }
  12899. }
  12900. for (index = this.lights.length - 1; index >= 0; index--) {
  12901. if (this.lights[index].id === id) {
  12902. return this.lights[index];
  12903. }
  12904. }
  12905. return null;
  12906. };
  12907. Scene.prototype.getNodeByName = function (name) {
  12908. var mesh = this.getMeshByName(name);
  12909. if (mesh) {
  12910. return mesh;
  12911. }
  12912. var light = this.getLightByName(name);
  12913. if (light) {
  12914. return light;
  12915. }
  12916. return this.getCameraByName(name);
  12917. };
  12918. Scene.prototype.getMeshByName = function (name) {
  12919. for (var index = 0; index < this.meshes.length; index++) {
  12920. if (this.meshes[index].name === name) {
  12921. return this.meshes[index];
  12922. }
  12923. }
  12924. return null;
  12925. };
  12926. Scene.prototype.getSoundByName = function (name) {
  12927. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12928. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12929. return this.mainSoundTrack.soundCollection[index];
  12930. }
  12931. }
  12932. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12933. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12934. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12935. return this.soundTracks[sdIndex].soundCollection[index];
  12936. }
  12937. }
  12938. }
  12939. return null;
  12940. };
  12941. Scene.prototype.getLastSkeletonByID = function (id) {
  12942. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12943. if (this.skeletons[index].id === id) {
  12944. return this.skeletons[index];
  12945. }
  12946. }
  12947. return null;
  12948. };
  12949. Scene.prototype.getSkeletonById = function (id) {
  12950. for (var index = 0; index < this.skeletons.length; index++) {
  12951. if (this.skeletons[index].id === id) {
  12952. return this.skeletons[index];
  12953. }
  12954. }
  12955. return null;
  12956. };
  12957. Scene.prototype.getSkeletonByName = function (name) {
  12958. for (var index = 0; index < this.skeletons.length; index++) {
  12959. if (this.skeletons[index].name === name) {
  12960. return this.skeletons[index];
  12961. }
  12962. }
  12963. return null;
  12964. };
  12965. Scene.prototype.isActiveMesh = function (mesh) {
  12966. return (this._activeMeshes.indexOf(mesh) !== -1);
  12967. };
  12968. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12969. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12970. var material = subMesh.getMaterial();
  12971. if (mesh.showSubMeshesBoundingBox) {
  12972. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12973. }
  12974. if (material) {
  12975. // Render targets
  12976. if (material.getRenderTargetTextures) {
  12977. if (this._processedMaterials.indexOf(material) === -1) {
  12978. this._processedMaterials.push(material);
  12979. this._renderTargets.concat(material.getRenderTargetTextures());
  12980. }
  12981. }
  12982. // Dispatch
  12983. this._activeIndices += subMesh.indexCount;
  12984. this._renderingManager.dispatch(subMesh);
  12985. }
  12986. }
  12987. };
  12988. Scene.prototype._evaluateActiveMeshes = function () {
  12989. this.activeCamera._activeMeshes.reset();
  12990. this._activeMeshes.reset();
  12991. this._renderingManager.reset();
  12992. this._processedMaterials.reset();
  12993. this._activeParticleSystems.reset();
  12994. this._activeSkeletons.reset();
  12995. this._boundingBoxRenderer.reset();
  12996. if (!this._frustumPlanes) {
  12997. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12998. }
  12999. else {
  13000. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13001. }
  13002. // Meshes
  13003. var meshes;
  13004. var len;
  13005. if (this._selectionOctree) {
  13006. var selection = this._selectionOctree.select(this._frustumPlanes);
  13007. meshes = selection.data;
  13008. len = selection.length;
  13009. }
  13010. else {
  13011. len = this.meshes.length;
  13012. meshes = this.meshes;
  13013. }
  13014. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13015. var mesh = meshes[meshIndex];
  13016. if (mesh.isBlocked) {
  13017. continue;
  13018. }
  13019. this._totalVertices += mesh.getTotalVertices();
  13020. if (!mesh.isReady() || !mesh.isEnabled()) {
  13021. continue;
  13022. }
  13023. mesh.computeWorldMatrix();
  13024. // Intersections
  13025. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13026. this._meshesForIntersections.pushNoDuplicate(mesh);
  13027. }
  13028. // Switch to current LOD
  13029. var meshLOD = mesh.getLOD(this.activeCamera);
  13030. if (!meshLOD) {
  13031. continue;
  13032. }
  13033. mesh._preActivate();
  13034. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13035. this._activeMeshes.push(mesh);
  13036. this.activeCamera._activeMeshes.push(mesh);
  13037. mesh._activate(this._renderId);
  13038. this._activeMesh(meshLOD);
  13039. }
  13040. }
  13041. // Particle systems
  13042. var beforeParticlesDate = BABYLON.Tools.Now;
  13043. if (this.particlesEnabled) {
  13044. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13045. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13046. var particleSystem = this.particleSystems[particleIndex];
  13047. if (!particleSystem.isStarted()) {
  13048. continue;
  13049. }
  13050. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13051. this._activeParticleSystems.push(particleSystem);
  13052. particleSystem.animate();
  13053. }
  13054. }
  13055. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13056. }
  13057. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13058. };
  13059. Scene.prototype._activeMesh = function (mesh) {
  13060. if (mesh.skeleton && this.skeletonsEnabled) {
  13061. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13062. }
  13063. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13064. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13065. }
  13066. if (mesh && mesh.subMeshes) {
  13067. // Submeshes Octrees
  13068. var len;
  13069. var subMeshes;
  13070. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13071. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13072. len = intersections.length;
  13073. subMeshes = intersections.data;
  13074. }
  13075. else {
  13076. subMeshes = mesh.subMeshes;
  13077. len = subMeshes.length;
  13078. }
  13079. for (var subIndex = 0; subIndex < len; subIndex++) {
  13080. var subMesh = subMeshes[subIndex];
  13081. this._evaluateSubMesh(subMesh, mesh);
  13082. }
  13083. }
  13084. };
  13085. Scene.prototype.updateTransformMatrix = function (force) {
  13086. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13087. };
  13088. Scene.prototype._renderForCamera = function (camera) {
  13089. var engine = this._engine;
  13090. this.activeCamera = camera;
  13091. if (!this.activeCamera)
  13092. throw new Error("Active camera not set");
  13093. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13094. // Viewport
  13095. engine.setViewport(this.activeCamera.viewport);
  13096. // Camera
  13097. this.resetCachedMaterial();
  13098. this._renderId++;
  13099. this.updateTransformMatrix();
  13100. if (this.beforeCameraRender) {
  13101. this.beforeCameraRender(this.activeCamera);
  13102. }
  13103. // Meshes
  13104. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13105. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13106. this._evaluateActiveMeshes();
  13107. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13108. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13109. // Skeletons
  13110. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13111. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13112. skeleton.prepare();
  13113. }
  13114. // Render targets
  13115. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13116. if (this.renderTargetsEnabled) {
  13117. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13118. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13119. var renderTarget = this._renderTargets.data[renderIndex];
  13120. if (renderTarget._shouldRender()) {
  13121. this._renderId++;
  13122. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13123. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13124. }
  13125. }
  13126. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13127. this._renderId++;
  13128. }
  13129. if (this._renderTargets.length > 0) {
  13130. engine.restoreDefaultFramebuffer();
  13131. }
  13132. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13133. // Prepare Frame
  13134. this.postProcessManager._prepareFrame();
  13135. var beforeRenderDate = BABYLON.Tools.Now;
  13136. // Backgrounds
  13137. if (this.layers.length) {
  13138. engine.setDepthBuffer(false);
  13139. var layerIndex;
  13140. var layer;
  13141. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13142. layer = this.layers[layerIndex];
  13143. if (layer.isBackground) {
  13144. layer.render();
  13145. }
  13146. }
  13147. engine.setDepthBuffer(true);
  13148. }
  13149. // Render
  13150. BABYLON.Tools.StartPerformanceCounter("Main render");
  13151. this._renderingManager.render(null, null, true, true);
  13152. BABYLON.Tools.EndPerformanceCounter("Main render");
  13153. // Bounding boxes
  13154. this._boundingBoxRenderer.render();
  13155. // Lens flares
  13156. if (this.lensFlaresEnabled) {
  13157. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13158. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13159. this.lensFlareSystems[lensFlareSystemIndex].render();
  13160. }
  13161. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13162. }
  13163. // Foregrounds
  13164. if (this.layers.length) {
  13165. engine.setDepthBuffer(false);
  13166. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13167. layer = this.layers[layerIndex];
  13168. if (!layer.isBackground) {
  13169. layer.render();
  13170. }
  13171. }
  13172. engine.setDepthBuffer(true);
  13173. }
  13174. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13175. // Finalize frame
  13176. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13177. // Update camera
  13178. this.activeCamera._updateFromScene();
  13179. // Reset some special arrays
  13180. this._renderTargets.reset();
  13181. if (this.afterCameraRender) {
  13182. this.afterCameraRender(this.activeCamera);
  13183. }
  13184. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13185. };
  13186. Scene.prototype._processSubCameras = function (camera) {
  13187. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13188. this._renderForCamera(camera);
  13189. return;
  13190. }
  13191. // rig cameras
  13192. for (var index = 0; index < camera._rigCameras.length; index++) {
  13193. this._renderForCamera(camera._rigCameras[index]);
  13194. }
  13195. this.activeCamera = camera;
  13196. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13197. // Update camera
  13198. this.activeCamera._updateFromScene();
  13199. };
  13200. Scene.prototype._checkIntersections = function () {
  13201. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13202. var sourceMesh = this._meshesForIntersections.data[index];
  13203. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13204. var action = sourceMesh.actionManager.actions[actionIndex];
  13205. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13206. var parameters = action.getTriggerParameter();
  13207. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13208. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13209. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13210. if (areIntersecting && currentIntersectionInProgress === -1) {
  13211. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13212. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13213. sourceMesh._intersectionsInProgress.push(otherMesh);
  13214. }
  13215. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13216. sourceMesh._intersectionsInProgress.push(otherMesh);
  13217. }
  13218. }
  13219. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13220. //They intersected, and now they don't.
  13221. //is this trigger an exit trigger? execute an event.
  13222. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13223. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13224. }
  13225. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13226. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13227. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13228. }
  13229. }
  13230. }
  13231. }
  13232. }
  13233. };
  13234. Scene.prototype.render = function () {
  13235. var startDate = BABYLON.Tools.Now;
  13236. this._particlesDuration = 0;
  13237. this._spritesDuration = 0;
  13238. this._activeParticles = 0;
  13239. this._renderDuration = 0;
  13240. this._renderTargetsDuration = 0;
  13241. this._evaluateActiveMeshesDuration = 0;
  13242. this._totalVertices = 0;
  13243. this._activeIndices = 0;
  13244. this._activeBones = 0;
  13245. this.getEngine().resetDrawCalls();
  13246. this._meshesForIntersections.reset();
  13247. this.resetCachedMaterial();
  13248. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13249. // Actions
  13250. if (this.actionManager) {
  13251. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13252. }
  13253. //Simplification Queue
  13254. if (!this.simplificationQueue.running) {
  13255. this.simplificationQueue.executeNext();
  13256. }
  13257. // Before render
  13258. if (this.beforeRender) {
  13259. this.beforeRender();
  13260. }
  13261. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13262. this._onBeforeRenderCallbacks[callbackIndex]();
  13263. }
  13264. // Animations
  13265. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13266. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13267. this._animate();
  13268. // Physics
  13269. if (this._physicsEngine) {
  13270. BABYLON.Tools.StartPerformanceCounter("Physics");
  13271. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13272. BABYLON.Tools.EndPerformanceCounter("Physics");
  13273. }
  13274. // Customs render targets
  13275. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13276. var engine = this.getEngine();
  13277. var currentActiveCamera = this.activeCamera;
  13278. if (this.renderTargetsEnabled) {
  13279. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13280. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13281. var renderTarget = this.customRenderTargets[customIndex];
  13282. if (renderTarget._shouldRender()) {
  13283. this._renderId++;
  13284. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13285. if (!this.activeCamera)
  13286. throw new Error("Active camera not set");
  13287. // Viewport
  13288. engine.setViewport(this.activeCamera.viewport);
  13289. // Camera
  13290. this.updateTransformMatrix();
  13291. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13292. }
  13293. }
  13294. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13295. this._renderId++;
  13296. }
  13297. if (this.customRenderTargets.length > 0) {
  13298. engine.restoreDefaultFramebuffer();
  13299. }
  13300. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13301. this.activeCamera = currentActiveCamera;
  13302. // Procedural textures
  13303. if (this.proceduralTexturesEnabled) {
  13304. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13305. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13306. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13307. if (proceduralTexture._shouldRender()) {
  13308. proceduralTexture.render();
  13309. }
  13310. }
  13311. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13312. }
  13313. // Clear
  13314. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13315. // Shadows
  13316. if (this.shadowsEnabled) {
  13317. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13318. var light = this.lights[lightIndex];
  13319. var shadowGenerator = light.getShadowGenerator();
  13320. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13321. this._renderTargets.push(shadowGenerator.getShadowMap());
  13322. }
  13323. }
  13324. }
  13325. // Depth renderer
  13326. if (this._depthRenderer) {
  13327. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13328. }
  13329. // RenderPipeline
  13330. this.postProcessRenderPipelineManager.update();
  13331. // Multi-cameras?
  13332. if (this.activeCameras.length > 0) {
  13333. var currentRenderId = this._renderId;
  13334. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13335. this._renderId = currentRenderId;
  13336. this._processSubCameras(this.activeCameras[cameraIndex]);
  13337. }
  13338. }
  13339. else {
  13340. if (!this.activeCamera) {
  13341. throw new Error("No camera defined");
  13342. }
  13343. this._processSubCameras(this.activeCamera);
  13344. }
  13345. // Intersection checks
  13346. this._checkIntersections();
  13347. // Update the audio listener attached to the camera
  13348. this._updateAudioParameters();
  13349. // After render
  13350. if (this.afterRender) {
  13351. this.afterRender();
  13352. }
  13353. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13354. this._onAfterRenderCallbacks[callbackIndex]();
  13355. }
  13356. // Cleaning
  13357. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13358. this._toBeDisposed.data[index].dispose();
  13359. this._toBeDisposed[index] = null;
  13360. }
  13361. this._toBeDisposed.reset();
  13362. if (this.dumpNextRenderTargets) {
  13363. this.dumpNextRenderTargets = false;
  13364. }
  13365. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13366. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13367. };
  13368. Scene.prototype._updateAudioParameters = function () {
  13369. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13370. return;
  13371. }
  13372. var listeningCamera;
  13373. var audioEngine = BABYLON.Engine.audioEngine;
  13374. if (this.activeCameras.length > 0) {
  13375. listeningCamera = this.activeCameras[0];
  13376. }
  13377. else {
  13378. listeningCamera = this.activeCamera;
  13379. }
  13380. if (listeningCamera && audioEngine.canUseWebAudio) {
  13381. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13382. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13383. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13384. cameraDirection.normalize();
  13385. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13386. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13387. var sound = this.mainSoundTrack.soundCollection[i];
  13388. if (sound.useCustomAttenuation) {
  13389. sound.updateDistanceFromListener();
  13390. }
  13391. }
  13392. for (i = 0; i < this.soundTracks.length; i++) {
  13393. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13394. sound = this.soundTracks[i].soundCollection[j];
  13395. if (sound.useCustomAttenuation) {
  13396. sound.updateDistanceFromListener();
  13397. }
  13398. }
  13399. }
  13400. }
  13401. };
  13402. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13403. // Audio
  13404. get: function () {
  13405. return this._audioEnabled;
  13406. },
  13407. set: function (value) {
  13408. this._audioEnabled = value;
  13409. if (this._audioEnabled) {
  13410. this._enableAudio();
  13411. }
  13412. else {
  13413. this._disableAudio();
  13414. }
  13415. },
  13416. enumerable: true,
  13417. configurable: true
  13418. });
  13419. Scene.prototype._disableAudio = function () {
  13420. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13421. this.mainSoundTrack.soundCollection[i].pause();
  13422. }
  13423. for (i = 0; i < this.soundTracks.length; i++) {
  13424. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13425. this.soundTracks[i].soundCollection[j].pause();
  13426. }
  13427. }
  13428. };
  13429. Scene.prototype._enableAudio = function () {
  13430. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13431. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13432. this.mainSoundTrack.soundCollection[i].play();
  13433. }
  13434. }
  13435. for (i = 0; i < this.soundTracks.length; i++) {
  13436. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13437. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13438. this.soundTracks[i].soundCollection[j].play();
  13439. }
  13440. }
  13441. }
  13442. };
  13443. Object.defineProperty(Scene.prototype, "headphone", {
  13444. get: function () {
  13445. return this._headphone;
  13446. },
  13447. set: function (value) {
  13448. this._headphone = value;
  13449. if (this._headphone) {
  13450. this._switchAudioModeForHeadphones();
  13451. }
  13452. else {
  13453. this._switchAudioModeForNormalSpeakers();
  13454. }
  13455. },
  13456. enumerable: true,
  13457. configurable: true
  13458. });
  13459. Scene.prototype._switchAudioModeForHeadphones = function () {
  13460. this.mainSoundTrack.switchPanningModelToHRTF();
  13461. for (var i = 0; i < this.soundTracks.length; i++) {
  13462. this.soundTracks[i].switchPanningModelToHRTF();
  13463. }
  13464. };
  13465. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13466. this.mainSoundTrack.switchPanningModelToEqualPower();
  13467. for (var i = 0; i < this.soundTracks.length; i++) {
  13468. this.soundTracks[i].switchPanningModelToEqualPower();
  13469. }
  13470. };
  13471. Scene.prototype.enableDepthRenderer = function () {
  13472. if (this._depthRenderer) {
  13473. return this._depthRenderer;
  13474. }
  13475. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13476. return this._depthRenderer;
  13477. };
  13478. Scene.prototype.disableDepthRenderer = function () {
  13479. if (!this._depthRenderer) {
  13480. return;
  13481. }
  13482. this._depthRenderer.dispose();
  13483. this._depthRenderer = null;
  13484. };
  13485. Scene.prototype.dispose = function () {
  13486. this.beforeRender = null;
  13487. this.afterRender = null;
  13488. this.skeletons = [];
  13489. this._boundingBoxRenderer.dispose();
  13490. if (this._depthRenderer) {
  13491. this._depthRenderer.dispose();
  13492. }
  13493. // Debug layer
  13494. this.debugLayer.hide();
  13495. // Events
  13496. if (this.onDispose) {
  13497. this.onDispose();
  13498. }
  13499. this._onBeforeRenderCallbacks = [];
  13500. this._onAfterRenderCallbacks = [];
  13501. this.detachControl();
  13502. // Release sounds & sounds tracks
  13503. this.disposeSounds();
  13504. // Detach cameras
  13505. var canvas = this._engine.getRenderingCanvas();
  13506. var index;
  13507. for (index = 0; index < this.cameras.length; index++) {
  13508. this.cameras[index].detachControl(canvas);
  13509. }
  13510. // Release lights
  13511. while (this.lights.length) {
  13512. this.lights[0].dispose();
  13513. }
  13514. // Release meshes
  13515. while (this.meshes.length) {
  13516. this.meshes[0].dispose(true);
  13517. }
  13518. // Release cameras
  13519. while (this.cameras.length) {
  13520. this.cameras[0].dispose();
  13521. }
  13522. // Release materials
  13523. while (this.materials.length) {
  13524. this.materials[0].dispose();
  13525. }
  13526. // Release particles
  13527. while (this.particleSystems.length) {
  13528. this.particleSystems[0].dispose();
  13529. }
  13530. // Release sprites
  13531. while (this.spriteManagers.length) {
  13532. this.spriteManagers[0].dispose();
  13533. }
  13534. // Release layers
  13535. while (this.layers.length) {
  13536. this.layers[0].dispose();
  13537. }
  13538. // Release textures
  13539. while (this.textures.length) {
  13540. this.textures[0].dispose();
  13541. }
  13542. // Post-processes
  13543. this.postProcessManager.dispose();
  13544. // Physics
  13545. if (this._physicsEngine) {
  13546. this.disablePhysicsEngine();
  13547. }
  13548. // Remove from engine
  13549. index = this._engine.scenes.indexOf(this);
  13550. if (index > -1) {
  13551. this._engine.scenes.splice(index, 1);
  13552. }
  13553. this._engine.wipeCaches();
  13554. };
  13555. // Release sounds & sounds tracks
  13556. Scene.prototype.disposeSounds = function () {
  13557. this.mainSoundTrack.dispose();
  13558. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13559. this.soundTracks[scIndex].dispose();
  13560. }
  13561. };
  13562. // Octrees
  13563. Scene.prototype.getWorldExtends = function () {
  13564. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13565. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13566. for (var index = 0; index < this.meshes.length; index++) {
  13567. var mesh = this.meshes[index];
  13568. mesh.computeWorldMatrix(true);
  13569. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13570. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13571. BABYLON.Tools.CheckExtends(minBox, min, max);
  13572. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13573. }
  13574. return {
  13575. min: min,
  13576. max: max
  13577. };
  13578. };
  13579. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13580. if (maxCapacity === void 0) { maxCapacity = 64; }
  13581. if (maxDepth === void 0) { maxDepth = 2; }
  13582. if (!this._selectionOctree) {
  13583. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13584. }
  13585. var worldExtends = this.getWorldExtends();
  13586. // Update octree
  13587. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13588. return this._selectionOctree;
  13589. };
  13590. // Picking
  13591. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13592. var engine = this._engine;
  13593. if (!camera) {
  13594. if (!this.activeCamera)
  13595. throw new Error("Active camera not set");
  13596. camera = this.activeCamera;
  13597. }
  13598. var cameraViewport = camera.viewport;
  13599. var viewport = cameraViewport.toGlobal(engine);
  13600. // Moving coordinates to local viewport world
  13601. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13602. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13603. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13604. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13605. };
  13606. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13607. var pickingInfo = null;
  13608. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13609. var mesh = this.meshes[meshIndex];
  13610. if (predicate) {
  13611. if (!predicate(mesh)) {
  13612. continue;
  13613. }
  13614. }
  13615. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13616. continue;
  13617. }
  13618. var world = mesh.getWorldMatrix();
  13619. var ray = rayFunction(world);
  13620. var result = mesh.intersects(ray, fastCheck);
  13621. if (!result || !result.hit)
  13622. continue;
  13623. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13624. continue;
  13625. pickingInfo = result;
  13626. if (fastCheck) {
  13627. break;
  13628. }
  13629. }
  13630. return pickingInfo || new BABYLON.PickingInfo();
  13631. };
  13632. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13633. var _this = this;
  13634. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13635. /// <param name="x">X position on screen</param>
  13636. /// <param name="y">Y position on screen</param>
  13637. /// <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>
  13638. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13639. /// <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>
  13640. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13641. };
  13642. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13643. var _this = this;
  13644. return this._internalPick(function (world) {
  13645. if (!_this._pickWithRayInverseMatrix) {
  13646. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13647. }
  13648. world.invertToRef(_this._pickWithRayInverseMatrix);
  13649. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13650. }, predicate, fastCheck);
  13651. };
  13652. Scene.prototype.setPointerOverMesh = function (mesh) {
  13653. if (this._pointerOverMesh === mesh) {
  13654. return;
  13655. }
  13656. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13657. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13658. }
  13659. this._pointerOverMesh = mesh;
  13660. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13661. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13662. }
  13663. };
  13664. Scene.prototype.getPointerOverMesh = function () {
  13665. return this._pointerOverMesh;
  13666. };
  13667. // Physics
  13668. Scene.prototype.getPhysicsEngine = function () {
  13669. return this._physicsEngine;
  13670. };
  13671. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13672. if (this._physicsEngine) {
  13673. return true;
  13674. }
  13675. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13676. if (!this._physicsEngine.isSupported()) {
  13677. this._physicsEngine = null;
  13678. return false;
  13679. }
  13680. this._physicsEngine._initialize(gravity);
  13681. return true;
  13682. };
  13683. Scene.prototype.disablePhysicsEngine = function () {
  13684. if (!this._physicsEngine) {
  13685. return;
  13686. }
  13687. this._physicsEngine.dispose();
  13688. this._physicsEngine = undefined;
  13689. };
  13690. Scene.prototype.isPhysicsEnabled = function () {
  13691. return this._physicsEngine !== undefined;
  13692. };
  13693. Scene.prototype.setGravity = function (gravity) {
  13694. if (!this._physicsEngine) {
  13695. return;
  13696. }
  13697. this._physicsEngine._setGravity(gravity);
  13698. };
  13699. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13700. if (parts.parts) {
  13701. options = parts;
  13702. parts = parts.parts;
  13703. }
  13704. if (!this._physicsEngine) {
  13705. return null;
  13706. }
  13707. for (var index = 0; index < parts.length; index++) {
  13708. var mesh = parts[index].mesh;
  13709. mesh._physicImpostor = parts[index].impostor;
  13710. mesh._physicsMass = options.mass / parts.length;
  13711. mesh._physicsFriction = options.friction;
  13712. mesh._physicRestitution = options.restitution;
  13713. }
  13714. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13715. };
  13716. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13717. for (var index = 0; index < compound.parts.length; index++) {
  13718. var mesh = compound.parts[index].mesh;
  13719. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13720. this._physicsEngine._unregisterMesh(mesh);
  13721. }
  13722. };
  13723. // Misc.
  13724. Scene.prototype.createDefaultCameraOrLight = function () {
  13725. // Light
  13726. if (this.lights.length === 0) {
  13727. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13728. }
  13729. // Camera
  13730. if (!this.activeCamera) {
  13731. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13732. // Compute position
  13733. var worldExtends = this.getWorldExtends();
  13734. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13735. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13736. camera.setTarget(worldCenter);
  13737. this.activeCamera = camera;
  13738. }
  13739. };
  13740. // Tags
  13741. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13742. if (tagsQuery === undefined) {
  13743. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13744. return list;
  13745. }
  13746. var listByTags = [];
  13747. forEach = forEach || (function (item) { return; });
  13748. for (var i in list) {
  13749. var item = list[i];
  13750. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13751. listByTags.push(item);
  13752. forEach(item);
  13753. }
  13754. }
  13755. return listByTags;
  13756. };
  13757. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13758. return this._getByTags(this.meshes, tagsQuery, forEach);
  13759. };
  13760. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13761. return this._getByTags(this.cameras, tagsQuery, forEach);
  13762. };
  13763. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13764. return this._getByTags(this.lights, tagsQuery, forEach);
  13765. };
  13766. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13767. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13768. };
  13769. // Statics
  13770. Scene._FOGMODE_NONE = 0;
  13771. Scene._FOGMODE_EXP = 1;
  13772. Scene._FOGMODE_EXP2 = 2;
  13773. Scene._FOGMODE_LINEAR = 3;
  13774. Scene.MinDeltaTime = 1.0;
  13775. Scene.MaxDeltaTime = 1000.0;
  13776. return Scene;
  13777. })();
  13778. BABYLON.Scene = Scene;
  13779. })(BABYLON || (BABYLON = {}));
  13780. //# sourceMappingURL=babylon.scene.js.map
  13781. var BABYLON;
  13782. (function (BABYLON) {
  13783. var VertexBuffer = (function () {
  13784. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13785. if (engine instanceof BABYLON.Mesh) {
  13786. this._engine = engine.getScene().getEngine();
  13787. }
  13788. else {
  13789. this._engine = engine;
  13790. }
  13791. this._updatable = updatable;
  13792. this._data = data;
  13793. if (!postponeInternalCreation) {
  13794. this.create();
  13795. }
  13796. this._kind = kind;
  13797. if (stride) {
  13798. this._strideSize = stride;
  13799. return;
  13800. }
  13801. // Deduce stride from kind
  13802. switch (kind) {
  13803. case VertexBuffer.PositionKind:
  13804. this._strideSize = 3;
  13805. break;
  13806. case VertexBuffer.NormalKind:
  13807. this._strideSize = 3;
  13808. break;
  13809. case VertexBuffer.UVKind:
  13810. this._strideSize = 2;
  13811. break;
  13812. case VertexBuffer.UV2Kind:
  13813. this._strideSize = 2;
  13814. break;
  13815. case VertexBuffer.ColorKind:
  13816. this._strideSize = 4;
  13817. break;
  13818. case VertexBuffer.MatricesIndicesKind:
  13819. this._strideSize = 4;
  13820. break;
  13821. case VertexBuffer.MatricesWeightsKind:
  13822. this._strideSize = 4;
  13823. break;
  13824. }
  13825. }
  13826. // Properties
  13827. VertexBuffer.prototype.isUpdatable = function () {
  13828. return this._updatable;
  13829. };
  13830. VertexBuffer.prototype.getData = function () {
  13831. return this._data;
  13832. };
  13833. VertexBuffer.prototype.getBuffer = function () {
  13834. return this._buffer;
  13835. };
  13836. VertexBuffer.prototype.getStrideSize = function () {
  13837. return this._strideSize;
  13838. };
  13839. // Methods
  13840. VertexBuffer.prototype.create = function (data) {
  13841. if (!data && this._buffer) {
  13842. return; // nothing to do
  13843. }
  13844. data = data || this._data;
  13845. if (!this._buffer) {
  13846. if (this._updatable) {
  13847. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13848. }
  13849. else {
  13850. this._buffer = this._engine.createVertexBuffer(data);
  13851. }
  13852. }
  13853. if (this._updatable) {
  13854. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13855. this._data = data;
  13856. }
  13857. };
  13858. VertexBuffer.prototype.update = function (data) {
  13859. this.create(data);
  13860. };
  13861. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13862. if (!this._buffer) {
  13863. return;
  13864. }
  13865. if (this._updatable) {
  13866. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13867. this._data = null;
  13868. }
  13869. };
  13870. VertexBuffer.prototype.dispose = function () {
  13871. if (!this._buffer) {
  13872. return;
  13873. }
  13874. if (this._engine._releaseBuffer(this._buffer)) {
  13875. this._buffer = null;
  13876. }
  13877. };
  13878. Object.defineProperty(VertexBuffer, "PositionKind", {
  13879. get: function () {
  13880. return VertexBuffer._PositionKind;
  13881. },
  13882. enumerable: true,
  13883. configurable: true
  13884. });
  13885. Object.defineProperty(VertexBuffer, "NormalKind", {
  13886. get: function () {
  13887. return VertexBuffer._NormalKind;
  13888. },
  13889. enumerable: true,
  13890. configurable: true
  13891. });
  13892. Object.defineProperty(VertexBuffer, "UVKind", {
  13893. get: function () {
  13894. return VertexBuffer._UVKind;
  13895. },
  13896. enumerable: true,
  13897. configurable: true
  13898. });
  13899. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13900. get: function () {
  13901. return VertexBuffer._UV2Kind;
  13902. },
  13903. enumerable: true,
  13904. configurable: true
  13905. });
  13906. Object.defineProperty(VertexBuffer, "ColorKind", {
  13907. get: function () {
  13908. return VertexBuffer._ColorKind;
  13909. },
  13910. enumerable: true,
  13911. configurable: true
  13912. });
  13913. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13914. get: function () {
  13915. return VertexBuffer._MatricesIndicesKind;
  13916. },
  13917. enumerable: true,
  13918. configurable: true
  13919. });
  13920. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13921. get: function () {
  13922. return VertexBuffer._MatricesWeightsKind;
  13923. },
  13924. enumerable: true,
  13925. configurable: true
  13926. });
  13927. // Enums
  13928. VertexBuffer._PositionKind = "position";
  13929. VertexBuffer._NormalKind = "normal";
  13930. VertexBuffer._UVKind = "uv";
  13931. VertexBuffer._UV2Kind = "uv2";
  13932. VertexBuffer._ColorKind = "color";
  13933. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13934. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13935. return VertexBuffer;
  13936. })();
  13937. BABYLON.VertexBuffer = VertexBuffer;
  13938. })(BABYLON || (BABYLON = {}));
  13939. //# sourceMappingURL=babylon.vertexBuffer.js.map
  13940. var BABYLON;
  13941. (function (BABYLON) {
  13942. /**
  13943. * Creates an instance based on a source mesh.
  13944. */
  13945. var InstancedMesh = (function (_super) {
  13946. __extends(InstancedMesh, _super);
  13947. function InstancedMesh(name, source) {
  13948. _super.call(this, name, source.getScene());
  13949. source.instances.push(this);
  13950. this._sourceMesh = source;
  13951. this.position.copyFrom(source.position);
  13952. this.rotation.copyFrom(source.rotation);
  13953. this.scaling.copyFrom(source.scaling);
  13954. if (source.rotationQuaternion) {
  13955. this.rotationQuaternion = source.rotationQuaternion.clone();
  13956. }
  13957. this.infiniteDistance = source.infiniteDistance;
  13958. this.setPivotMatrix(source.getPivotMatrix());
  13959. this.refreshBoundingInfo();
  13960. this._syncSubMeshes();
  13961. }
  13962. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13963. // Methods
  13964. get: function () {
  13965. return this._sourceMesh.receiveShadows;
  13966. },
  13967. enumerable: true,
  13968. configurable: true
  13969. });
  13970. Object.defineProperty(InstancedMesh.prototype, "material", {
  13971. get: function () {
  13972. return this._sourceMesh.material;
  13973. },
  13974. enumerable: true,
  13975. configurable: true
  13976. });
  13977. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13978. get: function () {
  13979. return this._sourceMesh.visibility;
  13980. },
  13981. enumerable: true,
  13982. configurable: true
  13983. });
  13984. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13985. get: function () {
  13986. return this._sourceMesh.skeleton;
  13987. },
  13988. enumerable: true,
  13989. configurable: true
  13990. });
  13991. InstancedMesh.prototype.getTotalVertices = function () {
  13992. return this._sourceMesh.getTotalVertices();
  13993. };
  13994. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13995. get: function () {
  13996. return this._sourceMesh;
  13997. },
  13998. enumerable: true,
  13999. configurable: true
  14000. });
  14001. InstancedMesh.prototype.getVerticesData = function (kind) {
  14002. return this._sourceMesh.getVerticesData(kind);
  14003. };
  14004. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14005. return this._sourceMesh.isVerticesDataPresent(kind);
  14006. };
  14007. InstancedMesh.prototype.getIndices = function () {
  14008. return this._sourceMesh.getIndices();
  14009. };
  14010. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14011. get: function () {
  14012. return this._sourceMesh._positions;
  14013. },
  14014. enumerable: true,
  14015. configurable: true
  14016. });
  14017. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14018. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14019. if (data) {
  14020. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14021. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14022. }
  14023. this._updateBoundingInfo();
  14024. };
  14025. InstancedMesh.prototype._preActivate = function () {
  14026. if (this._currentLOD) {
  14027. this._currentLOD._preActivate();
  14028. }
  14029. };
  14030. InstancedMesh.prototype._activate = function (renderId) {
  14031. if (this._currentLOD) {
  14032. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14033. }
  14034. };
  14035. InstancedMesh.prototype.getLOD = function (camera) {
  14036. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14037. if (this._currentLOD === this.sourceMesh) {
  14038. return this;
  14039. }
  14040. return this._currentLOD;
  14041. };
  14042. InstancedMesh.prototype._syncSubMeshes = function () {
  14043. this.releaseSubMeshes();
  14044. if (this._sourceMesh.subMeshes) {
  14045. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14046. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14047. }
  14048. }
  14049. };
  14050. InstancedMesh.prototype._generatePointsArray = function () {
  14051. return this._sourceMesh._generatePointsArray();
  14052. };
  14053. // Clone
  14054. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14055. var result = this._sourceMesh.createInstance(name);
  14056. // Deep copy
  14057. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14058. // Bounding info
  14059. this.refreshBoundingInfo();
  14060. // Parent
  14061. if (newParent) {
  14062. result.parent = newParent;
  14063. }
  14064. if (!doNotCloneChildren) {
  14065. // Children
  14066. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14067. var mesh = this.getScene().meshes[index];
  14068. if (mesh.parent === this) {
  14069. mesh.clone(mesh.name, result);
  14070. }
  14071. }
  14072. }
  14073. result.computeWorldMatrix(true);
  14074. return result;
  14075. };
  14076. // Dispoe
  14077. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14078. // Remove from mesh
  14079. var index = this._sourceMesh.instances.indexOf(this);
  14080. this._sourceMesh.instances.splice(index, 1);
  14081. _super.prototype.dispose.call(this, doNotRecurse);
  14082. };
  14083. return InstancedMesh;
  14084. })(BABYLON.AbstractMesh);
  14085. BABYLON.InstancedMesh = InstancedMesh;
  14086. })(BABYLON || (BABYLON = {}));
  14087. //# sourceMappingURL=babylon.instancedMesh.js.map
  14088. var BABYLON;
  14089. (function (BABYLON) {
  14090. var _InstancesBatch = (function () {
  14091. function _InstancesBatch() {
  14092. this.mustReturn = false;
  14093. this.visibleInstances = new Array();
  14094. this.renderSelf = new Array();
  14095. }
  14096. return _InstancesBatch;
  14097. })();
  14098. BABYLON._InstancesBatch = _InstancesBatch;
  14099. var Mesh = (function (_super) {
  14100. __extends(Mesh, _super);
  14101. /**
  14102. * @constructor
  14103. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14104. * @param {Scene} scene - The scene to add this mesh to.
  14105. * @param {Node} parent - The parent of this mesh, if it has one
  14106. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14107. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14108. * When false, achieved by calling a clone(), also passing False.
  14109. * This will make creation of children, recursive.
  14110. */
  14111. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14112. if (parent === void 0) { parent = null; }
  14113. _super.call(this, name, scene);
  14114. // Members
  14115. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14116. this.instances = new Array();
  14117. this._LODLevels = new Array();
  14118. this._onBeforeRenderCallbacks = new Array();
  14119. this._onAfterRenderCallbacks = new Array();
  14120. this._visibleInstances = {};
  14121. this._renderIdForInstances = new Array();
  14122. this._batchCache = new _InstancesBatch();
  14123. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14124. this._sideOrientation = Mesh._DEFAULTSIDE;
  14125. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14126. if (source) {
  14127. // Geometry
  14128. if (source._geometry) {
  14129. source._geometry.applyToMesh(this);
  14130. }
  14131. // Deep copy
  14132. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14133. // Material
  14134. this.material = source.material;
  14135. if (!doNotCloneChildren) {
  14136. // Children
  14137. for (var index = 0; index < scene.meshes.length; index++) {
  14138. var mesh = scene.meshes[index];
  14139. if (mesh.parent === source) {
  14140. // doNotCloneChildren is always going to be False
  14141. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14142. }
  14143. }
  14144. }
  14145. // Particles
  14146. for (index = 0; index < scene.particleSystems.length; index++) {
  14147. var system = scene.particleSystems[index];
  14148. if (system.emitter === source) {
  14149. system.clone(system.name, this);
  14150. }
  14151. }
  14152. this.computeWorldMatrix(true);
  14153. }
  14154. // Parent
  14155. if (parent !== null) {
  14156. this.parent = parent;
  14157. }
  14158. }
  14159. Object.defineProperty(Mesh, "FRONTSIDE", {
  14160. get: function () {
  14161. return Mesh._FRONTSIDE;
  14162. },
  14163. enumerable: true,
  14164. configurable: true
  14165. });
  14166. Object.defineProperty(Mesh, "BACKSIDE", {
  14167. get: function () {
  14168. return Mesh._BACKSIDE;
  14169. },
  14170. enumerable: true,
  14171. configurable: true
  14172. });
  14173. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14174. get: function () {
  14175. return Mesh._DOUBLESIDE;
  14176. },
  14177. enumerable: true,
  14178. configurable: true
  14179. });
  14180. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14181. get: function () {
  14182. return Mesh._DEFAULTSIDE;
  14183. },
  14184. enumerable: true,
  14185. configurable: true
  14186. });
  14187. Object.defineProperty(Mesh, "NO_CAP", {
  14188. get: function () {
  14189. return Mesh._NO_CAP;
  14190. },
  14191. enumerable: true,
  14192. configurable: true
  14193. });
  14194. Object.defineProperty(Mesh, "CAP_START", {
  14195. get: function () {
  14196. return Mesh._CAP_START;
  14197. },
  14198. enumerable: true,
  14199. configurable: true
  14200. });
  14201. Object.defineProperty(Mesh, "CAP_END", {
  14202. get: function () {
  14203. return Mesh._CAP_END;
  14204. },
  14205. enumerable: true,
  14206. configurable: true
  14207. });
  14208. Object.defineProperty(Mesh, "CAP_ALL", {
  14209. get: function () {
  14210. return Mesh._CAP_ALL;
  14211. },
  14212. enumerable: true,
  14213. configurable: true
  14214. });
  14215. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14216. // Methods
  14217. get: function () {
  14218. return this._LODLevels.length > 0;
  14219. },
  14220. enumerable: true,
  14221. configurable: true
  14222. });
  14223. Mesh.prototype._sortLODLevels = function () {
  14224. this._LODLevels.sort(function (a, b) {
  14225. if (a.distance < b.distance) {
  14226. return 1;
  14227. }
  14228. if (a.distance > b.distance) {
  14229. return -1;
  14230. }
  14231. return 0;
  14232. });
  14233. };
  14234. /**
  14235. * Add a mesh as LOD level triggered at the given distance.
  14236. * @param {number} distance - the distance from the center of the object to show this level
  14237. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14238. * @return {BABYLON.Mesh} this mesh (for chaining)
  14239. */
  14240. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14241. if (mesh && mesh._masterMesh) {
  14242. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14243. return this;
  14244. }
  14245. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14246. this._LODLevels.push(level);
  14247. if (mesh) {
  14248. mesh._masterMesh = this;
  14249. }
  14250. this._sortLODLevels();
  14251. return this;
  14252. };
  14253. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14254. for (var index = 0; index < this._LODLevels.length; index++) {
  14255. var level = this._LODLevels[index];
  14256. if (level.distance === distance) {
  14257. return level.mesh;
  14258. }
  14259. }
  14260. return null;
  14261. };
  14262. /**
  14263. * Remove a mesh from the LOD array
  14264. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14265. * @return {BABYLON.Mesh} this mesh (for chaining)
  14266. */
  14267. Mesh.prototype.removeLODLevel = function (mesh) {
  14268. for (var index = 0; index < this._LODLevels.length; index++) {
  14269. if (this._LODLevels[index].mesh === mesh) {
  14270. this._LODLevels.splice(index, 1);
  14271. if (mesh) {
  14272. mesh._masterMesh = null;
  14273. }
  14274. }
  14275. }
  14276. this._sortLODLevels();
  14277. return this;
  14278. };
  14279. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14280. if (!this._LODLevels || this._LODLevels.length === 0) {
  14281. return this;
  14282. }
  14283. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14284. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14285. if (this.onLODLevelSelection) {
  14286. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14287. }
  14288. return this;
  14289. }
  14290. for (var index = 0; index < this._LODLevels.length; index++) {
  14291. var level = this._LODLevels[index];
  14292. if (level.distance < distanceToCamera) {
  14293. if (level.mesh) {
  14294. level.mesh._preActivate();
  14295. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14296. }
  14297. if (this.onLODLevelSelection) {
  14298. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14299. }
  14300. return level.mesh;
  14301. }
  14302. }
  14303. if (this.onLODLevelSelection) {
  14304. this.onLODLevelSelection(distanceToCamera, this, this);
  14305. }
  14306. return this;
  14307. };
  14308. Object.defineProperty(Mesh.prototype, "geometry", {
  14309. get: function () {
  14310. return this._geometry;
  14311. },
  14312. enumerable: true,
  14313. configurable: true
  14314. });
  14315. Mesh.prototype.getTotalVertices = function () {
  14316. if (!this._geometry) {
  14317. return 0;
  14318. }
  14319. return this._geometry.getTotalVertices();
  14320. };
  14321. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14322. if (!this._geometry) {
  14323. return null;
  14324. }
  14325. return this._geometry.getVerticesData(kind, copyWhenShared);
  14326. };
  14327. Mesh.prototype.getVertexBuffer = function (kind) {
  14328. if (!this._geometry) {
  14329. return undefined;
  14330. }
  14331. return this._geometry.getVertexBuffer(kind);
  14332. };
  14333. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14334. if (!this._geometry) {
  14335. if (this._delayInfo) {
  14336. return this._delayInfo.indexOf(kind) !== -1;
  14337. }
  14338. return false;
  14339. }
  14340. return this._geometry.isVerticesDataPresent(kind);
  14341. };
  14342. Mesh.prototype.getVerticesDataKinds = function () {
  14343. if (!this._geometry) {
  14344. var result = [];
  14345. if (this._delayInfo) {
  14346. for (var kind in this._delayInfo) {
  14347. result.push(kind);
  14348. }
  14349. }
  14350. return result;
  14351. }
  14352. return this._geometry.getVerticesDataKinds();
  14353. };
  14354. Mesh.prototype.getTotalIndices = function () {
  14355. if (!this._geometry) {
  14356. return 0;
  14357. }
  14358. return this._geometry.getTotalIndices();
  14359. };
  14360. Mesh.prototype.getIndices = function (copyWhenShared) {
  14361. if (!this._geometry) {
  14362. return [];
  14363. }
  14364. return this._geometry.getIndices(copyWhenShared);
  14365. };
  14366. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14367. get: function () {
  14368. return this._masterMesh !== null && this._masterMesh !== undefined;
  14369. },
  14370. enumerable: true,
  14371. configurable: true
  14372. });
  14373. Mesh.prototype.isReady = function () {
  14374. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14375. return false;
  14376. }
  14377. return _super.prototype.isReady.call(this);
  14378. };
  14379. Mesh.prototype.isDisposed = function () {
  14380. return this._isDisposed;
  14381. };
  14382. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14383. get: function () {
  14384. return this._sideOrientation;
  14385. },
  14386. set: function (sideO) {
  14387. this._sideOrientation = sideO;
  14388. },
  14389. enumerable: true,
  14390. configurable: true
  14391. });
  14392. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14393. get: function () {
  14394. return this._areNormalsFrozen;
  14395. },
  14396. enumerable: true,
  14397. configurable: true
  14398. });
  14399. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14400. Mesh.prototype.freezeNormals = function () {
  14401. this._areNormalsFrozen = true;
  14402. };
  14403. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14404. Mesh.prototype.unfreezeNormals = function () {
  14405. this._areNormalsFrozen = false;
  14406. };
  14407. // Methods
  14408. Mesh.prototype._preActivate = function () {
  14409. var sceneRenderId = this.getScene().getRenderId();
  14410. if (this._preActivateId === sceneRenderId) {
  14411. return;
  14412. }
  14413. this._preActivateId = sceneRenderId;
  14414. this._visibleInstances = null;
  14415. };
  14416. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14417. if (!this._visibleInstances) {
  14418. this._visibleInstances = {};
  14419. this._visibleInstances.defaultRenderId = renderId;
  14420. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14421. }
  14422. if (!this._visibleInstances[renderId]) {
  14423. this._visibleInstances[renderId] = new Array();
  14424. }
  14425. this._visibleInstances[renderId].push(instance);
  14426. };
  14427. Mesh.prototype.refreshBoundingInfo = function () {
  14428. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14429. if (data) {
  14430. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14431. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14432. }
  14433. if (this.subMeshes) {
  14434. for (var index = 0; index < this.subMeshes.length; index++) {
  14435. this.subMeshes[index].refreshBoundingInfo();
  14436. }
  14437. }
  14438. this._updateBoundingInfo();
  14439. };
  14440. Mesh.prototype._createGlobalSubMesh = function () {
  14441. var totalVertices = this.getTotalVertices();
  14442. if (!totalVertices || !this.getIndices()) {
  14443. return null;
  14444. }
  14445. this.releaseSubMeshes();
  14446. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14447. };
  14448. Mesh.prototype.subdivide = function (count) {
  14449. if (count < 1) {
  14450. return;
  14451. }
  14452. var totalIndices = this.getTotalIndices();
  14453. var subdivisionSize = (totalIndices / count) | 0;
  14454. var offset = 0;
  14455. // Ensure that subdivisionSize is a multiple of 3
  14456. while (subdivisionSize % 3 !== 0) {
  14457. subdivisionSize++;
  14458. }
  14459. this.releaseSubMeshes();
  14460. for (var index = 0; index < count; index++) {
  14461. if (offset >= totalIndices) {
  14462. break;
  14463. }
  14464. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14465. offset += subdivisionSize;
  14466. }
  14467. this.synchronizeInstances();
  14468. };
  14469. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14470. if (kind instanceof Array) {
  14471. var temp = data;
  14472. data = kind;
  14473. kind = temp;
  14474. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14475. }
  14476. if (!this._geometry) {
  14477. var vertexData = new BABYLON.VertexData();
  14478. vertexData.set(data, kind);
  14479. var scene = this.getScene();
  14480. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14481. }
  14482. else {
  14483. this._geometry.setVerticesData(kind, data, updatable, stride);
  14484. }
  14485. };
  14486. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14487. if (!this._geometry) {
  14488. return;
  14489. }
  14490. if (!makeItUnique) {
  14491. this._geometry.updateVerticesData(kind, data, updateExtends);
  14492. }
  14493. else {
  14494. this.makeGeometryUnique();
  14495. this.updateVerticesData(kind, data, updateExtends, false);
  14496. }
  14497. };
  14498. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14499. if (!this._geometry) {
  14500. return;
  14501. }
  14502. if (!makeItUnique) {
  14503. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14504. }
  14505. else {
  14506. this.makeGeometryUnique();
  14507. this.updateVerticesDataDirectly(kind, data, offset, false);
  14508. }
  14509. };
  14510. // Mesh positions update function :
  14511. // updates the mesh positions according to the positionFunction returned values.
  14512. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14513. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14514. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14515. if (computeNormals === void 0) { computeNormals = true; }
  14516. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14517. positionFunction(positions);
  14518. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14519. if (computeNormals) {
  14520. var indices = this.getIndices();
  14521. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14522. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14523. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14524. }
  14525. };
  14526. Mesh.prototype.makeGeometryUnique = function () {
  14527. if (!this._geometry) {
  14528. return;
  14529. }
  14530. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14531. geometry.applyToMesh(this);
  14532. };
  14533. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14534. if (!this._geometry) {
  14535. var vertexData = new BABYLON.VertexData();
  14536. vertexData.indices = indices;
  14537. var scene = this.getScene();
  14538. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14539. }
  14540. else {
  14541. this._geometry.setIndices(indices, totalVertices);
  14542. }
  14543. };
  14544. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14545. var engine = this.getScene().getEngine();
  14546. // Wireframe
  14547. var indexToBind;
  14548. switch (fillMode) {
  14549. case BABYLON.Material.PointFillMode:
  14550. indexToBind = null;
  14551. break;
  14552. case BABYLON.Material.WireFrameFillMode:
  14553. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14554. break;
  14555. default:
  14556. case BABYLON.Material.TriangleFillMode:
  14557. indexToBind = this._geometry.getIndexBuffer();
  14558. break;
  14559. }
  14560. // VBOs
  14561. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14562. };
  14563. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14564. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14565. return;
  14566. }
  14567. var engine = this.getScene().getEngine();
  14568. // Draw order
  14569. switch (fillMode) {
  14570. case BABYLON.Material.PointFillMode:
  14571. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14572. break;
  14573. case BABYLON.Material.WireFrameFillMode:
  14574. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14575. break;
  14576. default:
  14577. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14578. }
  14579. };
  14580. Mesh.prototype.registerBeforeRender = function (func) {
  14581. this._onBeforeRenderCallbacks.push(func);
  14582. };
  14583. Mesh.prototype.unregisterBeforeRender = function (func) {
  14584. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14585. if (index > -1) {
  14586. this._onBeforeRenderCallbacks.splice(index, 1);
  14587. }
  14588. };
  14589. Mesh.prototype.registerAfterRender = function (func) {
  14590. this._onAfterRenderCallbacks.push(func);
  14591. };
  14592. Mesh.prototype.unregisterAfterRender = function (func) {
  14593. var index = this._onAfterRenderCallbacks.indexOf(func);
  14594. if (index > -1) {
  14595. this._onAfterRenderCallbacks.splice(index, 1);
  14596. }
  14597. };
  14598. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14599. var scene = this.getScene();
  14600. this._batchCache.mustReturn = false;
  14601. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14602. this._batchCache.visibleInstances[subMeshId] = null;
  14603. if (this._visibleInstances) {
  14604. var currentRenderId = scene.getRenderId();
  14605. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14606. var selfRenderId = this._renderId;
  14607. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14608. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14609. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14610. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14611. }
  14612. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14613. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14614. this._batchCache.mustReturn = true;
  14615. return this._batchCache;
  14616. }
  14617. if (currentRenderId !== selfRenderId) {
  14618. this._batchCache.renderSelf[subMeshId] = false;
  14619. }
  14620. }
  14621. this._renderIdForInstances[subMeshId] = currentRenderId;
  14622. }
  14623. return this._batchCache;
  14624. };
  14625. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14626. var visibleInstances = batch.visibleInstances[subMesh._id];
  14627. var matricesCount = visibleInstances.length + 1;
  14628. var bufferSize = matricesCount * 16 * 4;
  14629. while (this._instancesBufferSize < bufferSize) {
  14630. this._instancesBufferSize *= 2;
  14631. }
  14632. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14633. if (this._worldMatricesInstancesBuffer) {
  14634. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14635. }
  14636. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14637. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14638. }
  14639. var offset = 0;
  14640. var instancesCount = 0;
  14641. var world = this.getWorldMatrix();
  14642. if (batch.renderSelf[subMesh._id]) {
  14643. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14644. offset += 16;
  14645. instancesCount++;
  14646. }
  14647. if (visibleInstances) {
  14648. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14649. var instance = visibleInstances[instanceIndex];
  14650. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14651. offset += 16;
  14652. instancesCount++;
  14653. }
  14654. }
  14655. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14656. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14657. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14658. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14659. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14660. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14661. this._draw(subMesh, fillMode, instancesCount);
  14662. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14663. };
  14664. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14665. var scene = this.getScene();
  14666. var engine = scene.getEngine();
  14667. if (hardwareInstancedRendering) {
  14668. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14669. }
  14670. else {
  14671. if (batch.renderSelf[subMesh._id]) {
  14672. // Draw
  14673. if (onBeforeDraw) {
  14674. onBeforeDraw(false, this.getWorldMatrix());
  14675. }
  14676. this._draw(subMesh, fillMode);
  14677. }
  14678. if (batch.visibleInstances[subMesh._id]) {
  14679. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14680. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14681. // World
  14682. var world = instance.getWorldMatrix();
  14683. if (onBeforeDraw) {
  14684. onBeforeDraw(true, world);
  14685. }
  14686. // Draw
  14687. this._draw(subMesh, fillMode);
  14688. }
  14689. }
  14690. }
  14691. };
  14692. Mesh.prototype.render = function (subMesh) {
  14693. var scene = this.getScene();
  14694. // Managing instances
  14695. var batch = this._getInstancesRenderList(subMesh._id);
  14696. if (batch.mustReturn) {
  14697. return;
  14698. }
  14699. // Checking geometry state
  14700. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14701. return;
  14702. }
  14703. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14704. this._onBeforeRenderCallbacks[callbackIndex](this);
  14705. }
  14706. var engine = scene.getEngine();
  14707. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14708. // Material
  14709. var effectiveMaterial = subMesh.getMaterial();
  14710. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14711. return;
  14712. }
  14713. // Outline - step 1
  14714. var savedDepthWrite = engine.getDepthWrite();
  14715. if (this.renderOutline) {
  14716. engine.setDepthWrite(false);
  14717. scene.getOutlineRenderer().render(subMesh, batch);
  14718. engine.setDepthWrite(savedDepthWrite);
  14719. }
  14720. effectiveMaterial._preBind();
  14721. var effect = effectiveMaterial.getEffect();
  14722. // Bind
  14723. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14724. this._bind(subMesh, effect, fillMode);
  14725. var world = this.getWorldMatrix();
  14726. effectiveMaterial.bind(world, this);
  14727. // Draw
  14728. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14729. if (isInstance) {
  14730. effectiveMaterial.bindOnlyWorldMatrix(world);
  14731. }
  14732. });
  14733. // Unbind
  14734. effectiveMaterial.unbind();
  14735. // Outline - step 2
  14736. if (this.renderOutline && savedDepthWrite) {
  14737. engine.setDepthWrite(true);
  14738. engine.setColorWrite(false);
  14739. scene.getOutlineRenderer().render(subMesh, batch);
  14740. engine.setColorWrite(true);
  14741. }
  14742. // Overlay
  14743. if (this.renderOverlay) {
  14744. var currentMode = engine.getAlphaMode();
  14745. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14746. scene.getOutlineRenderer().render(subMesh, batch, true);
  14747. engine.setAlphaMode(currentMode);
  14748. }
  14749. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14750. this._onAfterRenderCallbacks[callbackIndex](this);
  14751. }
  14752. };
  14753. Mesh.prototype.getEmittedParticleSystems = function () {
  14754. var results = new Array();
  14755. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14756. var particleSystem = this.getScene().particleSystems[index];
  14757. if (particleSystem.emitter === this) {
  14758. results.push(particleSystem);
  14759. }
  14760. }
  14761. return results;
  14762. };
  14763. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14764. var results = new Array();
  14765. var descendants = this.getDescendants();
  14766. descendants.push(this);
  14767. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14768. var particleSystem = this.getScene().particleSystems[index];
  14769. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14770. results.push(particleSystem);
  14771. }
  14772. }
  14773. return results;
  14774. };
  14775. Mesh.prototype.getChildren = function () {
  14776. var results = [];
  14777. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14778. var mesh = this.getScene().meshes[index];
  14779. if (mesh.parent === this) {
  14780. results.push(mesh);
  14781. }
  14782. }
  14783. return results;
  14784. };
  14785. Mesh.prototype._checkDelayState = function () {
  14786. var _this = this;
  14787. var that = this;
  14788. var scene = this.getScene();
  14789. if (this._geometry) {
  14790. this._geometry.load(scene);
  14791. }
  14792. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14793. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14794. scene._addPendingData(that);
  14795. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14796. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14797. if (data instanceof ArrayBuffer) {
  14798. _this._delayLoadingFunction(data, _this);
  14799. }
  14800. else {
  14801. _this._delayLoadingFunction(JSON.parse(data), _this);
  14802. }
  14803. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14804. scene._removePendingData(_this);
  14805. }, function () { }, scene.database, getBinaryData);
  14806. }
  14807. };
  14808. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14809. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14810. return false;
  14811. }
  14812. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14813. return false;
  14814. }
  14815. this._checkDelayState();
  14816. return true;
  14817. };
  14818. Mesh.prototype.setMaterialByID = function (id) {
  14819. var materials = this.getScene().materials;
  14820. for (var index = 0; index < materials.length; index++) {
  14821. if (materials[index].id === id) {
  14822. this.material = materials[index];
  14823. return;
  14824. }
  14825. }
  14826. // Multi
  14827. var multiMaterials = this.getScene().multiMaterials;
  14828. for (index = 0; index < multiMaterials.length; index++) {
  14829. if (multiMaterials[index].id === id) {
  14830. this.material = multiMaterials[index];
  14831. return;
  14832. }
  14833. }
  14834. };
  14835. Mesh.prototype.getAnimatables = function () {
  14836. var results = [];
  14837. if (this.material) {
  14838. results.push(this.material);
  14839. }
  14840. if (this.skeleton) {
  14841. results.push(this.skeleton);
  14842. }
  14843. return results;
  14844. };
  14845. // Geometry
  14846. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14847. // Position
  14848. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14849. return;
  14850. }
  14851. this._resetPointsArrayCache();
  14852. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14853. var temp = [];
  14854. for (var index = 0; index < data.length; index += 3) {
  14855. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14856. }
  14857. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14858. // Normals
  14859. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14860. return;
  14861. }
  14862. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14863. temp = [];
  14864. for (index = 0; index < data.length; index += 3) {
  14865. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14866. }
  14867. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14868. };
  14869. // Cache
  14870. Mesh.prototype._resetPointsArrayCache = function () {
  14871. this._positions = null;
  14872. };
  14873. Mesh.prototype._generatePointsArray = function () {
  14874. if (this._positions)
  14875. return true;
  14876. this._positions = [];
  14877. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14878. if (!data) {
  14879. return false;
  14880. }
  14881. for (var index = 0; index < data.length; index += 3) {
  14882. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14883. }
  14884. return true;
  14885. };
  14886. // Clone
  14887. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14888. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14889. };
  14890. // Dispose
  14891. Mesh.prototype.dispose = function (doNotRecurse) {
  14892. if (this._geometry) {
  14893. this._geometry.releaseForMesh(this, true);
  14894. }
  14895. // Instances
  14896. if (this._worldMatricesInstancesBuffer) {
  14897. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14898. this._worldMatricesInstancesBuffer = null;
  14899. }
  14900. while (this.instances.length) {
  14901. this.instances[0].dispose();
  14902. }
  14903. _super.prototype.dispose.call(this, doNotRecurse);
  14904. };
  14905. // Geometric tools
  14906. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14907. var _this = this;
  14908. var scene = this.getScene();
  14909. var onload = function (img) {
  14910. // Getting height map data
  14911. var canvas = document.createElement("canvas");
  14912. var context = canvas.getContext("2d");
  14913. var heightMapWidth = img.width;
  14914. var heightMapHeight = img.height;
  14915. canvas.width = heightMapWidth;
  14916. canvas.height = heightMapHeight;
  14917. context.drawImage(img, 0, 0);
  14918. // Create VertexData from map data
  14919. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14920. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14921. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14922. //execute success callback, if set
  14923. if (onSuccess) {
  14924. onSuccess(_this);
  14925. }
  14926. };
  14927. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14928. };
  14929. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14930. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14931. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14932. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14933. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14934. return;
  14935. }
  14936. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14937. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14938. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14939. var position = BABYLON.Vector3.Zero();
  14940. var normal = BABYLON.Vector3.Zero();
  14941. var uv = BABYLON.Vector2.Zero();
  14942. for (var index = 0; index < positions.length; index += 3) {
  14943. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14944. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14945. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14946. // Compute height
  14947. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14948. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14949. var pos = (u + v * heightMapWidth) * 4;
  14950. var r = buffer[pos] / 255.0;
  14951. var g = buffer[pos + 1] / 255.0;
  14952. var b = buffer[pos + 2] / 255.0;
  14953. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14954. normal.normalize();
  14955. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14956. position = position.add(normal);
  14957. position.toArray(positions, index);
  14958. }
  14959. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14960. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14961. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14962. };
  14963. Mesh.prototype.convertToFlatShadedMesh = function () {
  14964. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14965. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14966. var kinds = this.getVerticesDataKinds();
  14967. var vbs = [];
  14968. var data = [];
  14969. var newdata = [];
  14970. var updatableNormals = false;
  14971. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14972. var kind = kinds[kindIndex];
  14973. var vertexBuffer = this.getVertexBuffer(kind);
  14974. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14975. updatableNormals = vertexBuffer.isUpdatable();
  14976. kinds.splice(kindIndex, 1);
  14977. kindIndex--;
  14978. continue;
  14979. }
  14980. vbs[kind] = vertexBuffer;
  14981. data[kind] = vbs[kind].getData();
  14982. newdata[kind] = [];
  14983. }
  14984. // Save previous submeshes
  14985. var previousSubmeshes = this.subMeshes.slice(0);
  14986. var indices = this.getIndices();
  14987. var totalIndices = this.getTotalIndices();
  14988. // Generating unique vertices per face
  14989. for (var index = 0; index < totalIndices; index++) {
  14990. var vertexIndex = indices[index];
  14991. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14992. kind = kinds[kindIndex];
  14993. var stride = vbs[kind].getStrideSize();
  14994. for (var offset = 0; offset < stride; offset++) {
  14995. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14996. }
  14997. }
  14998. }
  14999. // Updating faces & normal
  15000. var normals = [];
  15001. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15002. for (index = 0; index < totalIndices; index += 3) {
  15003. indices[index] = index;
  15004. indices[index + 1] = index + 1;
  15005. indices[index + 2] = index + 2;
  15006. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15007. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15008. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15009. var p1p2 = p1.subtract(p2);
  15010. var p3p2 = p3.subtract(p2);
  15011. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15012. // Store same normals for every vertex
  15013. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15014. normals.push(normal.x);
  15015. normals.push(normal.y);
  15016. normals.push(normal.z);
  15017. }
  15018. }
  15019. this.setIndices(indices);
  15020. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15021. // Updating vertex buffers
  15022. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15023. kind = kinds[kindIndex];
  15024. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15025. }
  15026. // Updating submeshes
  15027. this.releaseSubMeshes();
  15028. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15029. var previousOne = previousSubmeshes[submeshIndex];
  15030. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15031. }
  15032. this.synchronizeInstances();
  15033. };
  15034. // Instances
  15035. Mesh.prototype.createInstance = function (name) {
  15036. return new BABYLON.InstancedMesh(name, this);
  15037. };
  15038. Mesh.prototype.synchronizeInstances = function () {
  15039. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15040. var instance = this.instances[instanceIndex];
  15041. instance._syncSubMeshes();
  15042. }
  15043. };
  15044. /**
  15045. * Simplify the mesh according to the given array of settings.
  15046. * Function will return immediately and will simplify async.
  15047. * @param settings a collection of simplification settings.
  15048. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15049. * @param type the type of simplification to run.
  15050. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15051. */
  15052. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15053. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15054. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15055. this.getScene().simplificationQueue.addTask({
  15056. settings: settings,
  15057. parallelProcessing: parallelProcessing,
  15058. mesh: this,
  15059. simplificationType: simplificationType,
  15060. successCallback: successCallback
  15061. });
  15062. };
  15063. /**
  15064. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15065. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15066. * This should be used together with the simplification to avoid disappearing triangles.
  15067. * @param successCallback an optional success callback to be called after the optimization finished.
  15068. */
  15069. Mesh.prototype.optimizeIndices = function (successCallback) {
  15070. var _this = this;
  15071. var indices = this.getIndices();
  15072. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15073. var vectorPositions = [];
  15074. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15075. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15076. }
  15077. var dupes = [];
  15078. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15079. var realPos = vectorPositions.length - 1 - iteration;
  15080. var testedPosition = vectorPositions[realPos];
  15081. for (var j = 0; j < realPos; ++j) {
  15082. var againstPosition = vectorPositions[j];
  15083. if (testedPosition.equals(againstPosition)) {
  15084. dupes[realPos] = j;
  15085. break;
  15086. }
  15087. }
  15088. }, function () {
  15089. for (var i = 0; i < indices.length; ++i) {
  15090. indices[i] = dupes[indices[i]] || indices[i];
  15091. }
  15092. //indices are now reordered
  15093. var originalSubMeshes = _this.subMeshes.slice(0);
  15094. _this.setIndices(indices);
  15095. _this.subMeshes = originalSubMeshes;
  15096. if (successCallback) {
  15097. successCallback(_this);
  15098. }
  15099. });
  15100. };
  15101. // Statics
  15102. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15103. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15104. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15105. if (ribbonInstance) {
  15106. // positionFunction : ribbon case
  15107. // only pathArray and sideOrientation parameters are taken into account for positions update
  15108. var positionFunction = function (positions) {
  15109. var minlg = pathArray[0].length;
  15110. var i = 0;
  15111. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15112. for (var si = 1; si <= ns; si++) {
  15113. for (var p = 0; p < pathArray.length; p++) {
  15114. var path = pathArray[p];
  15115. var l = path.length;
  15116. minlg = (minlg < l) ? minlg : l;
  15117. var j = 0;
  15118. while (j < minlg) {
  15119. positions[i] = path[j].x;
  15120. positions[i + 1] = path[j].y;
  15121. positions[i + 2] = path[j].z;
  15122. j++;
  15123. i += 3;
  15124. }
  15125. }
  15126. }
  15127. };
  15128. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  15129. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  15130. return ribbonInstance;
  15131. }
  15132. else {
  15133. var ribbon = new Mesh(name, scene);
  15134. ribbon.sideOrientation = sideOrientation;
  15135. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15136. vertexData.applyToMesh(ribbon, updatable);
  15137. return ribbon;
  15138. }
  15139. };
  15140. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15141. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15142. var disc = new Mesh(name, scene);
  15143. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15144. vertexData.applyToMesh(disc, updatable);
  15145. return disc;
  15146. };
  15147. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15148. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15149. var box = new Mesh(name, scene);
  15150. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15151. vertexData.applyToMesh(box, updatable);
  15152. return box;
  15153. };
  15154. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15155. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15156. var sphere = new Mesh(name, scene);
  15157. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15158. vertexData.applyToMesh(sphere, updatable);
  15159. return sphere;
  15160. };
  15161. // Cylinder and cone (Code inspired by SharpDX.org)
  15162. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15163. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15164. // subdivisions is a new parameter, we need to support old signature
  15165. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15166. if (scene !== undefined) {
  15167. updatable = scene;
  15168. }
  15169. scene = subdivisions;
  15170. subdivisions = 1;
  15171. }
  15172. var cylinder = new Mesh(name, scene);
  15173. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  15174. vertexData.applyToMesh(cylinder, updatable);
  15175. return cylinder;
  15176. };
  15177. // Torus (Code from SharpDX.org)
  15178. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15179. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15180. var torus = new Mesh(name, scene);
  15181. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15182. vertexData.applyToMesh(torus, updatable);
  15183. return torus;
  15184. };
  15185. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15186. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15187. var torusKnot = new Mesh(name, scene);
  15188. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15189. vertexData.applyToMesh(torusKnot, updatable);
  15190. return torusKnot;
  15191. };
  15192. // Lines
  15193. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15194. if (linesInstance === void 0) { linesInstance = null; }
  15195. if (linesInstance) {
  15196. var positionFunction = function (positions) {
  15197. var i = 0;
  15198. for (var p = 0; p < points.length; p++) {
  15199. positions[i] = points[p].x;
  15200. positions[i + 1] = points[p].y;
  15201. positions[i + 2] = points[p].z;
  15202. i += 3;
  15203. }
  15204. };
  15205. linesInstance.updateMeshPositions(positionFunction, false);
  15206. return linesInstance;
  15207. }
  15208. // lines creation
  15209. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15210. var vertexData = BABYLON.VertexData.CreateLines(points);
  15211. vertexData.applyToMesh(lines, updatable);
  15212. return lines;
  15213. };
  15214. // Dashed Lines
  15215. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15216. if (linesInstance === void 0) { linesInstance = null; }
  15217. if (linesInstance) {
  15218. var positionFunction = function (positions) {
  15219. var curvect = BABYLON.Vector3.Zero();
  15220. var nbSeg = positions.length / 6;
  15221. var lg = 0;
  15222. var nb = 0;
  15223. var shft = 0;
  15224. var dashshft = 0;
  15225. var curshft = 0;
  15226. var p = 0;
  15227. var i = 0;
  15228. var j = 0;
  15229. for (i = 0; i < points.length - 1; i++) {
  15230. points[i + 1].subtractToRef(points[i], curvect);
  15231. lg += curvect.length();
  15232. }
  15233. shft = lg / nbSeg;
  15234. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15235. for (i = 0; i < points.length - 1; i++) {
  15236. points[i + 1].subtractToRef(points[i], curvect);
  15237. nb = Math.floor(curvect.length() / shft);
  15238. curvect.normalize();
  15239. j = 0;
  15240. while (j < nb && p < positions.length) {
  15241. curshft = shft * j;
  15242. positions[p] = points[i].x + curshft * curvect.x;
  15243. positions[p + 1] = points[i].y + curshft * curvect.y;
  15244. positions[p + 2] = points[i].z + curshft * curvect.z;
  15245. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15246. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15247. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15248. p += 6;
  15249. j++;
  15250. }
  15251. }
  15252. while (p < positions.length) {
  15253. positions[p] = points[i].x;
  15254. positions[p + 1] = points[i].y;
  15255. positions[p + 2] = points[i].z;
  15256. p += 3;
  15257. }
  15258. };
  15259. linesInstance.updateMeshPositions(positionFunction, false);
  15260. return linesInstance;
  15261. }
  15262. // dashed lines creation
  15263. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15264. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15265. vertexData.applyToMesh(dashedLines, updatable);
  15266. dashedLines.dashSize = dashSize;
  15267. dashedLines.gapSize = gapSize;
  15268. return dashedLines;
  15269. };
  15270. // Extrusion
  15271. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15272. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15273. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15274. scale = scale || 1;
  15275. rotation = rotation || 0;
  15276. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15277. return extruded;
  15278. };
  15279. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15280. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15281. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15282. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15283. return extrudedCustom;
  15284. };
  15285. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15286. // extrusion geometry
  15287. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15288. var tangents = path3D.getTangents();
  15289. var normals = path3D.getNormals();
  15290. var binormals = path3D.getBinormals();
  15291. var distances = path3D.getDistances();
  15292. var angle = 0;
  15293. var returnScale = function (i, distance) { return scale; };
  15294. var returnRotation = function (i, distance) { return rotation; };
  15295. var rotate = custom ? rotateFunction : returnRotation;
  15296. var scl = custom ? scaleFunction : returnScale;
  15297. var index = 0;
  15298. for (var i = 0; i < curve.length; i++) {
  15299. var shapePath = new Array();
  15300. var angleStep = rotate(i, distances[i]);
  15301. var scaleRatio = scl(i, distances[i]);
  15302. for (var p = 0; p < shape.length; p++) {
  15303. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15304. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15305. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15306. shapePath.push(rotated);
  15307. }
  15308. shapePaths[index] = shapePath;
  15309. angle += angleStep;
  15310. index++;
  15311. }
  15312. // cap
  15313. var capPath = function (shapePath) {
  15314. var pointCap = Array();
  15315. var barycenter = BABYLON.Vector3.Zero();
  15316. var i;
  15317. for (i = 0; i < shapePath.length; i++) {
  15318. barycenter.addInPlace(shapePath[i]);
  15319. }
  15320. barycenter.scaleInPlace(1 / shapePath.length);
  15321. for (i = 0; i < shapePath.length; i++) {
  15322. pointCap.push(barycenter);
  15323. }
  15324. return pointCap;
  15325. };
  15326. switch (cap) {
  15327. case Mesh.NO_CAP:
  15328. break;
  15329. case Mesh.CAP_START:
  15330. shapePaths.unshift(capPath(shapePaths[0]));
  15331. break;
  15332. case Mesh.CAP_END:
  15333. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15334. break;
  15335. case Mesh.CAP_ALL:
  15336. shapePaths.unshift(capPath(shapePaths[0]));
  15337. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15338. break;
  15339. default:
  15340. break;
  15341. }
  15342. return shapePaths;
  15343. };
  15344. if (instance) {
  15345. var path3D = (instance.path3D).update(curve);
  15346. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15347. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15348. return instance;
  15349. }
  15350. // extruded shape creation
  15351. var path3D = new BABYLON.Path3D(curve);
  15352. var newShapePaths = new Array();
  15353. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15354. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15355. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15356. extrudedGeneric.pathArray = pathArray;
  15357. extrudedGeneric.path3D = path3D;
  15358. extrudedGeneric.cap = cap;
  15359. return extrudedGeneric;
  15360. };
  15361. // Lathe
  15362. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15363. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15364. radius = radius || 1;
  15365. tessellation = tessellation || radius * 60;
  15366. var pi2 = Math.PI * 2;
  15367. var Y = BABYLON.Axis.Y;
  15368. var shapeLathe = new Array();
  15369. // first rotatable point
  15370. var i = 0;
  15371. while (shape[i].x === 0) {
  15372. i++;
  15373. }
  15374. var pt = shape[i];
  15375. for (i = 0; i < shape.length; i++) {
  15376. shapeLathe.push(shape[i].subtract(pt));
  15377. }
  15378. // circle path
  15379. var step = pi2 / tessellation;
  15380. var rotated;
  15381. var path = new Array();
  15382. ;
  15383. for (i = 0; i < tessellation; i++) {
  15384. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15385. path.push(rotated);
  15386. }
  15387. path.push(path[0]);
  15388. // extrusion
  15389. var scaleFunction = function () { return 1; };
  15390. var rotateFunction = function () { return 0; };
  15391. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15392. return lathe;
  15393. };
  15394. // Plane & ground
  15395. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15396. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15397. var plane = new Mesh(name, scene);
  15398. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15399. vertexData.applyToMesh(plane, updatable);
  15400. return plane;
  15401. };
  15402. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15403. var ground = new BABYLON.GroundMesh(name, scene);
  15404. ground._setReady(false);
  15405. ground._subdivisions = subdivisions;
  15406. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15407. vertexData.applyToMesh(ground, updatable);
  15408. ground._setReady(true);
  15409. return ground;
  15410. };
  15411. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15412. var tiledGround = new Mesh(name, scene);
  15413. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15414. vertexData.applyToMesh(tiledGround, updatable);
  15415. return tiledGround;
  15416. };
  15417. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15418. var ground = new BABYLON.GroundMesh(name, scene);
  15419. ground._subdivisions = subdivisions;
  15420. ground._setReady(false);
  15421. var onload = function (img) {
  15422. // Getting height map data
  15423. var canvas = document.createElement("canvas");
  15424. var context = canvas.getContext("2d");
  15425. var heightMapWidth = img.width;
  15426. var heightMapHeight = img.height;
  15427. canvas.width = heightMapWidth;
  15428. canvas.height = heightMapHeight;
  15429. context.drawImage(img, 0, 0);
  15430. // Create VertexData from map data
  15431. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15432. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15433. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15434. vertexData.applyToMesh(ground, updatable);
  15435. ground._setReady(true);
  15436. //execute ready callback, if set
  15437. if (onReady) {
  15438. onReady(ground);
  15439. }
  15440. };
  15441. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15442. return ground;
  15443. };
  15444. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15445. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15446. if (tubeInstance === void 0) { tubeInstance = null; }
  15447. // tube geometry
  15448. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15449. var tangents = path3D.getTangents();
  15450. var normals = path3D.getNormals();
  15451. var distances = path3D.getDistances();
  15452. var pi2 = Math.PI * 2;
  15453. var step = pi2 / tessellation;
  15454. var returnRadius = function (i, distance) { return radius; };
  15455. var radiusFunctionFinal = radiusFunction || returnRadius;
  15456. var circlePath;
  15457. var rad;
  15458. var normal;
  15459. var rotated;
  15460. var rotationMatrix;
  15461. var index = 0;
  15462. for (var i = 0; i < path.length; i++) {
  15463. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15464. circlePath = Array(); // current circle array
  15465. normal = normals[i]; // current normal
  15466. for (var t = 0; t < tessellation; t++) {
  15467. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15468. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15469. circlePath.push(rotated);
  15470. }
  15471. circlePath.push(circlePath[0]);
  15472. circlePaths[index] = circlePath;
  15473. index++;
  15474. }
  15475. // cap
  15476. var capPath = function (nbPoints, pathIndex) {
  15477. var pointCap = Array();
  15478. for (var i = 0; i < nbPoints; i++) {
  15479. pointCap.push(path[pathIndex]);
  15480. }
  15481. return pointCap;
  15482. };
  15483. switch (cap) {
  15484. case Mesh.NO_CAP:
  15485. break;
  15486. case Mesh.CAP_START:
  15487. circlePaths.unshift(capPath(tessellation + 1, 0));
  15488. break;
  15489. case Mesh.CAP_END:
  15490. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15491. break;
  15492. case Mesh.CAP_ALL:
  15493. circlePaths.unshift(capPath(tessellation + 1, 0));
  15494. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15495. break;
  15496. default:
  15497. break;
  15498. }
  15499. return circlePaths;
  15500. };
  15501. if (tubeInstance) {
  15502. var path3D = (tubeInstance.path3D).update(path);
  15503. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15504. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15505. return tubeInstance;
  15506. }
  15507. // tube creation
  15508. var path3D = new BABYLON.Path3D(path);
  15509. var newPathArray = new Array();
  15510. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15511. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15512. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15513. tube.pathArray = pathArray;
  15514. tube.path3D = path3D;
  15515. tube.tessellation = tessellation;
  15516. tube.cap = cap;
  15517. return tube;
  15518. };
  15519. // Decals
  15520. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15521. if (angle === void 0) { angle = 0; }
  15522. var indices = sourceMesh.getIndices();
  15523. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15524. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15525. // Getting correct rotation
  15526. if (!normal) {
  15527. var target = new BABYLON.Vector3(0, 0, 1);
  15528. var camera = sourceMesh.getScene().activeCamera;
  15529. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15530. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15531. }
  15532. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15533. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15534. var pitch = Math.atan2(normal.y, len);
  15535. // Matrix
  15536. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15537. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15538. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15539. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15540. var vertexData = new BABYLON.VertexData();
  15541. vertexData.indices = [];
  15542. vertexData.positions = [];
  15543. vertexData.normals = [];
  15544. vertexData.uvs = [];
  15545. var currentVertexDataIndex = 0;
  15546. var extractDecalVector3 = function (indexId) {
  15547. var vertexId = indices[indexId];
  15548. var result = new BABYLON.PositionNormalVertex();
  15549. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15550. // Send vector to decal local world
  15551. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15552. // Get normal
  15553. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15554. return result;
  15555. };
  15556. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15557. var clip = function (vertices, axis) {
  15558. if (vertices.length === 0) {
  15559. return vertices;
  15560. }
  15561. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15562. var clipVertices = function (v0, v1) {
  15563. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15564. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15565. };
  15566. var result = new Array();
  15567. for (var index = 0; index < vertices.length; index += 3) {
  15568. var v1Out;
  15569. var v2Out;
  15570. var v3Out;
  15571. var total = 0;
  15572. var nV1, nV2, nV3, nV4;
  15573. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15574. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15575. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15576. v1Out = d1 > 0;
  15577. v2Out = d2 > 0;
  15578. v3Out = d3 > 0;
  15579. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15580. switch (total) {
  15581. case 0:
  15582. result.push(vertices[index]);
  15583. result.push(vertices[index + 1]);
  15584. result.push(vertices[index + 2]);
  15585. break;
  15586. case 1:
  15587. if (v1Out) {
  15588. nV1 = vertices[index + 1];
  15589. nV2 = vertices[index + 2];
  15590. nV3 = clipVertices(vertices[index], nV1);
  15591. nV4 = clipVertices(vertices[index], nV2);
  15592. }
  15593. if (v2Out) {
  15594. nV1 = vertices[index];
  15595. nV2 = vertices[index + 2];
  15596. nV3 = clipVertices(vertices[index + 1], nV1);
  15597. nV4 = clipVertices(vertices[index + 1], nV2);
  15598. result.push(nV3);
  15599. result.push(nV2.clone());
  15600. result.push(nV1.clone());
  15601. result.push(nV2.clone());
  15602. result.push(nV3.clone());
  15603. result.push(nV4);
  15604. break;
  15605. }
  15606. if (v3Out) {
  15607. nV1 = vertices[index];
  15608. nV2 = vertices[index + 1];
  15609. nV3 = clipVertices(vertices[index + 2], nV1);
  15610. nV4 = clipVertices(vertices[index + 2], nV2);
  15611. }
  15612. result.push(nV1.clone());
  15613. result.push(nV2.clone());
  15614. result.push(nV3);
  15615. result.push(nV4);
  15616. result.push(nV3.clone());
  15617. result.push(nV2.clone());
  15618. break;
  15619. case 2:
  15620. if (!v1Out) {
  15621. nV1 = vertices[index].clone();
  15622. nV2 = clipVertices(nV1, vertices[index + 1]);
  15623. nV3 = clipVertices(nV1, vertices[index + 2]);
  15624. result.push(nV1);
  15625. result.push(nV2);
  15626. result.push(nV3);
  15627. }
  15628. if (!v2Out) {
  15629. nV1 = vertices[index + 1].clone();
  15630. nV2 = clipVertices(nV1, vertices[index + 2]);
  15631. nV3 = clipVertices(nV1, vertices[index]);
  15632. result.push(nV1);
  15633. result.push(nV2);
  15634. result.push(nV3);
  15635. }
  15636. if (!v3Out) {
  15637. nV1 = vertices[index + 2].clone();
  15638. nV2 = clipVertices(nV1, vertices[index]);
  15639. nV3 = clipVertices(nV1, vertices[index + 1]);
  15640. result.push(nV1);
  15641. result.push(nV2);
  15642. result.push(nV3);
  15643. }
  15644. break;
  15645. case 3:
  15646. break;
  15647. }
  15648. }
  15649. return result;
  15650. };
  15651. for (var index = 0; index < indices.length; index += 3) {
  15652. var faceVertices = new Array();
  15653. faceVertices.push(extractDecalVector3(index));
  15654. faceVertices.push(extractDecalVector3(index + 1));
  15655. faceVertices.push(extractDecalVector3(index + 2));
  15656. // Clip
  15657. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15658. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15659. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15660. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15661. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15662. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15663. if (faceVertices.length === 0) {
  15664. continue;
  15665. }
  15666. // Add UVs and get back to world
  15667. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  15668. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15669. var vertex = faceVertices[vIndex];
  15670. vertexData.indices.push(currentVertexDataIndex);
  15671. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15672. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15673. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15674. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15675. currentVertexDataIndex++;
  15676. }
  15677. }
  15678. // Return mesh
  15679. var decal = new Mesh(name, sourceMesh.getScene());
  15680. vertexData.applyToMesh(decal);
  15681. decal.position = position.clone();
  15682. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15683. return decal;
  15684. };
  15685. // Tools
  15686. Mesh.MinMax = function (meshes) {
  15687. var minVector = null;
  15688. var maxVector = null;
  15689. for (var i in meshes) {
  15690. var mesh = meshes[i];
  15691. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15692. if (!minVector) {
  15693. minVector = boundingBox.minimumWorld;
  15694. maxVector = boundingBox.maximumWorld;
  15695. continue;
  15696. }
  15697. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15698. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15699. }
  15700. return {
  15701. min: minVector,
  15702. max: maxVector
  15703. };
  15704. };
  15705. Mesh.Center = function (meshesOrMinMaxVector) {
  15706. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15707. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15708. };
  15709. /**
  15710. * Merge the array of meshes into a single mesh for performance reasons.
  15711. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15712. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15713. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15714. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15715. */
  15716. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15717. if (disposeSource === void 0) { disposeSource = true; }
  15718. if (!allow32BitsIndices) {
  15719. var totalVertices = 0;
  15720. // Counting vertices
  15721. for (var index = 0; index < meshes.length; index++) {
  15722. if (meshes[index]) {
  15723. totalVertices += meshes[index].getTotalVertices();
  15724. if (totalVertices > 65536) {
  15725. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15726. return null;
  15727. }
  15728. }
  15729. }
  15730. }
  15731. // Merge
  15732. var vertexData;
  15733. var otherVertexData;
  15734. var source;
  15735. for (index = 0; index < meshes.length; index++) {
  15736. if (meshes[index]) {
  15737. meshes[index].computeWorldMatrix(true);
  15738. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15739. otherVertexData.transform(meshes[index].getWorldMatrix());
  15740. if (vertexData) {
  15741. vertexData.merge(otherVertexData);
  15742. }
  15743. else {
  15744. vertexData = otherVertexData;
  15745. source = meshes[index];
  15746. }
  15747. }
  15748. }
  15749. if (!meshSubclass) {
  15750. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15751. }
  15752. vertexData.applyToMesh(meshSubclass);
  15753. // Setting properties
  15754. meshSubclass.material = source.material;
  15755. meshSubclass.checkCollisions = source.checkCollisions;
  15756. // Cleaning
  15757. if (disposeSource) {
  15758. for (index = 0; index < meshes.length; index++) {
  15759. if (meshes[index]) {
  15760. meshes[index].dispose();
  15761. }
  15762. }
  15763. }
  15764. return meshSubclass;
  15765. };
  15766. // Consts
  15767. Mesh._FRONTSIDE = 0;
  15768. Mesh._BACKSIDE = 1;
  15769. Mesh._DOUBLESIDE = 2;
  15770. Mesh._DEFAULTSIDE = 0;
  15771. Mesh._NO_CAP = 0;
  15772. Mesh._CAP_START = 1;
  15773. Mesh._CAP_END = 2;
  15774. Mesh._CAP_ALL = 3;
  15775. return Mesh;
  15776. })(BABYLON.AbstractMesh);
  15777. BABYLON.Mesh = Mesh;
  15778. })(BABYLON || (BABYLON = {}));
  15779. //# sourceMappingURL=babylon.mesh.js.map
  15780. var BABYLON;
  15781. (function (BABYLON) {
  15782. var SubMesh = (function () {
  15783. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15784. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15785. this.materialIndex = materialIndex;
  15786. this.verticesStart = verticesStart;
  15787. this.verticesCount = verticesCount;
  15788. this.indexStart = indexStart;
  15789. this.indexCount = indexCount;
  15790. this._renderId = 0;
  15791. this._mesh = mesh;
  15792. this._renderingMesh = renderingMesh || mesh;
  15793. mesh.subMeshes.push(this);
  15794. this._trianglePlanes = [];
  15795. this._id = mesh.subMeshes.length - 1;
  15796. if (createBoundingBox) {
  15797. this.refreshBoundingInfo();
  15798. mesh.computeWorldMatrix(true);
  15799. }
  15800. }
  15801. SubMesh.prototype.getBoundingInfo = function () {
  15802. return this._boundingInfo;
  15803. };
  15804. SubMesh.prototype.getMesh = function () {
  15805. return this._mesh;
  15806. };
  15807. SubMesh.prototype.getRenderingMesh = function () {
  15808. return this._renderingMesh;
  15809. };
  15810. SubMesh.prototype.getMaterial = function () {
  15811. var rootMaterial = this._renderingMesh.material;
  15812. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15813. var multiMaterial = rootMaterial;
  15814. return multiMaterial.getSubMaterial(this.materialIndex);
  15815. }
  15816. if (!rootMaterial) {
  15817. return this._mesh.getScene().defaultMaterial;
  15818. }
  15819. return rootMaterial;
  15820. };
  15821. // Methods
  15822. SubMesh.prototype.refreshBoundingInfo = function () {
  15823. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15824. if (!data) {
  15825. this._boundingInfo = this._mesh._boundingInfo;
  15826. return;
  15827. }
  15828. var indices = this._renderingMesh.getIndices();
  15829. var extend;
  15830. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15831. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  15832. }
  15833. else {
  15834. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15835. }
  15836. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15837. };
  15838. SubMesh.prototype._checkCollision = function (collider) {
  15839. return this._boundingInfo._checkCollision(collider);
  15840. };
  15841. SubMesh.prototype.updateBoundingInfo = function (world) {
  15842. if (!this._boundingInfo) {
  15843. this.refreshBoundingInfo();
  15844. }
  15845. this._boundingInfo._update(world);
  15846. };
  15847. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15848. return this._boundingInfo.isInFrustum(frustumPlanes);
  15849. };
  15850. SubMesh.prototype.render = function () {
  15851. this._renderingMesh.render(this);
  15852. };
  15853. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15854. if (!this._linesIndexBuffer) {
  15855. var linesIndices = [];
  15856. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15857. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15858. }
  15859. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15860. this.linesIndexCount = linesIndices.length;
  15861. }
  15862. return this._linesIndexBuffer;
  15863. };
  15864. SubMesh.prototype.canIntersects = function (ray) {
  15865. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15866. };
  15867. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15868. var intersectInfo = null;
  15869. // Triangles test
  15870. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15871. var p0 = positions[indices[index]];
  15872. var p1 = positions[indices[index + 1]];
  15873. var p2 = positions[indices[index + 2]];
  15874. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15875. if (currentIntersectInfo) {
  15876. if (currentIntersectInfo.distance < 0) {
  15877. continue;
  15878. }
  15879. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15880. intersectInfo = currentIntersectInfo;
  15881. intersectInfo.faceId = index / 3;
  15882. if (fastCheck) {
  15883. break;
  15884. }
  15885. }
  15886. }
  15887. }
  15888. return intersectInfo;
  15889. };
  15890. // Clone
  15891. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15892. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15893. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15894. return result;
  15895. };
  15896. // Dispose
  15897. SubMesh.prototype.dispose = function () {
  15898. if (this._linesIndexBuffer) {
  15899. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15900. this._linesIndexBuffer = null;
  15901. }
  15902. // Remove from mesh
  15903. var index = this._mesh.subMeshes.indexOf(this);
  15904. this._mesh.subMeshes.splice(index, 1);
  15905. };
  15906. // Statics
  15907. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15908. var minVertexIndex = Number.MAX_VALUE;
  15909. var maxVertexIndex = -Number.MAX_VALUE;
  15910. renderingMesh = renderingMesh || mesh;
  15911. var indices = renderingMesh.getIndices();
  15912. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15913. var vertexIndex = indices[index];
  15914. if (vertexIndex < minVertexIndex)
  15915. minVertexIndex = vertexIndex;
  15916. if (vertexIndex > maxVertexIndex)
  15917. maxVertexIndex = vertexIndex;
  15918. }
  15919. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15920. };
  15921. return SubMesh;
  15922. })();
  15923. BABYLON.SubMesh = SubMesh;
  15924. })(BABYLON || (BABYLON = {}));
  15925. //# sourceMappingURL=babylon.subMesh.js.map
  15926. var BABYLON;
  15927. (function (BABYLON) {
  15928. var BaseTexture = (function () {
  15929. function BaseTexture(scene) {
  15930. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15931. this.hasAlpha = false;
  15932. this.getAlphaFromRGB = false;
  15933. this.level = 1;
  15934. this.isCube = false;
  15935. this.isRenderTarget = false;
  15936. this.animations = new Array();
  15937. this.coordinatesIndex = 0;
  15938. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15939. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15940. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15941. this.anisotropicFilteringLevel = 4;
  15942. this._scene = scene;
  15943. this._scene.textures.push(this);
  15944. }
  15945. BaseTexture.prototype.getScene = function () {
  15946. return this._scene;
  15947. };
  15948. BaseTexture.prototype.getTextureMatrix = function () {
  15949. return null;
  15950. };
  15951. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15952. return null;
  15953. };
  15954. BaseTexture.prototype.getInternalTexture = function () {
  15955. return this._texture;
  15956. };
  15957. BaseTexture.prototype.isReady = function () {
  15958. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15959. return true;
  15960. }
  15961. if (this._texture) {
  15962. return this._texture.isReady;
  15963. }
  15964. return false;
  15965. };
  15966. BaseTexture.prototype.getSize = function () {
  15967. if (this._texture._width) {
  15968. return { width: this._texture._width, height: this._texture._height };
  15969. }
  15970. if (this._texture._size) {
  15971. return { width: this._texture._size, height: this._texture._size };
  15972. }
  15973. return { width: 0, height: 0 };
  15974. };
  15975. BaseTexture.prototype.getBaseSize = function () {
  15976. if (!this.isReady())
  15977. return { width: 0, height: 0 };
  15978. if (this._texture._size) {
  15979. return { width: this._texture._size, height: this._texture._size };
  15980. }
  15981. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15982. };
  15983. BaseTexture.prototype.scale = function (ratio) {
  15984. };
  15985. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15986. get: function () {
  15987. return false;
  15988. },
  15989. enumerable: true,
  15990. configurable: true
  15991. });
  15992. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  15993. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15994. for (var index = 0; index < texturesCache.length; index++) {
  15995. var texturesCacheEntry = texturesCache[index];
  15996. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15997. texturesCache.splice(index, 1);
  15998. return;
  15999. }
  16000. }
  16001. };
  16002. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16003. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16004. for (var index = 0; index < texturesCache.length; index++) {
  16005. var texturesCacheEntry = texturesCache[index];
  16006. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16007. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16008. texturesCacheEntry.references++;
  16009. return texturesCacheEntry;
  16010. }
  16011. }
  16012. }
  16013. return null;
  16014. };
  16015. BaseTexture.prototype.delayLoad = function () {
  16016. };
  16017. BaseTexture.prototype.releaseInternalTexture = function () {
  16018. if (!this._texture) {
  16019. return;
  16020. }
  16021. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16022. this._texture.references--;
  16023. // Final reference ?
  16024. if (this._texture.references === 0) {
  16025. var index = texturesCache.indexOf(this._texture);
  16026. texturesCache.splice(index, 1);
  16027. this._scene.getEngine()._releaseTexture(this._texture);
  16028. delete this._texture;
  16029. }
  16030. };
  16031. BaseTexture.prototype.clone = function () {
  16032. return null;
  16033. };
  16034. BaseTexture.prototype.dispose = function () {
  16035. // Remove from scene
  16036. var index = this._scene.textures.indexOf(this);
  16037. if (index >= 0) {
  16038. this._scene.textures.splice(index, 1);
  16039. }
  16040. if (this._texture === undefined) {
  16041. return;
  16042. }
  16043. this.releaseInternalTexture();
  16044. // Callback
  16045. if (this.onDispose) {
  16046. this.onDispose();
  16047. }
  16048. };
  16049. return BaseTexture;
  16050. })();
  16051. BABYLON.BaseTexture = BaseTexture;
  16052. })(BABYLON || (BABYLON = {}));
  16053. //# sourceMappingURL=babylon.baseTexture.js.map
  16054. var BABYLON;
  16055. (function (BABYLON) {
  16056. var Texture = (function (_super) {
  16057. __extends(Texture, _super);
  16058. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16059. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16060. if (onLoad === void 0) { onLoad = null; }
  16061. if (onError === void 0) { onError = null; }
  16062. if (buffer === void 0) { buffer = null; }
  16063. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16064. _super.call(this, scene);
  16065. this.uOffset = 0;
  16066. this.vOffset = 0;
  16067. this.uScale = 1.0;
  16068. this.vScale = 1.0;
  16069. this.uAng = 0;
  16070. this.vAng = 0;
  16071. this.wAng = 0;
  16072. this.name = url;
  16073. this.url = url;
  16074. this._noMipmap = noMipmap;
  16075. this._invertY = invertY;
  16076. this._samplingMode = samplingMode;
  16077. this._buffer = buffer;
  16078. this._deleteBuffer = deleteBuffer;
  16079. if (!url) {
  16080. return;
  16081. }
  16082. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16083. if (!this._texture) {
  16084. if (!scene.useDelayedTextureLoading) {
  16085. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16086. if (deleteBuffer) {
  16087. delete this._buffer;
  16088. }
  16089. }
  16090. else {
  16091. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16092. }
  16093. }
  16094. else {
  16095. BABYLON.Tools.SetImmediate(function () {
  16096. if (onLoad) {
  16097. onLoad();
  16098. }
  16099. });
  16100. }
  16101. }
  16102. Texture.prototype.delayLoad = function () {
  16103. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16104. return;
  16105. }
  16106. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16107. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16108. if (!this._texture) {
  16109. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16110. if (this._deleteBuffer) {
  16111. delete this._buffer;
  16112. }
  16113. }
  16114. };
  16115. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16116. if (!this._texture) {
  16117. return;
  16118. }
  16119. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16120. };
  16121. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16122. x -= this.uOffset + 0.5;
  16123. y -= this.vOffset + 0.5;
  16124. z -= 0.5;
  16125. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16126. t.x *= this.uScale;
  16127. t.y *= this.vScale;
  16128. t.x += 0.5;
  16129. t.y += 0.5;
  16130. t.z += 0.5;
  16131. };
  16132. Texture.prototype.getTextureMatrix = function () {
  16133. if (this.uOffset === this._cachedUOffset &&
  16134. this.vOffset === this._cachedVOffset &&
  16135. this.uScale === this._cachedUScale &&
  16136. this.vScale === this._cachedVScale &&
  16137. this.uAng === this._cachedUAng &&
  16138. this.vAng === this._cachedVAng &&
  16139. this.wAng === this._cachedWAng) {
  16140. return this._cachedTextureMatrix;
  16141. }
  16142. this._cachedUOffset = this.uOffset;
  16143. this._cachedVOffset = this.vOffset;
  16144. this._cachedUScale = this.uScale;
  16145. this._cachedVScale = this.vScale;
  16146. this._cachedUAng = this.uAng;
  16147. this._cachedVAng = this.vAng;
  16148. this._cachedWAng = this.wAng;
  16149. if (!this._cachedTextureMatrix) {
  16150. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16151. this._rowGenerationMatrix = new BABYLON.Matrix();
  16152. this._t0 = BABYLON.Vector3.Zero();
  16153. this._t1 = BABYLON.Vector3.Zero();
  16154. this._t2 = BABYLON.Vector3.Zero();
  16155. }
  16156. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16157. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16158. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16159. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16160. this._t1.subtractInPlace(this._t0);
  16161. this._t2.subtractInPlace(this._t0);
  16162. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16163. this._cachedTextureMatrix.m[0] = this._t1.x;
  16164. this._cachedTextureMatrix.m[1] = this._t1.y;
  16165. this._cachedTextureMatrix.m[2] = this._t1.z;
  16166. this._cachedTextureMatrix.m[4] = this._t2.x;
  16167. this._cachedTextureMatrix.m[5] = this._t2.y;
  16168. this._cachedTextureMatrix.m[6] = this._t2.z;
  16169. this._cachedTextureMatrix.m[8] = this._t0.x;
  16170. this._cachedTextureMatrix.m[9] = this._t0.y;
  16171. this._cachedTextureMatrix.m[10] = this._t0.z;
  16172. return this._cachedTextureMatrix;
  16173. };
  16174. Texture.prototype.getReflectionTextureMatrix = function () {
  16175. if (this.uOffset === this._cachedUOffset &&
  16176. this.vOffset === this._cachedVOffset &&
  16177. this.uScale === this._cachedUScale &&
  16178. this.vScale === this._cachedVScale &&
  16179. this.coordinatesMode === this._cachedCoordinatesMode) {
  16180. return this._cachedTextureMatrix;
  16181. }
  16182. if (!this._cachedTextureMatrix) {
  16183. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16184. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16185. }
  16186. this._cachedCoordinatesMode = this.coordinatesMode;
  16187. switch (this.coordinatesMode) {
  16188. case Texture.SPHERICAL_MODE:
  16189. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16190. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16191. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16192. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16193. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16194. break;
  16195. case Texture.PLANAR_MODE:
  16196. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16197. this._cachedTextureMatrix[0] = this.uScale;
  16198. this._cachedTextureMatrix[5] = this.vScale;
  16199. this._cachedTextureMatrix[12] = this.uOffset;
  16200. this._cachedTextureMatrix[13] = this.vOffset;
  16201. break;
  16202. case Texture.PROJECTION_MODE:
  16203. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16204. this._projectionModeMatrix.m[0] = 0.5;
  16205. this._projectionModeMatrix.m[5] = -0.5;
  16206. this._projectionModeMatrix.m[10] = 0.0;
  16207. this._projectionModeMatrix.m[12] = 0.5;
  16208. this._projectionModeMatrix.m[13] = 0.5;
  16209. this._projectionModeMatrix.m[14] = 1.0;
  16210. this._projectionModeMatrix.m[15] = 1.0;
  16211. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16212. break;
  16213. default:
  16214. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16215. break;
  16216. }
  16217. return this._cachedTextureMatrix;
  16218. };
  16219. Texture.prototype.clone = function () {
  16220. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16221. // Base texture
  16222. newTexture.hasAlpha = this.hasAlpha;
  16223. newTexture.level = this.level;
  16224. newTexture.wrapU = this.wrapU;
  16225. newTexture.wrapV = this.wrapV;
  16226. newTexture.coordinatesIndex = this.coordinatesIndex;
  16227. newTexture.coordinatesMode = this.coordinatesMode;
  16228. // Texture
  16229. newTexture.uOffset = this.uOffset;
  16230. newTexture.vOffset = this.vOffset;
  16231. newTexture.uScale = this.uScale;
  16232. newTexture.vScale = this.vScale;
  16233. newTexture.uAng = this.uAng;
  16234. newTexture.vAng = this.vAng;
  16235. newTexture.wAng = this.wAng;
  16236. return newTexture;
  16237. };
  16238. // Statics
  16239. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16240. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16241. if (onLoad === void 0) { onLoad = null; }
  16242. if (onError === void 0) { onError = null; }
  16243. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16244. };
  16245. // Constants
  16246. Texture.NEAREST_SAMPLINGMODE = 1;
  16247. Texture.BILINEAR_SAMPLINGMODE = 2;
  16248. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16249. Texture.EXPLICIT_MODE = 0;
  16250. Texture.SPHERICAL_MODE = 1;
  16251. Texture.PLANAR_MODE = 2;
  16252. Texture.CUBIC_MODE = 3;
  16253. Texture.PROJECTION_MODE = 4;
  16254. Texture.SKYBOX_MODE = 5;
  16255. Texture.CLAMP_ADDRESSMODE = 0;
  16256. Texture.WRAP_ADDRESSMODE = 1;
  16257. Texture.MIRROR_ADDRESSMODE = 2;
  16258. return Texture;
  16259. })(BABYLON.BaseTexture);
  16260. BABYLON.Texture = Texture;
  16261. })(BABYLON || (BABYLON = {}));
  16262. //# sourceMappingURL=babylon.texture.js.map
  16263. var BABYLON;
  16264. (function (BABYLON) {
  16265. var CubeTexture = (function (_super) {
  16266. __extends(CubeTexture, _super);
  16267. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16268. _super.call(this, scene);
  16269. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16270. this.name = rootUrl;
  16271. this.url = rootUrl;
  16272. this._noMipmap = noMipmap;
  16273. this.hasAlpha = false;
  16274. this._texture = this._getFromCache(rootUrl, noMipmap);
  16275. if (!extensions) {
  16276. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16277. }
  16278. this._extensions = extensions;
  16279. if (!this._texture) {
  16280. if (!scene.useDelayedTextureLoading) {
  16281. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16282. }
  16283. else {
  16284. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16285. }
  16286. }
  16287. this.isCube = true;
  16288. this._textureMatrix = BABYLON.Matrix.Identity();
  16289. }
  16290. CubeTexture.prototype.clone = function () {
  16291. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16292. // Base texture
  16293. newTexture.level = this.level;
  16294. newTexture.wrapU = this.wrapU;
  16295. newTexture.wrapV = this.wrapV;
  16296. newTexture.coordinatesIndex = this.coordinatesIndex;
  16297. newTexture.coordinatesMode = this.coordinatesMode;
  16298. return newTexture;
  16299. };
  16300. // Methods
  16301. CubeTexture.prototype.delayLoad = function () {
  16302. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16303. return;
  16304. }
  16305. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16306. this._texture = this._getFromCache(this.url, this._noMipmap);
  16307. if (!this._texture) {
  16308. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16309. }
  16310. };
  16311. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16312. return this._textureMatrix;
  16313. };
  16314. return CubeTexture;
  16315. })(BABYLON.BaseTexture);
  16316. BABYLON.CubeTexture = CubeTexture;
  16317. })(BABYLON || (BABYLON = {}));
  16318. //# sourceMappingURL=babylon.cubeTexture.js.map
  16319. var BABYLON;
  16320. (function (BABYLON) {
  16321. var RenderTargetTexture = (function (_super) {
  16322. __extends(RenderTargetTexture, _super);
  16323. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16324. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16325. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16326. _super.call(this, null, scene, !generateMipMaps);
  16327. this.renderList = new Array();
  16328. this.renderParticles = true;
  16329. this.renderSprites = false;
  16330. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16331. this._currentRefreshId = -1;
  16332. this._refreshRate = 1;
  16333. this.name = name;
  16334. this.isRenderTarget = true;
  16335. this._size = size;
  16336. this._generateMipMaps = generateMipMaps;
  16337. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16338. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16339. // Rendering groups
  16340. this._renderingManager = new BABYLON.RenderingManager(scene);
  16341. }
  16342. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16343. this._currentRefreshId = -1;
  16344. };
  16345. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16346. get: function () {
  16347. return this._refreshRate;
  16348. },
  16349. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16350. set: function (value) {
  16351. this._refreshRate = value;
  16352. this.resetRefreshCounter();
  16353. },
  16354. enumerable: true,
  16355. configurable: true
  16356. });
  16357. RenderTargetTexture.prototype._shouldRender = function () {
  16358. if (this._currentRefreshId === -1) {
  16359. this._currentRefreshId = 1;
  16360. return true;
  16361. }
  16362. if (this.refreshRate === this._currentRefreshId) {
  16363. this._currentRefreshId = 1;
  16364. return true;
  16365. }
  16366. this._currentRefreshId++;
  16367. return false;
  16368. };
  16369. RenderTargetTexture.prototype.isReady = function () {
  16370. if (!this.getScene().renderTargetsEnabled) {
  16371. return false;
  16372. }
  16373. return _super.prototype.isReady.call(this);
  16374. };
  16375. RenderTargetTexture.prototype.getRenderSize = function () {
  16376. return this._size;
  16377. };
  16378. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16379. get: function () {
  16380. return true;
  16381. },
  16382. enumerable: true,
  16383. configurable: true
  16384. });
  16385. RenderTargetTexture.prototype.scale = function (ratio) {
  16386. var newSize = this._size * ratio;
  16387. this.resize(newSize, this._generateMipMaps);
  16388. };
  16389. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16390. this.releaseInternalTexture();
  16391. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16392. };
  16393. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16394. var scene = this.getScene();
  16395. var engine = scene.getEngine();
  16396. if (this._waitingRenderList) {
  16397. this.renderList = [];
  16398. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16399. var id = this._waitingRenderList[index];
  16400. this.renderList.push(scene.getMeshByID(id));
  16401. }
  16402. delete this._waitingRenderList;
  16403. }
  16404. if (this.renderList && this.renderList.length === 0) {
  16405. return;
  16406. }
  16407. // Bind
  16408. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16409. engine.bindFramebuffer(this._texture);
  16410. }
  16411. this._renderingManager.reset();
  16412. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16413. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16414. var mesh = currentRenderList[meshIndex];
  16415. if (mesh) {
  16416. if (!mesh.isReady()) {
  16417. // Reset _currentRefreshId
  16418. this.resetRefreshCounter();
  16419. continue;
  16420. }
  16421. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16422. mesh._activate(scene.getRenderId());
  16423. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16424. var subMesh = mesh.subMeshes[subIndex];
  16425. scene._activeIndices += subMesh.indexCount;
  16426. this._renderingManager.dispatch(subMesh);
  16427. }
  16428. }
  16429. }
  16430. }
  16431. if (this.onBeforeRender) {
  16432. this.onBeforeRender();
  16433. }
  16434. // Clear
  16435. if (this.onClear) {
  16436. this.onClear(engine);
  16437. }
  16438. else {
  16439. engine.clear(scene.clearColor, true, true);
  16440. }
  16441. if (!this._doNotChangeAspectRatio) {
  16442. scene.updateTransformMatrix(true);
  16443. }
  16444. // Render
  16445. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16446. if (useCameraPostProcess) {
  16447. scene.postProcessManager._finalizeFrame(false, this._texture);
  16448. }
  16449. if (!this._doNotChangeAspectRatio) {
  16450. scene.updateTransformMatrix(true);
  16451. }
  16452. if (this.onAfterRender) {
  16453. this.onAfterRender();
  16454. }
  16455. // Dump ?
  16456. if (dumpForDebug) {
  16457. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16458. }
  16459. // Unbind
  16460. engine.unBindFramebuffer(this._texture);
  16461. if (this.onAfterUnbind) {
  16462. this.onAfterUnbind();
  16463. }
  16464. };
  16465. RenderTargetTexture.prototype.clone = function () {
  16466. var textureSize = this.getSize();
  16467. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16468. // Base texture
  16469. newTexture.hasAlpha = this.hasAlpha;
  16470. newTexture.level = this.level;
  16471. // RenderTarget Texture
  16472. newTexture.coordinatesMode = this.coordinatesMode;
  16473. newTexture.renderList = this.renderList.slice(0);
  16474. return newTexture;
  16475. };
  16476. return RenderTargetTexture;
  16477. })(BABYLON.Texture);
  16478. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16479. })(BABYLON || (BABYLON = {}));
  16480. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  16481. var BABYLON;
  16482. (function (BABYLON) {
  16483. var ProceduralTexture = (function (_super) {
  16484. __extends(ProceduralTexture, _super);
  16485. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16486. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16487. _super.call(this, null, scene, !generateMipMaps);
  16488. this._currentRefreshId = -1;
  16489. this._refreshRate = 1;
  16490. this._vertexDeclaration = [2];
  16491. this._vertexStrideSize = 2 * 4;
  16492. this._uniforms = new Array();
  16493. this._samplers = new Array();
  16494. this._textures = new Array();
  16495. this._floats = new Array();
  16496. this._floatsArrays = {};
  16497. this._colors3 = new Array();
  16498. this._colors4 = new Array();
  16499. this._vectors2 = new Array();
  16500. this._vectors3 = new Array();
  16501. this._matrices = new Array();
  16502. this._fallbackTextureUsed = false;
  16503. scene._proceduralTextures.push(this);
  16504. this.name = name;
  16505. this.isRenderTarget = true;
  16506. this._size = size;
  16507. this._generateMipMaps = generateMipMaps;
  16508. this.setFragment(fragment);
  16509. this._fallbackTexture = fallbackTexture;
  16510. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16511. // VBO
  16512. var vertices = [];
  16513. vertices.push(1, 1);
  16514. vertices.push(-1, 1);
  16515. vertices.push(-1, -1);
  16516. vertices.push(1, -1);
  16517. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16518. // Indices
  16519. var indices = [];
  16520. indices.push(0);
  16521. indices.push(1);
  16522. indices.push(2);
  16523. indices.push(0);
  16524. indices.push(2);
  16525. indices.push(3);
  16526. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16527. }
  16528. ProceduralTexture.prototype.reset = function () {
  16529. if (this._effect === undefined) {
  16530. return;
  16531. }
  16532. var engine = this.getScene().getEngine();
  16533. engine._releaseEffect(this._effect);
  16534. };
  16535. ProceduralTexture.prototype.isReady = function () {
  16536. var _this = this;
  16537. var engine = this.getScene().getEngine();
  16538. var shaders;
  16539. if (!this._fragment) {
  16540. return false;
  16541. }
  16542. if (this._fallbackTextureUsed) {
  16543. return true;
  16544. }
  16545. if (this._fragment.fragmentElement !== undefined) {
  16546. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16547. }
  16548. else {
  16549. shaders = { vertex: "procedural", fragment: this._fragment };
  16550. }
  16551. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16552. _this.releaseInternalTexture();
  16553. if (_this._fallbackTexture) {
  16554. _this._texture = _this._fallbackTexture._texture;
  16555. _this._texture.references++;
  16556. }
  16557. _this._fallbackTextureUsed = true;
  16558. });
  16559. return this._effect.isReady();
  16560. };
  16561. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16562. this._currentRefreshId = -1;
  16563. };
  16564. ProceduralTexture.prototype.setFragment = function (fragment) {
  16565. this._fragment = fragment;
  16566. };
  16567. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16568. get: function () {
  16569. return this._refreshRate;
  16570. },
  16571. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16572. set: function (value) {
  16573. this._refreshRate = value;
  16574. this.resetRefreshCounter();
  16575. },
  16576. enumerable: true,
  16577. configurable: true
  16578. });
  16579. ProceduralTexture.prototype._shouldRender = function () {
  16580. if (!this.isReady() || !this._texture) {
  16581. return false;
  16582. }
  16583. if (this._fallbackTextureUsed) {
  16584. return false;
  16585. }
  16586. if (this._currentRefreshId === -1) {
  16587. this._currentRefreshId = 1;
  16588. return true;
  16589. }
  16590. if (this.refreshRate === this._currentRefreshId) {
  16591. this._currentRefreshId = 1;
  16592. return true;
  16593. }
  16594. this._currentRefreshId++;
  16595. return false;
  16596. };
  16597. ProceduralTexture.prototype.getRenderSize = function () {
  16598. return this._size;
  16599. };
  16600. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16601. if (this._fallbackTextureUsed) {
  16602. return;
  16603. }
  16604. this.releaseInternalTexture();
  16605. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16606. };
  16607. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16608. if (this._uniforms.indexOf(uniformName) === -1) {
  16609. this._uniforms.push(uniformName);
  16610. }
  16611. };
  16612. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16613. if (this._samplers.indexOf(name) === -1) {
  16614. this._samplers.push(name);
  16615. }
  16616. this._textures[name] = texture;
  16617. return this;
  16618. };
  16619. ProceduralTexture.prototype.setFloat = function (name, value) {
  16620. this._checkUniform(name);
  16621. this._floats[name] = value;
  16622. return this;
  16623. };
  16624. ProceduralTexture.prototype.setFloats = function (name, value) {
  16625. this._checkUniform(name);
  16626. this._floatsArrays[name] = value;
  16627. return this;
  16628. };
  16629. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16630. this._checkUniform(name);
  16631. this._colors3[name] = value;
  16632. return this;
  16633. };
  16634. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16635. this._checkUniform(name);
  16636. this._colors4[name] = value;
  16637. return this;
  16638. };
  16639. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16640. this._checkUniform(name);
  16641. this._vectors2[name] = value;
  16642. return this;
  16643. };
  16644. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16645. this._checkUniform(name);
  16646. this._vectors3[name] = value;
  16647. return this;
  16648. };
  16649. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16650. this._checkUniform(name);
  16651. this._matrices[name] = value;
  16652. return this;
  16653. };
  16654. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16655. var scene = this.getScene();
  16656. var engine = scene.getEngine();
  16657. engine.bindFramebuffer(this._texture);
  16658. // Clear
  16659. engine.clear(scene.clearColor, true, true);
  16660. // Render
  16661. engine.enableEffect(this._effect);
  16662. engine.setState(false);
  16663. // Texture
  16664. for (var name in this._textures) {
  16665. this._effect.setTexture(name, this._textures[name]);
  16666. }
  16667. // Float
  16668. for (name in this._floats) {
  16669. this._effect.setFloat(name, this._floats[name]);
  16670. }
  16671. // Floats
  16672. for (name in this._floatsArrays) {
  16673. this._effect.setArray(name, this._floatsArrays[name]);
  16674. }
  16675. // Color3
  16676. for (name in this._colors3) {
  16677. this._effect.setColor3(name, this._colors3[name]);
  16678. }
  16679. // Color4
  16680. for (name in this._colors4) {
  16681. var color = this._colors4[name];
  16682. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16683. }
  16684. // Vector2
  16685. for (name in this._vectors2) {
  16686. this._effect.setVector2(name, this._vectors2[name]);
  16687. }
  16688. // Vector3
  16689. for (name in this._vectors3) {
  16690. this._effect.setVector3(name, this._vectors3[name]);
  16691. }
  16692. // Matrix
  16693. for (name in this._matrices) {
  16694. this._effect.setMatrix(name, this._matrices[name]);
  16695. }
  16696. // VBOs
  16697. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16698. // Draw order
  16699. engine.draw(true, 0, 6);
  16700. // Unbind
  16701. engine.unBindFramebuffer(this._texture);
  16702. };
  16703. ProceduralTexture.prototype.clone = function () {
  16704. var textureSize = this.getSize();
  16705. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16706. // Base texture
  16707. newTexture.hasAlpha = this.hasAlpha;
  16708. newTexture.level = this.level;
  16709. // RenderTarget Texture
  16710. newTexture.coordinatesMode = this.coordinatesMode;
  16711. return newTexture;
  16712. };
  16713. ProceduralTexture.prototype.dispose = function () {
  16714. var index = this.getScene()._proceduralTextures.indexOf(this);
  16715. if (index >= 0) {
  16716. this.getScene()._proceduralTextures.splice(index, 1);
  16717. }
  16718. _super.prototype.dispose.call(this);
  16719. };
  16720. return ProceduralTexture;
  16721. })(BABYLON.Texture);
  16722. BABYLON.ProceduralTexture = ProceduralTexture;
  16723. })(BABYLON || (BABYLON = {}));
  16724. //# sourceMappingURL=babylon.proceduralTexture.js.map
  16725. var BABYLON;
  16726. (function (BABYLON) {
  16727. var MirrorTexture = (function (_super) {
  16728. __extends(MirrorTexture, _super);
  16729. function MirrorTexture(name, size, scene, generateMipMaps) {
  16730. var _this = this;
  16731. _super.call(this, name, size, scene, generateMipMaps, true);
  16732. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16733. this._transformMatrix = BABYLON.Matrix.Zero();
  16734. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16735. this.onBeforeRender = function () {
  16736. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16737. _this._savedViewMatrix = scene.getViewMatrix();
  16738. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16739. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16740. scene.clipPlane = _this.mirrorPlane;
  16741. scene.getEngine().cullBackFaces = false;
  16742. };
  16743. this.onAfterRender = function () {
  16744. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16745. scene.getEngine().cullBackFaces = true;
  16746. delete scene.clipPlane;
  16747. };
  16748. }
  16749. MirrorTexture.prototype.clone = function () {
  16750. var textureSize = this.getSize();
  16751. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16752. // Base texture
  16753. newTexture.hasAlpha = this.hasAlpha;
  16754. newTexture.level = this.level;
  16755. // Mirror Texture
  16756. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16757. newTexture.renderList = this.renderList.slice(0);
  16758. return newTexture;
  16759. };
  16760. return MirrorTexture;
  16761. })(BABYLON.RenderTargetTexture);
  16762. BABYLON.MirrorTexture = MirrorTexture;
  16763. })(BABYLON || (BABYLON = {}));
  16764. //# sourceMappingURL=babylon.mirrorTexture.js.map
  16765. var BABYLON;
  16766. (function (BABYLON) {
  16767. var DynamicTexture = (function (_super) {
  16768. __extends(DynamicTexture, _super);
  16769. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16770. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16771. _super.call(this, null, scene, !generateMipMaps);
  16772. this.name = name;
  16773. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16774. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16775. this._generateMipMaps = generateMipMaps;
  16776. if (options.getContext) {
  16777. this._canvas = options;
  16778. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16779. }
  16780. else {
  16781. this._canvas = document.createElement("canvas");
  16782. if (options.width) {
  16783. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16784. }
  16785. else {
  16786. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16787. }
  16788. }
  16789. var textureSize = this.getSize();
  16790. this._canvas.width = textureSize.width;
  16791. this._canvas.height = textureSize.height;
  16792. this._context = this._canvas.getContext("2d");
  16793. }
  16794. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16795. get: function () {
  16796. return true;
  16797. },
  16798. enumerable: true,
  16799. configurable: true
  16800. });
  16801. DynamicTexture.prototype.scale = function (ratio) {
  16802. var textureSize = this.getSize();
  16803. textureSize.width *= ratio;
  16804. textureSize.height *= ratio;
  16805. this._canvas.width = textureSize.width;
  16806. this._canvas.height = textureSize.height;
  16807. this.releaseInternalTexture();
  16808. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16809. };
  16810. DynamicTexture.prototype.getContext = function () {
  16811. return this._context;
  16812. };
  16813. DynamicTexture.prototype.clear = function () {
  16814. var size = this.getSize();
  16815. this._context.fillRect(0, 0, size.width, size.height);
  16816. };
  16817. DynamicTexture.prototype.update = function (invertY) {
  16818. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16819. };
  16820. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16821. if (update === void 0) { update = true; }
  16822. var size = this.getSize();
  16823. if (clearColor) {
  16824. this._context.fillStyle = clearColor;
  16825. this._context.fillRect(0, 0, size.width, size.height);
  16826. }
  16827. this._context.font = font;
  16828. if (x === null) {
  16829. var textSize = this._context.measureText(text);
  16830. x = (size.width - textSize.width) / 2;
  16831. }
  16832. this._context.fillStyle = color;
  16833. this._context.fillText(text, x, y);
  16834. if (update) {
  16835. this.update(invertY);
  16836. }
  16837. };
  16838. DynamicTexture.prototype.clone = function () {
  16839. var textureSize = this.getSize();
  16840. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16841. // Base texture
  16842. newTexture.hasAlpha = this.hasAlpha;
  16843. newTexture.level = this.level;
  16844. // Dynamic Texture
  16845. newTexture.wrapU = this.wrapU;
  16846. newTexture.wrapV = this.wrapV;
  16847. return newTexture;
  16848. };
  16849. return DynamicTexture;
  16850. })(BABYLON.Texture);
  16851. BABYLON.DynamicTexture = DynamicTexture;
  16852. })(BABYLON || (BABYLON = {}));
  16853. //# sourceMappingURL=babylon.dynamicTexture.js.map
  16854. var BABYLON;
  16855. (function (BABYLON) {
  16856. var VideoTexture = (function (_super) {
  16857. __extends(VideoTexture, _super);
  16858. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16859. var _this = this;
  16860. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16861. if (invertY === void 0) { invertY = false; }
  16862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16863. _super.call(this, null, scene, !generateMipMaps, invertY);
  16864. this._autoLaunch = true;
  16865. this.name = name;
  16866. this.video = document.createElement("video");
  16867. this.video.autoplay = false;
  16868. this.video.loop = true;
  16869. this.video.addEventListener("canplaythrough", function () {
  16870. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  16871. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16872. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16873. }
  16874. else {
  16875. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16876. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16877. generateMipMaps = false;
  16878. }
  16879. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16880. _this._texture.isReady = true;
  16881. });
  16882. urls.forEach(function (url) {
  16883. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16884. var source = document.createElement("source");
  16885. source.src = url;
  16886. _this.video.appendChild(source);
  16887. });
  16888. this._lastUpdate = BABYLON.Tools.Now;
  16889. }
  16890. VideoTexture.prototype.update = function () {
  16891. if (this._autoLaunch) {
  16892. this._autoLaunch = false;
  16893. this.video.play();
  16894. }
  16895. var now = BABYLON.Tools.Now;
  16896. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16897. return false;
  16898. }
  16899. this._lastUpdate = now;
  16900. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16901. return true;
  16902. };
  16903. return VideoTexture;
  16904. })(BABYLON.Texture);
  16905. BABYLON.VideoTexture = VideoTexture;
  16906. })(BABYLON || (BABYLON = {}));
  16907. //# sourceMappingURL=babylon.videoTexture.js.map
  16908. var BABYLON;
  16909. (function (BABYLON) {
  16910. var CustomProceduralTexture = (function (_super) {
  16911. __extends(CustomProceduralTexture, _super);
  16912. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16913. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16914. this._animate = true;
  16915. this._time = 0;
  16916. this._texturePath = texturePath;
  16917. //Try to load json
  16918. this.loadJson(texturePath);
  16919. this.refreshRate = 1;
  16920. }
  16921. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16922. var _this = this;
  16923. var that = this;
  16924. function noConfigFile() {
  16925. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16926. try {
  16927. that.setFragment(that._texturePath);
  16928. }
  16929. catch (ex) {
  16930. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16931. }
  16932. }
  16933. var configFileUrl = jsonUrl + "/config.json";
  16934. var xhr = new XMLHttpRequest();
  16935. xhr.open("GET", configFileUrl, true);
  16936. xhr.addEventListener("load", function () {
  16937. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16938. try {
  16939. _this._config = JSON.parse(xhr.response);
  16940. _this.updateShaderUniforms();
  16941. _this.updateTextures();
  16942. _this.setFragment(_this._texturePath + "/custom");
  16943. _this._animate = _this._config.animate;
  16944. _this.refreshRate = _this._config.refreshrate;
  16945. }
  16946. catch (ex) {
  16947. noConfigFile();
  16948. }
  16949. }
  16950. else {
  16951. noConfigFile();
  16952. }
  16953. }, false);
  16954. xhr.addEventListener("error", function () {
  16955. noConfigFile();
  16956. }, false);
  16957. try {
  16958. xhr.send();
  16959. }
  16960. catch (ex) {
  16961. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  16962. }
  16963. };
  16964. CustomProceduralTexture.prototype.isReady = function () {
  16965. if (!_super.prototype.isReady.call(this)) {
  16966. return false;
  16967. }
  16968. for (var name in this._textures) {
  16969. var texture = this._textures[name];
  16970. if (!texture.isReady()) {
  16971. return false;
  16972. }
  16973. }
  16974. return true;
  16975. };
  16976. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16977. if (this._animate) {
  16978. this._time += this.getScene().getAnimationRatio() * 0.03;
  16979. this.updateShaderUniforms();
  16980. }
  16981. _super.prototype.render.call(this, useCameraPostProcess);
  16982. };
  16983. CustomProceduralTexture.prototype.updateTextures = function () {
  16984. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  16985. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  16986. }
  16987. };
  16988. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  16989. if (this._config) {
  16990. for (var j = 0; j < this._config.uniforms.length; j++) {
  16991. var uniform = this._config.uniforms[j];
  16992. switch (uniform.type) {
  16993. case "float":
  16994. this.setFloat(uniform.name, uniform.value);
  16995. break;
  16996. case "color3":
  16997. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  16998. break;
  16999. case "color4":
  17000. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17001. break;
  17002. case "vector2":
  17003. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17004. break;
  17005. case "vector3":
  17006. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17007. break;
  17008. }
  17009. }
  17010. }
  17011. this.setFloat("time", this._time);
  17012. };
  17013. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17014. get: function () {
  17015. return this._animate;
  17016. },
  17017. set: function (value) {
  17018. this._animate = value;
  17019. },
  17020. enumerable: true,
  17021. configurable: true
  17022. });
  17023. return CustomProceduralTexture;
  17024. })(BABYLON.ProceduralTexture);
  17025. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17026. })(BABYLON || (BABYLON = {}));
  17027. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  17028. var BABYLON;
  17029. (function (BABYLON) {
  17030. var WoodProceduralTexture = (function (_super) {
  17031. __extends(WoodProceduralTexture, _super);
  17032. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17033. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17034. this._ampScale = 100.0;
  17035. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17036. this.updateShaderUniforms();
  17037. this.refreshRate = 0;
  17038. }
  17039. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17040. this.setFloat("ampScale", this._ampScale);
  17041. this.setColor3("woodColor", this._woodColor);
  17042. };
  17043. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17044. get: function () {
  17045. return this._ampScale;
  17046. },
  17047. set: function (value) {
  17048. this._ampScale = value;
  17049. this.updateShaderUniforms();
  17050. },
  17051. enumerable: true,
  17052. configurable: true
  17053. });
  17054. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17055. get: function () {
  17056. return this._woodColor;
  17057. },
  17058. set: function (value) {
  17059. this._woodColor = value;
  17060. this.updateShaderUniforms();
  17061. },
  17062. enumerable: true,
  17063. configurable: true
  17064. });
  17065. return WoodProceduralTexture;
  17066. })(BABYLON.ProceduralTexture);
  17067. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17068. var FireProceduralTexture = (function (_super) {
  17069. __extends(FireProceduralTexture, _super);
  17070. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17071. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17072. this._time = 0.0;
  17073. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17074. this._autoGenerateTime = true;
  17075. this._alphaThreshold = 0.5;
  17076. this._fireColors = FireProceduralTexture.RedFireColors;
  17077. this.updateShaderUniforms();
  17078. this.refreshRate = 1;
  17079. }
  17080. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17081. this.setFloat("time", this._time);
  17082. this.setVector2("speed", this._speed);
  17083. this.setColor3("c1", this._fireColors[0]);
  17084. this.setColor3("c2", this._fireColors[1]);
  17085. this.setColor3("c3", this._fireColors[2]);
  17086. this.setColor3("c4", this._fireColors[3]);
  17087. this.setColor3("c5", this._fireColors[4]);
  17088. this.setColor3("c6", this._fireColors[5]);
  17089. this.setFloat("alphaThreshold", this._alphaThreshold);
  17090. };
  17091. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17092. if (this._autoGenerateTime) {
  17093. this._time += this.getScene().getAnimationRatio() * 0.03;
  17094. this.updateShaderUniforms();
  17095. }
  17096. _super.prototype.render.call(this, useCameraPostProcess);
  17097. };
  17098. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17099. get: function () {
  17100. return [
  17101. new BABYLON.Color3(0.5, 0.0, 1.0),
  17102. new BABYLON.Color3(0.9, 0.0, 1.0),
  17103. new BABYLON.Color3(0.2, 0.0, 1.0),
  17104. new BABYLON.Color3(1.0, 0.9, 1.0),
  17105. new BABYLON.Color3(0.1, 0.1, 1.0),
  17106. new BABYLON.Color3(0.9, 0.9, 1.0)
  17107. ];
  17108. },
  17109. enumerable: true,
  17110. configurable: true
  17111. });
  17112. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17113. get: function () {
  17114. return [
  17115. new BABYLON.Color3(0.5, 1.0, 0.0),
  17116. new BABYLON.Color3(0.5, 1.0, 0.0),
  17117. new BABYLON.Color3(0.3, 0.4, 0.0),
  17118. new BABYLON.Color3(0.5, 1.0, 0.0),
  17119. new BABYLON.Color3(0.2, 0.0, 0.0),
  17120. new BABYLON.Color3(0.5, 1.0, 0.0)
  17121. ];
  17122. },
  17123. enumerable: true,
  17124. configurable: true
  17125. });
  17126. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17127. get: function () {
  17128. return [
  17129. new BABYLON.Color3(0.5, 0.0, 0.1),
  17130. new BABYLON.Color3(0.9, 0.0, 0.0),
  17131. new BABYLON.Color3(0.2, 0.0, 0.0),
  17132. new BABYLON.Color3(1.0, 0.9, 0.0),
  17133. new BABYLON.Color3(0.1, 0.1, 0.1),
  17134. new BABYLON.Color3(0.9, 0.9, 0.9)
  17135. ];
  17136. },
  17137. enumerable: true,
  17138. configurable: true
  17139. });
  17140. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17141. get: function () {
  17142. return [
  17143. new BABYLON.Color3(0.1, 0.0, 0.5),
  17144. new BABYLON.Color3(0.0, 0.0, 0.5),
  17145. new BABYLON.Color3(0.1, 0.0, 0.2),
  17146. new BABYLON.Color3(0.0, 0.0, 1.0),
  17147. new BABYLON.Color3(0.1, 0.2, 0.3),
  17148. new BABYLON.Color3(0.0, 0.2, 0.9)
  17149. ];
  17150. },
  17151. enumerable: true,
  17152. configurable: true
  17153. });
  17154. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17155. get: function () {
  17156. return this._fireColors;
  17157. },
  17158. set: function (value) {
  17159. this._fireColors = value;
  17160. this.updateShaderUniforms();
  17161. },
  17162. enumerable: true,
  17163. configurable: true
  17164. });
  17165. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17166. get: function () {
  17167. return this._time;
  17168. },
  17169. set: function (value) {
  17170. this._time = value;
  17171. this.updateShaderUniforms();
  17172. },
  17173. enumerable: true,
  17174. configurable: true
  17175. });
  17176. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17177. get: function () {
  17178. return this._speed;
  17179. },
  17180. set: function (value) {
  17181. this._speed = value;
  17182. this.updateShaderUniforms();
  17183. },
  17184. enumerable: true,
  17185. configurable: true
  17186. });
  17187. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17188. get: function () {
  17189. return this._alphaThreshold;
  17190. },
  17191. set: function (value) {
  17192. this._alphaThreshold = value;
  17193. this.updateShaderUniforms();
  17194. },
  17195. enumerable: true,
  17196. configurable: true
  17197. });
  17198. return FireProceduralTexture;
  17199. })(BABYLON.ProceduralTexture);
  17200. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17201. var CloudProceduralTexture = (function (_super) {
  17202. __extends(CloudProceduralTexture, _super);
  17203. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17204. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17205. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  17206. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  17207. this.updateShaderUniforms();
  17208. this.refreshRate = 0;
  17209. }
  17210. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17211. this.setColor3("skyColor", this._skyColor);
  17212. this.setColor3("cloudColor", this._cloudColor);
  17213. };
  17214. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17215. get: function () {
  17216. return this._skyColor;
  17217. },
  17218. set: function (value) {
  17219. this._skyColor = value;
  17220. this.updateShaderUniforms();
  17221. },
  17222. enumerable: true,
  17223. configurable: true
  17224. });
  17225. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17226. get: function () {
  17227. return this._cloudColor;
  17228. },
  17229. set: function (value) {
  17230. this._cloudColor = value;
  17231. this.updateShaderUniforms();
  17232. },
  17233. enumerable: true,
  17234. configurable: true
  17235. });
  17236. return CloudProceduralTexture;
  17237. })(BABYLON.ProceduralTexture);
  17238. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17239. var GrassProceduralTexture = (function (_super) {
  17240. __extends(GrassProceduralTexture, _super);
  17241. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17242. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17243. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17244. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17245. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17246. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17247. this._grassColors = [
  17248. new BABYLON.Color3(0.29, 0.38, 0.02),
  17249. new BABYLON.Color3(0.36, 0.49, 0.09),
  17250. new BABYLON.Color3(0.51, 0.6, 0.28)
  17251. ];
  17252. this.updateShaderUniforms();
  17253. this.refreshRate = 0;
  17254. }
  17255. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17256. this.setColor3("herb1Color", this._grassColors[0]);
  17257. this.setColor3("herb2Color", this._grassColors[1]);
  17258. this.setColor3("herb3Color", this._grassColors[2]);
  17259. this.setColor3("groundColor", this._groundColor);
  17260. };
  17261. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17262. get: function () {
  17263. return this._grassColors;
  17264. },
  17265. set: function (value) {
  17266. this._grassColors = value;
  17267. this.updateShaderUniforms();
  17268. },
  17269. enumerable: true,
  17270. configurable: true
  17271. });
  17272. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17273. get: function () {
  17274. return this._groundColor;
  17275. },
  17276. set: function (value) {
  17277. this.groundColor = value;
  17278. this.updateShaderUniforms();
  17279. },
  17280. enumerable: true,
  17281. configurable: true
  17282. });
  17283. return GrassProceduralTexture;
  17284. })(BABYLON.ProceduralTexture);
  17285. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17286. var RoadProceduralTexture = (function (_super) {
  17287. __extends(RoadProceduralTexture, _super);
  17288. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17289. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17290. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17291. this.updateShaderUniforms();
  17292. this.refreshRate = 0;
  17293. }
  17294. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17295. this.setColor3("roadColor", this._roadColor);
  17296. };
  17297. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17298. get: function () {
  17299. return this._roadColor;
  17300. },
  17301. set: function (value) {
  17302. this._roadColor = value;
  17303. this.updateShaderUniforms();
  17304. },
  17305. enumerable: true,
  17306. configurable: true
  17307. });
  17308. return RoadProceduralTexture;
  17309. })(BABYLON.ProceduralTexture);
  17310. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17311. var BrickProceduralTexture = (function (_super) {
  17312. __extends(BrickProceduralTexture, _super);
  17313. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17314. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17315. this._numberOfBricksHeight = 15;
  17316. this._numberOfBricksWidth = 5;
  17317. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17318. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17319. this.updateShaderUniforms();
  17320. this.refreshRate = 0;
  17321. }
  17322. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17323. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17324. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17325. this.setColor3("brickColor", this._brickColor);
  17326. this.setColor3("jointColor", this._jointColor);
  17327. };
  17328. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17329. get: function () {
  17330. return this._numberOfBricksHeight;
  17331. },
  17332. set: function (value) {
  17333. this._numberOfBricksHeight = value;
  17334. this.updateShaderUniforms();
  17335. },
  17336. enumerable: true,
  17337. configurable: true
  17338. });
  17339. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17340. get: function () {
  17341. return this._numberOfBricksWidth;
  17342. },
  17343. set: function (value) {
  17344. this._numberOfBricksHeight = value;
  17345. this.updateShaderUniforms();
  17346. },
  17347. enumerable: true,
  17348. configurable: true
  17349. });
  17350. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17351. get: function () {
  17352. return this._jointColor;
  17353. },
  17354. set: function (value) {
  17355. this._jointColor = value;
  17356. this.updateShaderUniforms();
  17357. },
  17358. enumerable: true,
  17359. configurable: true
  17360. });
  17361. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17362. get: function () {
  17363. return this._brickColor;
  17364. },
  17365. set: function (value) {
  17366. this._brickColor = value;
  17367. this.updateShaderUniforms();
  17368. },
  17369. enumerable: true,
  17370. configurable: true
  17371. });
  17372. return BrickProceduralTexture;
  17373. })(BABYLON.ProceduralTexture);
  17374. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17375. var MarbleProceduralTexture = (function (_super) {
  17376. __extends(MarbleProceduralTexture, _super);
  17377. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17378. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17379. this._numberOfTilesHeight = 3;
  17380. this._numberOfTilesWidth = 3;
  17381. this._amplitude = 9.0;
  17382. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17383. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17384. this.updateShaderUniforms();
  17385. this.refreshRate = 0;
  17386. }
  17387. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17388. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17389. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17390. this.setFloat("amplitude", this._amplitude);
  17391. this.setColor3("marbleColor", this._marbleColor);
  17392. this.setColor3("jointColor", this._jointColor);
  17393. };
  17394. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17395. get: function () {
  17396. return this._numberOfTilesHeight;
  17397. },
  17398. set: function (value) {
  17399. this._numberOfTilesHeight = value;
  17400. this.updateShaderUniforms();
  17401. },
  17402. enumerable: true,
  17403. configurable: true
  17404. });
  17405. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17406. get: function () {
  17407. return this._numberOfTilesWidth;
  17408. },
  17409. set: function (value) {
  17410. this._numberOfTilesWidth = value;
  17411. this.updateShaderUniforms();
  17412. },
  17413. enumerable: true,
  17414. configurable: true
  17415. });
  17416. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17417. get: function () {
  17418. return this._jointColor;
  17419. },
  17420. set: function (value) {
  17421. this._jointColor = value;
  17422. this.updateShaderUniforms();
  17423. },
  17424. enumerable: true,
  17425. configurable: true
  17426. });
  17427. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17428. get: function () {
  17429. return this._marbleColor;
  17430. },
  17431. set: function (value) {
  17432. this._marbleColor = value;
  17433. this.updateShaderUniforms();
  17434. },
  17435. enumerable: true,
  17436. configurable: true
  17437. });
  17438. return MarbleProceduralTexture;
  17439. })(BABYLON.ProceduralTexture);
  17440. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17441. })(BABYLON || (BABYLON = {}));
  17442. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  17443. var BABYLON;
  17444. (function (BABYLON) {
  17445. var EffectFallbacks = (function () {
  17446. function EffectFallbacks() {
  17447. this._defines = {};
  17448. this._currentRank = 32;
  17449. this._maxRank = -1;
  17450. }
  17451. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17452. if (!this._defines[rank]) {
  17453. if (rank < this._currentRank) {
  17454. this._currentRank = rank;
  17455. }
  17456. if (rank > this._maxRank) {
  17457. this._maxRank = rank;
  17458. }
  17459. this._defines[rank] = new Array();
  17460. }
  17461. this._defines[rank].push(define);
  17462. };
  17463. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17464. get: function () {
  17465. return this._currentRank <= this._maxRank;
  17466. },
  17467. enumerable: true,
  17468. configurable: true
  17469. });
  17470. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17471. var currentFallbacks = this._defines[this._currentRank];
  17472. for (var index = 0; index < currentFallbacks.length; index++) {
  17473. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17474. }
  17475. this._currentRank++;
  17476. return currentDefines;
  17477. };
  17478. return EffectFallbacks;
  17479. })();
  17480. BABYLON.EffectFallbacks = EffectFallbacks;
  17481. var Effect = (function () {
  17482. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17483. var _this = this;
  17484. this._isReady = false;
  17485. this._compilationError = "";
  17486. this._valueCache = [];
  17487. this._engine = engine;
  17488. this.name = baseName;
  17489. this.defines = defines;
  17490. this._uniformsNames = uniformsNames.concat(samplers);
  17491. this._samplers = samplers;
  17492. this._attributesNames = attributesNames;
  17493. this.onError = onError;
  17494. this.onCompiled = onCompiled;
  17495. var vertexSource;
  17496. var fragmentSource;
  17497. if (baseName.vertexElement) {
  17498. vertexSource = document.getElementById(baseName.vertexElement);
  17499. if (!vertexSource) {
  17500. vertexSource = baseName.vertexElement;
  17501. }
  17502. }
  17503. else {
  17504. vertexSource = baseName.vertex || baseName;
  17505. }
  17506. if (baseName.fragmentElement) {
  17507. fragmentSource = document.getElementById(baseName.fragmentElement);
  17508. if (!fragmentSource) {
  17509. fragmentSource = baseName.fragmentElement;
  17510. }
  17511. }
  17512. else {
  17513. fragmentSource = baseName.fragment || baseName;
  17514. }
  17515. this._loadVertexShader(vertexSource, function (vertexCode) {
  17516. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17517. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17518. });
  17519. });
  17520. }
  17521. // Properties
  17522. Effect.prototype.isReady = function () {
  17523. return this._isReady;
  17524. };
  17525. Effect.prototype.getProgram = function () {
  17526. return this._program;
  17527. };
  17528. Effect.prototype.getAttributesNames = function () {
  17529. return this._attributesNames;
  17530. };
  17531. Effect.prototype.getAttributeLocation = function (index) {
  17532. return this._attributes[index];
  17533. };
  17534. Effect.prototype.getAttributeLocationByName = function (name) {
  17535. var index = this._attributesNames.indexOf(name);
  17536. return this._attributes[index];
  17537. };
  17538. Effect.prototype.getAttributesCount = function () {
  17539. return this._attributes.length;
  17540. };
  17541. Effect.prototype.getUniformIndex = function (uniformName) {
  17542. return this._uniformsNames.indexOf(uniformName);
  17543. };
  17544. Effect.prototype.getUniform = function (uniformName) {
  17545. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17546. };
  17547. Effect.prototype.getSamplers = function () {
  17548. return this._samplers;
  17549. };
  17550. Effect.prototype.getCompilationError = function () {
  17551. return this._compilationError;
  17552. };
  17553. // Methods
  17554. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17555. // DOM element ?
  17556. if (vertex instanceof HTMLElement) {
  17557. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17558. callback(vertexCode);
  17559. return;
  17560. }
  17561. // Is in local store ?
  17562. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17563. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17564. return;
  17565. }
  17566. var vertexShaderUrl;
  17567. if (vertex[0] === "." || vertex[0] === "/") {
  17568. vertexShaderUrl = vertex;
  17569. }
  17570. else {
  17571. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17572. }
  17573. // Vertex shader
  17574. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17575. };
  17576. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17577. // DOM element ?
  17578. if (fragment instanceof HTMLElement) {
  17579. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17580. callback(fragmentCode);
  17581. return;
  17582. }
  17583. // Is in local store ?
  17584. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17585. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17586. return;
  17587. }
  17588. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17589. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17590. return;
  17591. }
  17592. var fragmentShaderUrl;
  17593. if (fragment[0] === "." || fragment[0] === "/") {
  17594. fragmentShaderUrl = fragment;
  17595. }
  17596. else {
  17597. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17598. }
  17599. // Fragment shader
  17600. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17601. };
  17602. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17603. try {
  17604. var engine = this._engine;
  17605. if (!engine.getCaps().highPrecisionShaderSupported) {
  17606. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17607. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17608. }
  17609. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17610. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17611. this._attributes = engine.getAttributes(this._program, attributesNames);
  17612. for (var index = 0; index < this._samplers.length; index++) {
  17613. var sampler = this.getUniform(this._samplers[index]);
  17614. if (sampler == null) {
  17615. this._samplers.splice(index, 1);
  17616. index--;
  17617. }
  17618. }
  17619. engine.bindSamplers(this);
  17620. this._isReady = true;
  17621. if (this.onCompiled) {
  17622. this.onCompiled(this);
  17623. }
  17624. }
  17625. catch (e) {
  17626. // Is it a problem with precision?
  17627. if (e.message.indexOf("highp") !== -1) {
  17628. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17629. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17630. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17631. return;
  17632. }
  17633. // Let's go through fallbacks then
  17634. if (fallbacks && fallbacks.isMoreFallbacks) {
  17635. defines = fallbacks.reduce(defines);
  17636. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17637. }
  17638. else {
  17639. BABYLON.Tools.Error("Unable to compile effect: ");
  17640. if (this.name.vertexElement) {
  17641. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17642. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17643. }
  17644. else if (this.name.vertex) {
  17645. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17646. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17647. }
  17648. else {
  17649. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17650. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17651. }
  17652. BABYLON.Tools.Error("Defines: " + defines);
  17653. BABYLON.Tools.Error("Error: " + e.message);
  17654. this._compilationError = e.message;
  17655. if (this.onError) {
  17656. this.onError(this, this._compilationError);
  17657. }
  17658. }
  17659. }
  17660. };
  17661. Effect.prototype._bindTexture = function (channel, texture) {
  17662. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17663. };
  17664. Effect.prototype.setTexture = function (channel, texture) {
  17665. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17666. };
  17667. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17668. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17669. };
  17670. //public _cacheMatrix(uniformName, matrix) {
  17671. // if (!this._valueCache[uniformName]) {
  17672. // this._valueCache[uniformName] = new BABYLON.Matrix();
  17673. // }
  17674. // for (var index = 0; index < 16; index++) {
  17675. // this._valueCache[uniformName].m[index] = matrix.m[index];
  17676. // }
  17677. //};
  17678. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17679. if (!this._valueCache[uniformName]) {
  17680. this._valueCache[uniformName] = [x, y];
  17681. return;
  17682. }
  17683. this._valueCache[uniformName][0] = x;
  17684. this._valueCache[uniformName][1] = y;
  17685. };
  17686. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17687. if (!this._valueCache[uniformName]) {
  17688. this._valueCache[uniformName] = [x, y, z];
  17689. return;
  17690. }
  17691. this._valueCache[uniformName][0] = x;
  17692. this._valueCache[uniformName][1] = y;
  17693. this._valueCache[uniformName][2] = z;
  17694. };
  17695. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17696. if (!this._valueCache[uniformName]) {
  17697. this._valueCache[uniformName] = [x, y, z, w];
  17698. return;
  17699. }
  17700. this._valueCache[uniformName][0] = x;
  17701. this._valueCache[uniformName][1] = y;
  17702. this._valueCache[uniformName][2] = z;
  17703. this._valueCache[uniformName][3] = w;
  17704. };
  17705. Effect.prototype.setArray = function (uniformName, array) {
  17706. this._engine.setArray(this.getUniform(uniformName), array);
  17707. return this;
  17708. };
  17709. Effect.prototype.setArray2 = function (uniformName, array) {
  17710. this._engine.setArray2(this.getUniform(uniformName), array);
  17711. return this;
  17712. };
  17713. Effect.prototype.setArray3 = function (uniformName, array) {
  17714. this._engine.setArray3(this.getUniform(uniformName), array);
  17715. return this;
  17716. };
  17717. Effect.prototype.setArray4 = function (uniformName, array) {
  17718. this._engine.setArray4(this.getUniform(uniformName), array);
  17719. return this;
  17720. };
  17721. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17722. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17723. return this;
  17724. };
  17725. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17726. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17727. // return;
  17728. //this._cacheMatrix(uniformName, matrix);
  17729. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17730. return this;
  17731. };
  17732. Effect.prototype.setFloat = function (uniformName, value) {
  17733. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17734. return this;
  17735. this._valueCache[uniformName] = value;
  17736. this._engine.setFloat(this.getUniform(uniformName), value);
  17737. return this;
  17738. };
  17739. Effect.prototype.setBool = function (uniformName, bool) {
  17740. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17741. return this;
  17742. this._valueCache[uniformName] = bool;
  17743. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17744. return this;
  17745. };
  17746. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17747. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17748. return this;
  17749. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17750. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17751. return this;
  17752. };
  17753. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17754. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17755. return this;
  17756. this._cacheFloat2(uniformName, x, y);
  17757. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17758. return this;
  17759. };
  17760. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17761. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17762. return this;
  17763. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17764. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17765. return this;
  17766. };
  17767. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17768. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17769. return this;
  17770. this._cacheFloat3(uniformName, x, y, z);
  17771. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17772. return this;
  17773. };
  17774. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17775. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17776. return this;
  17777. this._cacheFloat4(uniformName, x, y, z, w);
  17778. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17779. return this;
  17780. };
  17781. Effect.prototype.setColor3 = function (uniformName, color3) {
  17782. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17783. return this;
  17784. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17785. this._engine.setColor3(this.getUniform(uniformName), color3);
  17786. return this;
  17787. };
  17788. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17789. 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)
  17790. return this;
  17791. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17792. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17793. return this;
  17794. };
  17795. // Statics
  17796. Effect.ShadersStore = {};
  17797. return Effect;
  17798. })();
  17799. BABYLON.Effect = Effect;
  17800. })(BABYLON || (BABYLON = {}));
  17801. //# sourceMappingURL=babylon.effect.js.map
  17802. var BABYLON;
  17803. (function (BABYLON) {
  17804. var Material = (function () {
  17805. function Material(name, scene, doNotAdd) {
  17806. this.name = name;
  17807. this.checkReadyOnEveryCall = true;
  17808. this.checkReadyOnlyOnce = false;
  17809. this.state = "";
  17810. this.alpha = 1.0;
  17811. this.backFaceCulling = true;
  17812. this._wasPreviouslyReady = false;
  17813. this._fillMode = Material.TriangleFillMode;
  17814. this.pointSize = 1.0;
  17815. this.zOffset = 0;
  17816. this.id = name;
  17817. this._scene = scene;
  17818. if (!doNotAdd) {
  17819. scene.materials.push(this);
  17820. }
  17821. }
  17822. Object.defineProperty(Material, "TriangleFillMode", {
  17823. get: function () {
  17824. return Material._TriangleFillMode;
  17825. },
  17826. enumerable: true,
  17827. configurable: true
  17828. });
  17829. Object.defineProperty(Material, "WireFrameFillMode", {
  17830. get: function () {
  17831. return Material._WireFrameFillMode;
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. Object.defineProperty(Material, "PointFillMode", {
  17837. get: function () {
  17838. return Material._PointFillMode;
  17839. },
  17840. enumerable: true,
  17841. configurable: true
  17842. });
  17843. Object.defineProperty(Material.prototype, "wireframe", {
  17844. get: function () {
  17845. return this._fillMode === Material.WireFrameFillMode;
  17846. },
  17847. set: function (value) {
  17848. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17849. },
  17850. enumerable: true,
  17851. configurable: true
  17852. });
  17853. Object.defineProperty(Material.prototype, "pointsCloud", {
  17854. get: function () {
  17855. return this._fillMode === Material.PointFillMode;
  17856. },
  17857. set: function (value) {
  17858. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17859. },
  17860. enumerable: true,
  17861. configurable: true
  17862. });
  17863. Object.defineProperty(Material.prototype, "fillMode", {
  17864. get: function () {
  17865. return this._fillMode;
  17866. },
  17867. set: function (value) {
  17868. this._fillMode = value;
  17869. },
  17870. enumerable: true,
  17871. configurable: true
  17872. });
  17873. Material.prototype.isReady = function (mesh, useInstances) {
  17874. return true;
  17875. };
  17876. Material.prototype.getEffect = function () {
  17877. return this._effect;
  17878. };
  17879. Material.prototype.getScene = function () {
  17880. return this._scene;
  17881. };
  17882. Material.prototype.needAlphaBlending = function () {
  17883. return (this.alpha < 1.0);
  17884. };
  17885. Material.prototype.needAlphaTesting = function () {
  17886. return false;
  17887. };
  17888. Material.prototype.getAlphaTestTexture = function () {
  17889. return null;
  17890. };
  17891. Material.prototype.trackCreation = function (onCompiled, onError) {
  17892. };
  17893. Material.prototype._preBind = function () {
  17894. var engine = this._scene.getEngine();
  17895. engine.enableEffect(this._effect);
  17896. engine.setState(this.backFaceCulling, this.zOffset);
  17897. };
  17898. Material.prototype.bind = function (world, mesh) {
  17899. this._scene._cachedMaterial = this;
  17900. if (this.onBind) {
  17901. this.onBind(this, mesh);
  17902. }
  17903. };
  17904. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17905. };
  17906. Material.prototype.unbind = function () {
  17907. };
  17908. Material.prototype.dispose = function (forceDisposeEffect) {
  17909. // Remove from scene
  17910. var index = this._scene.materials.indexOf(this);
  17911. this._scene.materials.splice(index, 1);
  17912. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17913. if (forceDisposeEffect && this._effect) {
  17914. this._scene.getEngine()._releaseEffect(this._effect);
  17915. this._effect = null;
  17916. }
  17917. // Callback
  17918. if (this.onDispose) {
  17919. this.onDispose();
  17920. }
  17921. };
  17922. Material._TriangleFillMode = 0;
  17923. Material._WireFrameFillMode = 1;
  17924. Material._PointFillMode = 2;
  17925. return Material;
  17926. })();
  17927. BABYLON.Material = Material;
  17928. })(BABYLON || (BABYLON = {}));
  17929. //# sourceMappingURL=babylon.material.js.map
  17930. var BABYLON;
  17931. (function (BABYLON) {
  17932. var maxSimultaneousLights = 4;
  17933. var FresnelParameters = (function () {
  17934. function FresnelParameters() {
  17935. this.isEnabled = true;
  17936. this.leftColor = BABYLON.Color3.White();
  17937. this.rightColor = BABYLON.Color3.Black();
  17938. this.bias = 0;
  17939. this.power = 1;
  17940. }
  17941. return FresnelParameters;
  17942. })();
  17943. BABYLON.FresnelParameters = FresnelParameters;
  17944. var StandardMaterial = (function (_super) {
  17945. __extends(StandardMaterial, _super);
  17946. function StandardMaterial(name, scene) {
  17947. var _this = this;
  17948. _super.call(this, name, scene);
  17949. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17950. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  17951. this.specularColor = new BABYLON.Color3(1, 1, 1);
  17952. this.specularPower = 64;
  17953. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  17954. this.useAlphaFromDiffuseTexture = false;
  17955. this.useSpecularOverAlpha = true;
  17956. this.fogEnabled = true;
  17957. this._cachedDefines = null;
  17958. this._renderTargets = new BABYLON.SmartArray(16);
  17959. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  17960. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  17961. this._scaledDiffuse = new BABYLON.Color3();
  17962. this._scaledSpecular = new BABYLON.Color3();
  17963. this.getRenderTargetTextures = function () {
  17964. _this._renderTargets.reset();
  17965. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  17966. _this._renderTargets.push(_this.reflectionTexture);
  17967. }
  17968. return _this._renderTargets;
  17969. };
  17970. }
  17971. StandardMaterial.prototype.needAlphaBlending = function () {
  17972. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  17973. };
  17974. StandardMaterial.prototype.needAlphaTesting = function () {
  17975. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  17976. };
  17977. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  17978. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  17979. };
  17980. StandardMaterial.prototype.getAlphaTestTexture = function () {
  17981. return this.diffuseTexture;
  17982. };
  17983. // Methods
  17984. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  17985. if (this.checkReadyOnlyOnce) {
  17986. if (this._wasPreviouslyReady) {
  17987. return true;
  17988. }
  17989. }
  17990. var scene = this.getScene();
  17991. if (!this.checkReadyOnEveryCall) {
  17992. if (this._renderId === scene.getRenderId()) {
  17993. return true;
  17994. }
  17995. }
  17996. var engine = scene.getEngine();
  17997. var defines = [];
  17998. var fallbacks = new BABYLON.EffectFallbacks();
  17999. var needNormals = false;
  18000. var needUVs = false;
  18001. // Textures
  18002. if (scene.texturesEnabled) {
  18003. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18004. if (!this.diffuseTexture.isReady()) {
  18005. return false;
  18006. }
  18007. else {
  18008. needUVs = true;
  18009. defines.push("#define DIFFUSE");
  18010. }
  18011. }
  18012. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18013. if (!this.ambientTexture.isReady()) {
  18014. return false;
  18015. }
  18016. else {
  18017. needUVs = true;
  18018. defines.push("#define AMBIENT");
  18019. }
  18020. }
  18021. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18022. if (!this.opacityTexture.isReady()) {
  18023. return false;
  18024. }
  18025. else {
  18026. needUVs = true;
  18027. defines.push("#define OPACITY");
  18028. if (this.opacityTexture.getAlphaFromRGB) {
  18029. defines.push("#define OPACITYRGB");
  18030. }
  18031. }
  18032. }
  18033. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18034. if (!this.reflectionTexture.isReady()) {
  18035. return false;
  18036. }
  18037. else {
  18038. needNormals = true;
  18039. needUVs = true;
  18040. defines.push("#define REFLECTION");
  18041. fallbacks.addFallback(0, "REFLECTION");
  18042. }
  18043. }
  18044. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18045. if (!this.emissiveTexture.isReady()) {
  18046. return false;
  18047. }
  18048. else {
  18049. needUVs = true;
  18050. defines.push("#define EMISSIVE");
  18051. }
  18052. }
  18053. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18054. if (!this.specularTexture.isReady()) {
  18055. return false;
  18056. }
  18057. else {
  18058. needUVs = true;
  18059. defines.push("#define SPECULAR");
  18060. fallbacks.addFallback(0, "SPECULAR");
  18061. }
  18062. }
  18063. }
  18064. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18065. if (!this.bumpTexture.isReady()) {
  18066. return false;
  18067. }
  18068. else {
  18069. needUVs = true;
  18070. defines.push("#define BUMP");
  18071. fallbacks.addFallback(0, "BUMP");
  18072. }
  18073. }
  18074. // Effect
  18075. if (this.useSpecularOverAlpha) {
  18076. defines.push("#define SPECULAROVERALPHA");
  18077. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18078. }
  18079. if (scene.clipPlane) {
  18080. defines.push("#define CLIPPLANE");
  18081. }
  18082. if (engine.getAlphaTesting()) {
  18083. defines.push("#define ALPHATEST");
  18084. }
  18085. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18086. defines.push("#define ALPHAFROMDIFFUSE");
  18087. }
  18088. // Point size
  18089. if (this.pointsCloud || scene.forcePointsCloud) {
  18090. defines.push("#define POINTSIZE");
  18091. }
  18092. // Fog
  18093. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18094. defines.push("#define FOG");
  18095. fallbacks.addFallback(1, "FOG");
  18096. }
  18097. var shadowsActivated = false;
  18098. var lightIndex = 0;
  18099. if (scene.lightsEnabled) {
  18100. for (var index = 0; index < scene.lights.length; index++) {
  18101. var light = scene.lights[index];
  18102. if (!light.isEnabled()) {
  18103. continue;
  18104. }
  18105. // Excluded check
  18106. if (light._excludedMeshesIds.length > 0) {
  18107. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18108. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18109. if (excludedMesh) {
  18110. light.excludedMeshes.push(excludedMesh);
  18111. }
  18112. }
  18113. light._excludedMeshesIds = [];
  18114. }
  18115. // Included check
  18116. if (light._includedOnlyMeshesIds.length > 0) {
  18117. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18118. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18119. if (includedOnlyMesh) {
  18120. light.includedOnlyMeshes.push(includedOnlyMesh);
  18121. }
  18122. }
  18123. light._includedOnlyMeshesIds = [];
  18124. }
  18125. if (!light.canAffectMesh(mesh)) {
  18126. continue;
  18127. }
  18128. needNormals = true;
  18129. defines.push("#define LIGHT" + lightIndex);
  18130. if (lightIndex > 0) {
  18131. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18132. }
  18133. var type;
  18134. if (light instanceof BABYLON.SpotLight) {
  18135. type = "#define SPOTLIGHT" + lightIndex;
  18136. }
  18137. else if (light instanceof BABYLON.HemisphericLight) {
  18138. type = "#define HEMILIGHT" + lightIndex;
  18139. }
  18140. else {
  18141. type = "#define POINTDIRLIGHT" + lightIndex;
  18142. }
  18143. defines.push(type);
  18144. if (lightIndex > 0) {
  18145. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  18146. }
  18147. // Shadows
  18148. if (scene.shadowsEnabled) {
  18149. var shadowGenerator = light.getShadowGenerator();
  18150. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18151. defines.push("#define SHADOW" + lightIndex);
  18152. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18153. if (!shadowsActivated) {
  18154. defines.push("#define SHADOWS");
  18155. shadowsActivated = true;
  18156. }
  18157. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18158. defines.push("#define SHADOWVSM" + lightIndex);
  18159. if (lightIndex > 0) {
  18160. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18161. }
  18162. }
  18163. if (shadowGenerator.usePoissonSampling) {
  18164. defines.push("#define SHADOWPCF" + lightIndex);
  18165. if (lightIndex > 0) {
  18166. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18167. }
  18168. }
  18169. }
  18170. }
  18171. lightIndex++;
  18172. if (lightIndex === maxSimultaneousLights)
  18173. break;
  18174. }
  18175. }
  18176. if (StandardMaterial.FresnelEnabled) {
  18177. // Fresnel
  18178. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18179. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18180. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18181. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18182. var fresnelRank = 1;
  18183. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18184. defines.push("#define DIFFUSEFRESNEL");
  18185. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  18186. fresnelRank++;
  18187. }
  18188. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18189. defines.push("#define OPACITYFRESNEL");
  18190. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  18191. fresnelRank++;
  18192. }
  18193. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18194. defines.push("#define REFLECTIONFRESNEL");
  18195. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  18196. fresnelRank++;
  18197. }
  18198. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18199. defines.push("#define EMISSIVEFRESNEL");
  18200. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  18201. fresnelRank++;
  18202. }
  18203. needNormals = true;
  18204. defines.push("#define FRESNEL");
  18205. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  18206. }
  18207. }
  18208. // Attribs
  18209. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18210. if (mesh) {
  18211. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18212. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18213. defines.push("#define NORMAL");
  18214. }
  18215. if (needUVs) {
  18216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18217. attribs.push(BABYLON.VertexBuffer.UVKind);
  18218. defines.push("#define UV1");
  18219. }
  18220. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18221. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18222. defines.push("#define UV2");
  18223. }
  18224. }
  18225. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18226. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18227. defines.push("#define VERTEXCOLOR");
  18228. if (mesh.hasVertexAlpha) {
  18229. defines.push("#define VERTEXALPHA");
  18230. }
  18231. }
  18232. if (mesh.useBones) {
  18233. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18234. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18235. defines.push("#define BONES");
  18236. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  18237. defines.push("#define BONES4");
  18238. fallbacks.addFallback(0, "BONES4");
  18239. }
  18240. // Instances
  18241. if (useInstances) {
  18242. defines.push("#define INSTANCES");
  18243. attribs.push("world0");
  18244. attribs.push("world1");
  18245. attribs.push("world2");
  18246. attribs.push("world3");
  18247. }
  18248. }
  18249. // Get correct effect
  18250. var join = defines.join("\n");
  18251. if (this._cachedDefines !== join) {
  18252. this._cachedDefines = join;
  18253. scene.resetCachedMaterial();
  18254. // Legacy browser patch
  18255. var shaderName = "default";
  18256. if (!scene.getEngine().getCaps().standardDerivatives) {
  18257. shaderName = "legacydefault";
  18258. }
  18259. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18260. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18261. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18262. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18263. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18264. "vFogInfos", "vFogColor", "pointSize",
  18265. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18266. "mBones",
  18267. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18268. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18269. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18270. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18271. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18272. ], join, fallbacks, this.onCompiled, this.onError);
  18273. }
  18274. if (!this._effect.isReady()) {
  18275. return false;
  18276. }
  18277. this._renderId = scene.getRenderId();
  18278. this._wasPreviouslyReady = true;
  18279. return true;
  18280. };
  18281. StandardMaterial.prototype.unbind = function () {
  18282. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18283. this._effect.setTexture("reflection2DSampler", null);
  18284. }
  18285. };
  18286. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18287. this._effect.setMatrix("world", world);
  18288. };
  18289. StandardMaterial.prototype.bind = function (world, mesh) {
  18290. var scene = this.getScene();
  18291. // Matrices
  18292. this.bindOnlyWorldMatrix(world);
  18293. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18294. // Bones
  18295. if (mesh && mesh.useBones) {
  18296. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18297. }
  18298. if (scene.getCachedMaterial() !== this) {
  18299. if (StandardMaterial.FresnelEnabled) {
  18300. // Fresnel
  18301. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18302. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18303. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18304. }
  18305. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18306. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18307. }
  18308. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18309. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18310. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18311. }
  18312. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18313. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18314. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18315. }
  18316. }
  18317. // Textures
  18318. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18319. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18320. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18321. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18322. }
  18323. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18324. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18325. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18326. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18327. }
  18328. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18329. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18330. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18331. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18332. }
  18333. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18334. if (this.reflectionTexture.isCube) {
  18335. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18336. }
  18337. else {
  18338. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18339. }
  18340. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18341. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18342. }
  18343. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18344. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18345. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18346. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18347. }
  18348. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18349. this._effect.setTexture("specularSampler", this.specularTexture);
  18350. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18351. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18352. }
  18353. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18354. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18355. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18356. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18357. }
  18358. // Clip plane
  18359. if (scene.clipPlane) {
  18360. var clipPlane = scene.clipPlane;
  18361. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18362. }
  18363. // Point size
  18364. if (this.pointsCloud) {
  18365. this._effect.setFloat("pointSize", this.pointSize);
  18366. }
  18367. // Colors
  18368. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18369. // Scaling down color according to emissive
  18370. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18371. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18372. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18373. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  18374. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18375. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18376. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18377. }
  18378. // Scaling down color according to emissive
  18379. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18380. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18381. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18382. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18383. if (scene.lightsEnabled) {
  18384. var lightIndex = 0;
  18385. for (var index = 0; index < scene.lights.length; index++) {
  18386. var light = scene.lights[index];
  18387. if (!light.isEnabled()) {
  18388. continue;
  18389. }
  18390. if (!light.canAffectMesh(mesh)) {
  18391. continue;
  18392. }
  18393. if (light instanceof BABYLON.PointLight) {
  18394. // Point Light
  18395. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18396. }
  18397. else if (light instanceof BABYLON.DirectionalLight) {
  18398. // Directional Light
  18399. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18400. }
  18401. else if (light instanceof BABYLON.SpotLight) {
  18402. // Spot Light
  18403. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18404. }
  18405. else if (light instanceof BABYLON.HemisphericLight) {
  18406. // Hemispheric Light
  18407. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18408. }
  18409. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18410. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18411. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18412. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18413. // Shadows
  18414. if (scene.shadowsEnabled) {
  18415. var shadowGenerator = light.getShadowGenerator();
  18416. if (mesh.receiveShadows && shadowGenerator) {
  18417. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18418. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18419. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18420. }
  18421. }
  18422. lightIndex++;
  18423. if (lightIndex === maxSimultaneousLights)
  18424. break;
  18425. }
  18426. }
  18427. // View
  18428. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18429. this._effect.setMatrix("view", scene.getViewMatrix());
  18430. }
  18431. // Fog
  18432. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18433. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18434. this._effect.setColor3("vFogColor", scene.fogColor);
  18435. }
  18436. _super.prototype.bind.call(this, world, mesh);
  18437. };
  18438. StandardMaterial.prototype.getAnimatables = function () {
  18439. var results = [];
  18440. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18441. results.push(this.diffuseTexture);
  18442. }
  18443. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18444. results.push(this.ambientTexture);
  18445. }
  18446. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18447. results.push(this.opacityTexture);
  18448. }
  18449. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18450. results.push(this.reflectionTexture);
  18451. }
  18452. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18453. results.push(this.emissiveTexture);
  18454. }
  18455. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18456. results.push(this.specularTexture);
  18457. }
  18458. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18459. results.push(this.bumpTexture);
  18460. }
  18461. return results;
  18462. };
  18463. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18464. if (this.diffuseTexture) {
  18465. this.diffuseTexture.dispose();
  18466. }
  18467. if (this.ambientTexture) {
  18468. this.ambientTexture.dispose();
  18469. }
  18470. if (this.opacityTexture) {
  18471. this.opacityTexture.dispose();
  18472. }
  18473. if (this.reflectionTexture) {
  18474. this.reflectionTexture.dispose();
  18475. }
  18476. if (this.emissiveTexture) {
  18477. this.emissiveTexture.dispose();
  18478. }
  18479. if (this.specularTexture) {
  18480. this.specularTexture.dispose();
  18481. }
  18482. if (this.bumpTexture) {
  18483. this.bumpTexture.dispose();
  18484. }
  18485. _super.prototype.dispose.call(this, forceDisposeEffect);
  18486. };
  18487. StandardMaterial.prototype.clone = function (name) {
  18488. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18489. // Base material
  18490. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18491. newStandardMaterial.alpha = this.alpha;
  18492. newStandardMaterial.fillMode = this.fillMode;
  18493. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  18494. // Standard material
  18495. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18496. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18497. }
  18498. if (this.ambientTexture && this.ambientTexture.clone) {
  18499. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18500. }
  18501. if (this.opacityTexture && this.opacityTexture.clone) {
  18502. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18503. }
  18504. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18505. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18506. }
  18507. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18508. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18509. }
  18510. if (this.specularTexture && this.specularTexture.clone) {
  18511. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18512. }
  18513. if (this.bumpTexture && this.bumpTexture.clone) {
  18514. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18515. }
  18516. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18517. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18518. newStandardMaterial.specularColor = this.specularColor.clone();
  18519. newStandardMaterial.specularPower = this.specularPower;
  18520. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18521. return newStandardMaterial;
  18522. };
  18523. // Statics
  18524. // Flags used to enable or disable a type of texture for all Standard Materials
  18525. StandardMaterial.DiffuseTextureEnabled = true;
  18526. StandardMaterial.AmbientTextureEnabled = true;
  18527. StandardMaterial.OpacityTextureEnabled = true;
  18528. StandardMaterial.ReflectionTextureEnabled = true;
  18529. StandardMaterial.EmissiveTextureEnabled = true;
  18530. StandardMaterial.SpecularTextureEnabled = true;
  18531. StandardMaterial.BumpTextureEnabled = true;
  18532. StandardMaterial.FresnelEnabled = true;
  18533. return StandardMaterial;
  18534. })(BABYLON.Material);
  18535. BABYLON.StandardMaterial = StandardMaterial;
  18536. })(BABYLON || (BABYLON = {}));
  18537. //# sourceMappingURL=babylon.standardMaterial.js.map
  18538. var BABYLON;
  18539. (function (BABYLON) {
  18540. var MultiMaterial = (function (_super) {
  18541. __extends(MultiMaterial, _super);
  18542. function MultiMaterial(name, scene) {
  18543. _super.call(this, name, scene, true);
  18544. this.subMaterials = new Array();
  18545. scene.multiMaterials.push(this);
  18546. }
  18547. // Properties
  18548. MultiMaterial.prototype.getSubMaterial = function (index) {
  18549. if (index < 0 || index >= this.subMaterials.length) {
  18550. return this.getScene().defaultMaterial;
  18551. }
  18552. return this.subMaterials[index];
  18553. };
  18554. // Methods
  18555. MultiMaterial.prototype.isReady = function (mesh) {
  18556. for (var index = 0; index < this.subMaterials.length; index++) {
  18557. var subMaterial = this.subMaterials[index];
  18558. if (subMaterial) {
  18559. if (!this.subMaterials[index].isReady(mesh)) {
  18560. return false;
  18561. }
  18562. }
  18563. }
  18564. return true;
  18565. };
  18566. MultiMaterial.prototype.clone = function (name) {
  18567. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18568. for (var index = 0; index < this.subMaterials.length; index++) {
  18569. var subMaterial = this.subMaterials[index];
  18570. newMultiMaterial.subMaterials.push(subMaterial);
  18571. }
  18572. return newMultiMaterial;
  18573. };
  18574. return MultiMaterial;
  18575. })(BABYLON.Material);
  18576. BABYLON.MultiMaterial = MultiMaterial;
  18577. })(BABYLON || (BABYLON = {}));
  18578. //# sourceMappingURL=babylon.multiMaterial.js.map
  18579. var BABYLON;
  18580. (function (BABYLON) {
  18581. var SceneLoader = (function () {
  18582. function SceneLoader() {
  18583. }
  18584. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18585. get: function () {
  18586. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18587. },
  18588. set: function (value) {
  18589. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18590. },
  18591. enumerable: true,
  18592. configurable: true
  18593. });
  18594. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18595. get: function () {
  18596. return SceneLoader._ShowLoadingScreen;
  18597. },
  18598. set: function (value) {
  18599. SceneLoader._ShowLoadingScreen = value;
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18605. var dotPosition = sceneFilename.lastIndexOf(".");
  18606. var queryStringPosition = sceneFilename.indexOf("?");
  18607. if (queryStringPosition === -1) {
  18608. queryStringPosition = sceneFilename.length;
  18609. }
  18610. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18611. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18612. var plugin = this._registeredPlugins[index];
  18613. if (plugin.extensions.indexOf(extension) !== -1) {
  18614. return plugin;
  18615. }
  18616. }
  18617. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18618. };
  18619. // Public functions
  18620. SceneLoader.RegisterPlugin = function (plugin) {
  18621. plugin.extensions = plugin.extensions.toLowerCase();
  18622. SceneLoader._registeredPlugins.push(plugin);
  18623. };
  18624. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18625. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18626. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18627. return;
  18628. }
  18629. var loadingToken = {};
  18630. scene._addPendingData(loadingToken);
  18631. var manifestChecked = function (success) {
  18632. scene.database = database;
  18633. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18634. var importMeshFromData = function (data) {
  18635. var meshes = [];
  18636. var particleSystems = [];
  18637. var skeletons = [];
  18638. try {
  18639. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18640. if (onerror) {
  18641. onerror(scene, 'unable to load the scene');
  18642. }
  18643. scene._removePendingData(loadingToken);
  18644. return;
  18645. }
  18646. }
  18647. catch (e) {
  18648. if (onerror) {
  18649. onerror(scene, e);
  18650. }
  18651. scene._removePendingData(loadingToken);
  18652. return;
  18653. }
  18654. if (onsuccess) {
  18655. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18656. onsuccess(meshes, particleSystems, skeletons);
  18657. scene._removePendingData(loadingToken);
  18658. }
  18659. };
  18660. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18661. // Direct load
  18662. importMeshFromData(sceneFilename.substr(5));
  18663. return;
  18664. }
  18665. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18666. importMeshFromData(data);
  18667. }, progressCallBack, database);
  18668. };
  18669. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18670. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18671. };
  18672. /**
  18673. * Load a scene
  18674. * @param rootUrl a string that defines the root url for scene and resources
  18675. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18676. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18677. */
  18678. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18679. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18680. };
  18681. /**
  18682. * Append a scene
  18683. * @param rootUrl a string that defines the root url for scene and resources
  18684. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18685. * @param scene is the instance of BABYLON.Scene to append to
  18686. */
  18687. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18688. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18689. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18690. return;
  18691. }
  18692. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18693. var database;
  18694. var loadingToken = {};
  18695. scene._addPendingData(loadingToken);
  18696. if (SceneLoader.ShowLoadingScreen) {
  18697. scene.getEngine().displayLoadingUI();
  18698. }
  18699. var loadSceneFromData = function (data) {
  18700. scene.database = database;
  18701. if (!plugin.load(scene, data, rootUrl)) {
  18702. if (onerror) {
  18703. onerror(scene);
  18704. }
  18705. scene._removePendingData(loadingToken);
  18706. scene.getEngine().hideLoadingUI();
  18707. return;
  18708. }
  18709. if (onsuccess) {
  18710. onsuccess(scene);
  18711. }
  18712. scene._removePendingData(loadingToken);
  18713. if (SceneLoader.ShowLoadingScreen) {
  18714. scene.executeWhenReady(function () {
  18715. scene.getEngine().hideLoadingUI();
  18716. });
  18717. }
  18718. };
  18719. var manifestChecked = function (success) {
  18720. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18721. };
  18722. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18723. // Direct load
  18724. loadSceneFromData(sceneFilename.substr(5));
  18725. return;
  18726. }
  18727. if (rootUrl.indexOf("file:") === -1) {
  18728. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18729. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18730. }
  18731. else {
  18732. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18733. }
  18734. };
  18735. // Flags
  18736. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18737. SceneLoader._ShowLoadingScreen = true;
  18738. // Members
  18739. SceneLoader._registeredPlugins = new Array();
  18740. return SceneLoader;
  18741. })();
  18742. BABYLON.SceneLoader = SceneLoader;
  18743. ;
  18744. })(BABYLON || (BABYLON = {}));
  18745. //# sourceMappingURL=babylon.sceneLoader.js.map
  18746. var BABYLON;
  18747. (function (BABYLON) {
  18748. var Internals;
  18749. (function (Internals) {
  18750. var checkColors4 = function (colors, count) {
  18751. // Check if color3 was used
  18752. if (colors.length === count * 3) {
  18753. var colors4 = [];
  18754. for (var index = 0; index < colors.length; index += 3) {
  18755. var newIndex = (index / 3) * 4;
  18756. colors4[newIndex] = colors[index];
  18757. colors4[newIndex + 1] = colors[index + 1];
  18758. colors4[newIndex + 2] = colors[index + 2];
  18759. colors4[newIndex + 3] = 1.0;
  18760. }
  18761. return colors4;
  18762. }
  18763. return colors;
  18764. };
  18765. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18766. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18767. texture.name = parsedTexture.name;
  18768. texture.hasAlpha = parsedTexture.hasAlpha;
  18769. texture.level = parsedTexture.level;
  18770. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18771. return texture;
  18772. };
  18773. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18774. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18775. return null;
  18776. }
  18777. if (parsedTexture.isCube) {
  18778. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18779. }
  18780. var texture;
  18781. if (parsedTexture.mirrorPlane) {
  18782. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18783. texture._waitingRenderList = parsedTexture.renderList;
  18784. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18785. }
  18786. else if (parsedTexture.isRenderTarget) {
  18787. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18788. texture._waitingRenderList = parsedTexture.renderList;
  18789. }
  18790. else {
  18791. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18792. }
  18793. texture.name = parsedTexture.name;
  18794. texture.hasAlpha = parsedTexture.hasAlpha;
  18795. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18796. texture.level = parsedTexture.level;
  18797. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18798. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18799. texture.uOffset = parsedTexture.uOffset;
  18800. texture.vOffset = parsedTexture.vOffset;
  18801. texture.uScale = parsedTexture.uScale;
  18802. texture.vScale = parsedTexture.vScale;
  18803. texture.uAng = parsedTexture.uAng;
  18804. texture.vAng = parsedTexture.vAng;
  18805. texture.wAng = parsedTexture.wAng;
  18806. texture.wrapU = parsedTexture.wrapU;
  18807. texture.wrapV = parsedTexture.wrapV;
  18808. // Animations
  18809. if (parsedTexture.animations) {
  18810. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18811. var parsedAnimation = parsedTexture.animations[animationIndex];
  18812. texture.animations.push(parseAnimation(parsedAnimation));
  18813. }
  18814. }
  18815. return texture;
  18816. };
  18817. var parseSkeleton = function (parsedSkeleton, scene) {
  18818. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18819. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18820. var parsedBone = parsedSkeleton.bones[index];
  18821. var parentBone = null;
  18822. if (parsedBone.parentBoneIndex > -1) {
  18823. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18824. }
  18825. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18826. if (parsedBone.animation) {
  18827. bone.animations.push(parseAnimation(parsedBone.animation));
  18828. }
  18829. }
  18830. return skeleton;
  18831. };
  18832. var parseFresnelParameters = function (parsedFresnelParameters) {
  18833. var fresnelParameters = new BABYLON.FresnelParameters();
  18834. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18835. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18836. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18837. fresnelParameters.bias = parsedFresnelParameters.bias;
  18838. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18839. return fresnelParameters;
  18840. };
  18841. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18842. var material;
  18843. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18844. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18845. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18846. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18847. material.specularPower = parsedMaterial.specularPower;
  18848. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18849. material.alpha = parsedMaterial.alpha;
  18850. material.id = parsedMaterial.id;
  18851. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18852. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18853. material.wireframe = parsedMaterial.wireframe;
  18854. if (parsedMaterial.diffuseTexture) {
  18855. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18856. }
  18857. if (parsedMaterial.diffuseFresnelParameters) {
  18858. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18859. }
  18860. if (parsedMaterial.ambientTexture) {
  18861. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18862. }
  18863. if (parsedMaterial.opacityTexture) {
  18864. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18865. }
  18866. if (parsedMaterial.opacityFresnelParameters) {
  18867. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18868. }
  18869. if (parsedMaterial.reflectionTexture) {
  18870. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18871. }
  18872. if (parsedMaterial.reflectionFresnelParameters) {
  18873. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18874. }
  18875. if (parsedMaterial.emissiveTexture) {
  18876. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18877. }
  18878. if (parsedMaterial.emissiveFresnelParameters) {
  18879. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18880. }
  18881. if (parsedMaterial.specularTexture) {
  18882. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18883. }
  18884. if (parsedMaterial.bumpTexture) {
  18885. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18886. }
  18887. return material;
  18888. };
  18889. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18890. for (var index = 0; index < parsedData.materials.length; index++) {
  18891. var parsedMaterial = parsedData.materials[index];
  18892. if (parsedMaterial.id === id) {
  18893. return parseMaterial(parsedMaterial, scene, rootUrl);
  18894. }
  18895. }
  18896. return null;
  18897. };
  18898. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18899. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18900. multiMaterial.id = parsedMultiMaterial.id;
  18901. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18902. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18903. var subMatId = parsedMultiMaterial.materials[matIndex];
  18904. if (subMatId) {
  18905. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18906. }
  18907. else {
  18908. multiMaterial.subMaterials.push(null);
  18909. }
  18910. }
  18911. return multiMaterial;
  18912. };
  18913. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18914. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18915. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18916. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18917. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18918. var parsedFlare = parsedLensFlareSystem.flares[index];
  18919. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18920. }
  18921. return lensFlareSystem;
  18922. };
  18923. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18924. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18925. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18926. if (parsedParticleSystem.textureName) {
  18927. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18928. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18929. }
  18930. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18931. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18932. particleSystem.minSize = parsedParticleSystem.minSize;
  18933. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18934. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18935. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18936. particleSystem.emitter = emitter;
  18937. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18938. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18939. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18940. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18941. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18942. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18943. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18944. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18945. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18946. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18947. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18948. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18949. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18950. particleSystem.start();
  18951. return particleSystem;
  18952. };
  18953. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18954. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18955. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18956. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18957. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18958. shadowGenerator.getShadowMap().renderList.push(mesh);
  18959. }
  18960. if (parsedShadowGenerator.usePoissonSampling) {
  18961. shadowGenerator.usePoissonSampling = true;
  18962. }
  18963. else if (parsedShadowGenerator.useVarianceShadowMap) {
  18964. shadowGenerator.useVarianceShadowMap = true;
  18965. }
  18966. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  18967. shadowGenerator.useBlurVarianceShadowMap = true;
  18968. if (parsedShadowGenerator.blurScale) {
  18969. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  18970. }
  18971. if (parsedShadowGenerator.blurBoxOffset) {
  18972. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  18973. }
  18974. }
  18975. if (parsedShadowGenerator.bias !== undefined) {
  18976. shadowGenerator.bias = parsedShadowGenerator.bias;
  18977. }
  18978. return shadowGenerator;
  18979. };
  18980. var parseAnimation = function (parsedAnimation) {
  18981. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18982. var dataType = parsedAnimation.dataType;
  18983. var keys = [];
  18984. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18985. var key = parsedAnimation.keys[index];
  18986. var data;
  18987. switch (dataType) {
  18988. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18989. data = key.values[0];
  18990. break;
  18991. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18992. data = BABYLON.Quaternion.FromArray(key.values);
  18993. break;
  18994. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18995. data = BABYLON.Matrix.FromArray(key.values);
  18996. break;
  18997. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18998. default:
  18999. data = BABYLON.Vector3.FromArray(key.values);
  19000. break;
  19001. }
  19002. keys.push({
  19003. frame: key.frame,
  19004. value: data
  19005. });
  19006. }
  19007. animation.setKeys(keys);
  19008. return animation;
  19009. };
  19010. var parseLight = function (parsedLight, scene) {
  19011. var light;
  19012. switch (parsedLight.type) {
  19013. case 0:
  19014. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19015. break;
  19016. case 1:
  19017. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19018. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19019. break;
  19020. case 2:
  19021. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19022. break;
  19023. case 3:
  19024. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19025. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19026. break;
  19027. }
  19028. light.id = parsedLight.id;
  19029. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19030. if (parsedLight.intensity !== undefined) {
  19031. light.intensity = parsedLight.intensity;
  19032. }
  19033. if (parsedLight.range) {
  19034. light.range = parsedLight.range;
  19035. }
  19036. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19037. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19038. if (parsedLight.excludedMeshesIds) {
  19039. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19040. }
  19041. // Parent
  19042. if (parsedLight.parentId) {
  19043. light._waitingParentId = parsedLight.parentId;
  19044. }
  19045. if (parsedLight.includedOnlyMeshesIds) {
  19046. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19047. }
  19048. // Animations
  19049. if (parsedLight.animations) {
  19050. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19051. var parsedAnimation = parsedLight.animations[animationIndex];
  19052. light.animations.push(parseAnimation(parsedAnimation));
  19053. }
  19054. }
  19055. if (parsedLight.autoAnimate) {
  19056. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19057. }
  19058. };
  19059. var parseCamera = function (parsedCamera, scene) {
  19060. var camera;
  19061. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19062. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19063. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19064. var alpha = parsedCamera.alpha;
  19065. var beta = parsedCamera.beta;
  19066. var radius = parsedCamera.radius;
  19067. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19068. var interaxial_distance = parsedCamera.interaxial_distance;
  19069. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19070. }
  19071. else {
  19072. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19073. }
  19074. }
  19075. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19076. interaxial_distance = parsedCamera.interaxial_distance;
  19077. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19078. }
  19079. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19080. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19081. }
  19082. else if (parsedCamera.type === "FollowCamera") {
  19083. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19084. camera.heightOffset = parsedCamera.heightOffset;
  19085. camera.radius = parsedCamera.radius;
  19086. camera.rotationOffset = parsedCamera.rotationOffset;
  19087. if (lockedTargetMesh)
  19088. camera.target = lockedTargetMesh;
  19089. }
  19090. else if (parsedCamera.type === "GamepadCamera") {
  19091. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19092. }
  19093. else if (parsedCamera.type === "TouchCamera") {
  19094. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19095. }
  19096. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19097. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19098. }
  19099. else if (parsedCamera.type === "WebVRFreeCamera") {
  19100. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19101. }
  19102. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19103. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19104. }
  19105. else {
  19106. // Free Camera is the default value
  19107. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19108. }
  19109. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19110. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19111. camera.lockedTarget = lockedTargetMesh;
  19112. }
  19113. camera.id = parsedCamera.id;
  19114. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19115. // Parent
  19116. if (parsedCamera.parentId) {
  19117. camera._waitingParentId = parsedCamera.parentId;
  19118. }
  19119. // Target
  19120. if (parsedCamera.target) {
  19121. if (camera.setTarget) {
  19122. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19123. }
  19124. else {
  19125. //For ArcRotate
  19126. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19127. }
  19128. }
  19129. else {
  19130. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19131. }
  19132. camera.fov = parsedCamera.fov;
  19133. camera.minZ = parsedCamera.minZ;
  19134. camera.maxZ = parsedCamera.maxZ;
  19135. camera.speed = parsedCamera.speed;
  19136. camera.inertia = parsedCamera.inertia;
  19137. camera.checkCollisions = parsedCamera.checkCollisions;
  19138. camera.applyGravity = parsedCamera.applyGravity;
  19139. if (parsedCamera.ellipsoid) {
  19140. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19141. }
  19142. // Animations
  19143. if (parsedCamera.animations) {
  19144. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19145. var parsedAnimation = parsedCamera.animations[animationIndex];
  19146. camera.animations.push(parseAnimation(parsedAnimation));
  19147. }
  19148. }
  19149. if (parsedCamera.autoAnimate) {
  19150. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19151. }
  19152. // Layer Mask
  19153. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19154. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19155. }
  19156. else {
  19157. camera.layerMask = 0xFFFFFFFF;
  19158. }
  19159. return camera;
  19160. };
  19161. var parseGeometry = function (parsedGeometry, scene) {
  19162. var id = parsedGeometry.id;
  19163. return scene.getGeometryByID(id);
  19164. };
  19165. var parseBox = function (parsedBox, scene) {
  19166. if (parseGeometry(parsedBox, scene)) {
  19167. return null; // null since geometry could be something else than a box...
  19168. }
  19169. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19170. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19171. scene.pushGeometry(box, true);
  19172. return box;
  19173. };
  19174. var parseSphere = function (parsedSphere, scene) {
  19175. if (parseGeometry(parsedSphere, scene)) {
  19176. return null; // null since geometry could be something else than a sphere...
  19177. }
  19178. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19179. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19180. scene.pushGeometry(sphere, true);
  19181. return sphere;
  19182. };
  19183. var parseCylinder = function (parsedCylinder, scene) {
  19184. if (parseGeometry(parsedCylinder, scene)) {
  19185. return null; // null since geometry could be something else than a cylinder...
  19186. }
  19187. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19188. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19189. scene.pushGeometry(cylinder, true);
  19190. return cylinder;
  19191. };
  19192. var parseTorus = function (parsedTorus, scene) {
  19193. if (parseGeometry(parsedTorus, scene)) {
  19194. return null; // null since geometry could be something else than a torus...
  19195. }
  19196. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19197. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19198. scene.pushGeometry(torus, true);
  19199. return torus;
  19200. };
  19201. var parseGround = function (parsedGround, scene) {
  19202. if (parseGeometry(parsedGround, scene)) {
  19203. return null; // null since geometry could be something else than a ground...
  19204. }
  19205. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19206. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19207. scene.pushGeometry(ground, true);
  19208. return ground;
  19209. };
  19210. var parsePlane = function (parsedPlane, scene) {
  19211. if (parseGeometry(parsedPlane, scene)) {
  19212. return null; // null since geometry could be something else than a plane...
  19213. }
  19214. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19215. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19216. scene.pushGeometry(plane, true);
  19217. return plane;
  19218. };
  19219. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19220. if (parseGeometry(parsedTorusKnot, scene)) {
  19221. return null; // null since geometry could be something else than a torusKnot...
  19222. }
  19223. 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);
  19224. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19225. scene.pushGeometry(torusKnot, true);
  19226. return torusKnot;
  19227. };
  19228. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19229. if (parseGeometry(parsedVertexData, scene)) {
  19230. return null; // null since geometry could be a primitive
  19231. }
  19232. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19233. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19234. if (parsedVertexData.delayLoadingFile) {
  19235. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19236. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19237. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19238. geometry._delayInfo = [];
  19239. if (parsedVertexData.hasUVs) {
  19240. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19241. }
  19242. if (parsedVertexData.hasUVs2) {
  19243. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19244. }
  19245. if (parsedVertexData.hasColors) {
  19246. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19247. }
  19248. if (parsedVertexData.hasMatricesIndices) {
  19249. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19250. }
  19251. if (parsedVertexData.hasMatricesWeights) {
  19252. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19253. }
  19254. geometry._delayLoadingFunction = importVertexData;
  19255. }
  19256. else {
  19257. importVertexData(parsedVertexData, geometry);
  19258. }
  19259. scene.pushGeometry(geometry, true);
  19260. return geometry;
  19261. };
  19262. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19263. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19264. mesh.id = parsedMesh.id;
  19265. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19266. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19267. if (parsedMesh.rotationQuaternion) {
  19268. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19269. }
  19270. else if (parsedMesh.rotation) {
  19271. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19272. }
  19273. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19274. if (parsedMesh.localMatrix) {
  19275. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19276. }
  19277. else if (parsedMesh.pivotMatrix) {
  19278. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19279. }
  19280. mesh.setEnabled(parsedMesh.isEnabled);
  19281. mesh.isVisible = parsedMesh.isVisible;
  19282. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19283. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19284. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19285. if (parsedMesh.applyFog !== undefined) {
  19286. mesh.applyFog = parsedMesh.applyFog;
  19287. }
  19288. if (parsedMesh.pickable !== undefined) {
  19289. mesh.isPickable = parsedMesh.pickable;
  19290. }
  19291. if (parsedMesh.alphaIndex !== undefined) {
  19292. mesh.alphaIndex = parsedMesh.alphaIndex;
  19293. }
  19294. mesh.receiveShadows = parsedMesh.receiveShadows;
  19295. mesh.billboardMode = parsedMesh.billboardMode;
  19296. if (parsedMesh.visibility !== undefined) {
  19297. mesh.visibility = parsedMesh.visibility;
  19298. }
  19299. mesh.checkCollisions = parsedMesh.checkCollisions;
  19300. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19301. // Parent
  19302. if (parsedMesh.parentId) {
  19303. mesh._waitingParentId = parsedMesh.parentId;
  19304. }
  19305. // Actions
  19306. if (parsedMesh.actions !== undefined) {
  19307. mesh._waitingActions = parsedMesh.actions;
  19308. }
  19309. // Geometry
  19310. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19311. if (parsedMesh.delayLoadingFile) {
  19312. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19313. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19314. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19315. if (parsedMesh._binaryInfo) {
  19316. mesh._binaryInfo = parsedMesh._binaryInfo;
  19317. }
  19318. mesh._delayInfo = [];
  19319. if (parsedMesh.hasUVs) {
  19320. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19321. }
  19322. if (parsedMesh.hasUVs2) {
  19323. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19324. }
  19325. if (parsedMesh.hasColors) {
  19326. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19327. }
  19328. if (parsedMesh.hasMatricesIndices) {
  19329. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19330. }
  19331. if (parsedMesh.hasMatricesWeights) {
  19332. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19333. }
  19334. mesh._delayLoadingFunction = importGeometry;
  19335. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19336. mesh._checkDelayState();
  19337. }
  19338. }
  19339. else {
  19340. importGeometry(parsedMesh, mesh);
  19341. }
  19342. // Material
  19343. if (parsedMesh.materialId) {
  19344. mesh.setMaterialByID(parsedMesh.materialId);
  19345. }
  19346. else {
  19347. mesh.material = null;
  19348. }
  19349. // Skeleton
  19350. if (parsedMesh.skeletonId > -1) {
  19351. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19352. }
  19353. // Physics
  19354. if (parsedMesh.physicsImpostor) {
  19355. if (!scene.isPhysicsEnabled()) {
  19356. scene.enablePhysics();
  19357. }
  19358. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19359. }
  19360. // Animations
  19361. if (parsedMesh.animations) {
  19362. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19363. var parsedAnimation = parsedMesh.animations[animationIndex];
  19364. mesh.animations.push(parseAnimation(parsedAnimation));
  19365. }
  19366. }
  19367. if (parsedMesh.autoAnimate) {
  19368. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19369. }
  19370. // Layer Mask
  19371. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19372. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19373. }
  19374. else {
  19375. mesh.layerMask = 0xFFFFFFFF;
  19376. }
  19377. // Instances
  19378. if (parsedMesh.instances) {
  19379. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19380. var parsedInstance = parsedMesh.instances[index];
  19381. var instance = mesh.createInstance(parsedInstance.name);
  19382. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19383. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19384. if (parsedInstance.rotationQuaternion) {
  19385. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19386. }
  19387. else if (parsedInstance.rotation) {
  19388. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19389. }
  19390. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19391. instance.checkCollisions = mesh.checkCollisions;
  19392. if (parsedMesh.animations) {
  19393. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19394. parsedAnimation = parsedMesh.animations[animationIndex];
  19395. instance.animations.push(parseAnimation(parsedAnimation));
  19396. }
  19397. }
  19398. }
  19399. }
  19400. return mesh;
  19401. };
  19402. var parseActions = function (parsedActions, object, scene) {
  19403. var actionManager = new BABYLON.ActionManager(scene);
  19404. if (object === null)
  19405. scene.actionManager = actionManager;
  19406. else
  19407. object.actionManager = actionManager;
  19408. // instanciate a new object
  19409. var instanciate = function (name, params) {
  19410. var newInstance = Object.create(BABYLON[name].prototype);
  19411. newInstance.constructor.apply(newInstance, params);
  19412. return newInstance;
  19413. };
  19414. var parseParameter = function (name, value, target, propertyPath) {
  19415. if (propertyPath === null) {
  19416. // String, boolean or float
  19417. var floatValue = parseFloat(value);
  19418. if (value === "true" || value === "false")
  19419. return value === "true";
  19420. else
  19421. return isNaN(floatValue) ? value : floatValue;
  19422. }
  19423. var effectiveTarget = propertyPath.split(".");
  19424. var values = value.split(",");
  19425. // Get effective Target
  19426. for (var i = 0; i < effectiveTarget.length; i++) {
  19427. target = target[effectiveTarget[i]];
  19428. }
  19429. // Return appropriate value with its type
  19430. if (typeof (target) === "boolean")
  19431. return values[0] === "true";
  19432. if (typeof (target) === "string")
  19433. return values[0];
  19434. // Parameters with multiple values such as Vector3 etc.
  19435. var split = new Array();
  19436. for (var i = 0; i < values.length; i++)
  19437. split.push(parseFloat(values[i]));
  19438. if (target instanceof BABYLON.Vector3)
  19439. return BABYLON.Vector3.FromArray(split);
  19440. if (target instanceof BABYLON.Vector4)
  19441. return BABYLON.Vector4.FromArray(split);
  19442. if (target instanceof BABYLON.Color3)
  19443. return BABYLON.Color3.FromArray(split);
  19444. if (target instanceof BABYLON.Color4)
  19445. return BABYLON.Color4.FromArray(split);
  19446. return parseFloat(values[0]);
  19447. };
  19448. // traverse graph per trigger
  19449. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19450. if (combineArray === void 0) { combineArray = null; }
  19451. if (parsedAction.detached)
  19452. return;
  19453. var parameters = new Array();
  19454. var target = null;
  19455. var propertyPath = null;
  19456. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19457. // Parameters
  19458. if (parsedAction.type === 2)
  19459. parameters.push(actionManager);
  19460. else
  19461. parameters.push(trigger);
  19462. if (combine) {
  19463. var actions = new Array();
  19464. for (var j = 0; j < parsedAction.combine.length; j++) {
  19465. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19466. }
  19467. parameters.push(actions);
  19468. }
  19469. else {
  19470. for (var i = 0; i < parsedAction.properties.length; i++) {
  19471. var value = parsedAction.properties[i].value;
  19472. var name = parsedAction.properties[i].name;
  19473. var targetType = parsedAction.properties[i].targetType;
  19474. if (name === "target")
  19475. if (targetType !== null && targetType === "SceneProperties")
  19476. value = target = scene;
  19477. else
  19478. value = target = scene.getNodeByName(value);
  19479. else if (name === "parent")
  19480. value = scene.getNodeByName(value);
  19481. else if (name === "sound")
  19482. value = scene.getSoundByName(value);
  19483. else if (name !== "propertyPath") {
  19484. if (parsedAction.type === 2 && name === "operator")
  19485. value = BABYLON.ValueCondition[value];
  19486. else
  19487. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19488. }
  19489. else {
  19490. propertyPath = value;
  19491. }
  19492. parameters.push(value);
  19493. }
  19494. }
  19495. if (combineArray === null) {
  19496. parameters.push(condition);
  19497. }
  19498. else {
  19499. parameters.push(null);
  19500. }
  19501. // If interpolate value action
  19502. if (parsedAction.name === "InterpolateValueAction") {
  19503. var param = parameters[parameters.length - 2];
  19504. parameters[parameters.length - 1] = param;
  19505. parameters[parameters.length - 2] = condition;
  19506. }
  19507. // Action or condition(s) and not CombineAction
  19508. var newAction = instanciate(parsedAction.name, parameters);
  19509. if (combineArray === null) {
  19510. if (newAction instanceof BABYLON.Condition) {
  19511. condition = newAction;
  19512. newAction = action;
  19513. }
  19514. else {
  19515. condition = null;
  19516. if (action)
  19517. action.then(newAction);
  19518. else
  19519. actionManager.registerAction(newAction);
  19520. }
  19521. }
  19522. else {
  19523. combineArray.push(newAction);
  19524. }
  19525. for (var i = 0; i < parsedAction.children.length; i++)
  19526. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19527. };
  19528. // triggers
  19529. for (var i = 0; i < parsedActions.children.length; i++) {
  19530. var triggerParams;
  19531. var trigger = parsedActions.children[i];
  19532. if (trigger.properties.length > 0) {
  19533. var param = trigger.properties[0].value;
  19534. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19535. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19536. }
  19537. else
  19538. triggerParams = BABYLON.ActionManager[trigger.name];
  19539. for (var j = 0; j < trigger.children.length; j++) {
  19540. if (!trigger.detached)
  19541. traverse(trigger.children[j], triggerParams, null, null);
  19542. }
  19543. }
  19544. };
  19545. var parseSound = function (parsedSound, scene, rootUrl) {
  19546. var soundName = parsedSound.name;
  19547. var soundUrl = rootUrl + soundName;
  19548. var options = {
  19549. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  19550. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  19551. rolloffFactor: parsedSound.rolloffFactor,
  19552. refDistance: parsedSound.refDistance,
  19553. distanceModel: parsedSound.distanceModel,
  19554. playbackRate: parsedSound.playbackRate
  19555. };
  19556. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  19557. scene._addPendingData(newSound);
  19558. if (parsedSound.position) {
  19559. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19560. newSound.setPosition(soundPosition);
  19561. }
  19562. if (parsedSound.isDirectional) {
  19563. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19564. if (parsedSound.localDirectionToMesh) {
  19565. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19566. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19567. }
  19568. }
  19569. if (parsedSound.connectedMeshId) {
  19570. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19571. if (connectedMesh) {
  19572. newSound.attachToMesh(connectedMesh);
  19573. }
  19574. }
  19575. };
  19576. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19577. names = (names instanceof Array) ? names : [names];
  19578. for (var i in names) {
  19579. if (mesh.name === names[i]) {
  19580. hierarchyIds.push(mesh.id);
  19581. return true;
  19582. }
  19583. }
  19584. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19585. hierarchyIds.push(mesh.id);
  19586. return true;
  19587. }
  19588. return false;
  19589. };
  19590. var importVertexData = function (parsedVertexData, geometry) {
  19591. var vertexData = new BABYLON.VertexData();
  19592. // positions
  19593. var positions = parsedVertexData.positions;
  19594. if (positions) {
  19595. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19596. }
  19597. // normals
  19598. var normals = parsedVertexData.normals;
  19599. if (normals) {
  19600. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19601. }
  19602. // uvs
  19603. var uvs = parsedVertexData.uvs;
  19604. if (uvs) {
  19605. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19606. }
  19607. // uv2s
  19608. var uv2s = parsedVertexData.uv2s;
  19609. if (uv2s) {
  19610. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19611. }
  19612. // colors
  19613. var colors = parsedVertexData.colors;
  19614. if (colors) {
  19615. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19616. }
  19617. // matricesIndices
  19618. var matricesIndices = parsedVertexData.matricesIndices;
  19619. if (matricesIndices) {
  19620. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19621. }
  19622. // matricesWeights
  19623. var matricesWeights = parsedVertexData.matricesWeights;
  19624. if (matricesWeights) {
  19625. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19626. }
  19627. // indices
  19628. var indices = parsedVertexData.indices;
  19629. if (indices) {
  19630. vertexData.indices = indices;
  19631. }
  19632. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19633. };
  19634. var importGeometry = function (parsedGeometry, mesh) {
  19635. var scene = mesh.getScene();
  19636. // Geometry
  19637. var geometryId = parsedGeometry.geometryId;
  19638. if (geometryId) {
  19639. var geometry = scene.getGeometryByID(geometryId);
  19640. if (geometry) {
  19641. geometry.applyToMesh(mesh);
  19642. }
  19643. }
  19644. else if (parsedGeometry instanceof ArrayBuffer) {
  19645. var binaryInfo = mesh._binaryInfo;
  19646. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19647. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19648. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19649. }
  19650. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19651. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19652. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19653. }
  19654. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19655. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19656. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19657. }
  19658. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19659. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19660. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19661. }
  19662. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19663. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19664. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  19665. }
  19666. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19667. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19668. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19669. }
  19670. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19671. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19672. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19673. }
  19674. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19675. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19676. mesh.setIndices(indicesData);
  19677. }
  19678. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19679. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19680. mesh.subMeshes = [];
  19681. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19682. var materialIndex = subMeshesData[(i * 5) + 0];
  19683. var verticesStart = subMeshesData[(i * 5) + 1];
  19684. var verticesCount = subMeshesData[(i * 5) + 2];
  19685. var indexStart = subMeshesData[(i * 5) + 3];
  19686. var indexCount = subMeshesData[(i * 5) + 4];
  19687. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19688. }
  19689. }
  19690. }
  19691. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19692. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19693. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19694. if (parsedGeometry.uvs) {
  19695. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19696. }
  19697. if (parsedGeometry.uvs2) {
  19698. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19699. }
  19700. if (parsedGeometry.colors) {
  19701. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19702. }
  19703. if (parsedGeometry.matricesIndices) {
  19704. if (!parsedGeometry.matricesIndices._isExpanded) {
  19705. var floatIndices = [];
  19706. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19707. var matricesIndex = parsedGeometry.matricesIndices[i];
  19708. floatIndices.push(matricesIndex & 0x000000FF);
  19709. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19710. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19711. floatIndices.push(matricesIndex >> 24);
  19712. }
  19713. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19714. }
  19715. else {
  19716. delete parsedGeometry.matricesIndices._isExpanded;
  19717. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19718. }
  19719. }
  19720. if (parsedGeometry.matricesWeights) {
  19721. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19722. }
  19723. mesh.setIndices(parsedGeometry.indices);
  19724. // SubMeshes
  19725. if (parsedGeometry.subMeshes) {
  19726. mesh.subMeshes = [];
  19727. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19728. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19729. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19730. }
  19731. }
  19732. }
  19733. // Flat shading
  19734. if (mesh._shouldGenerateFlatShading) {
  19735. mesh.convertToFlatShadedMesh();
  19736. delete mesh._shouldGenerateFlatShading;
  19737. }
  19738. // Update
  19739. mesh.computeWorldMatrix(true);
  19740. // Octree
  19741. if (scene._selectionOctree) {
  19742. scene._selectionOctree.addMesh(mesh);
  19743. }
  19744. };
  19745. BABYLON.SceneLoader.RegisterPlugin({
  19746. extensions: ".babylon",
  19747. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19748. var parsedData = JSON.parse(data);
  19749. var loadedSkeletonsIds = [];
  19750. var loadedMaterialsIds = [];
  19751. var hierarchyIds = [];
  19752. for (var index = 0; index < parsedData.meshes.length; index++) {
  19753. var parsedMesh = parsedData.meshes[index];
  19754. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19755. if (meshesNames instanceof Array) {
  19756. // Remove found mesh name from list.
  19757. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19758. }
  19759. //Geometry?
  19760. if (parsedMesh.geometryId) {
  19761. //does the file contain geometries?
  19762. if (parsedData.geometries) {
  19763. //find the correct geometry and add it to the scene
  19764. var found = false;
  19765. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19766. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19767. return;
  19768. }
  19769. else {
  19770. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19771. if (parsedGeometryData.id == parsedMesh.geometryId) {
  19772. switch (geometryType) {
  19773. case "boxes":
  19774. parseBox(parsedGeometryData, scene);
  19775. break;
  19776. case "spheres":
  19777. parseSphere(parsedGeometryData, scene);
  19778. break;
  19779. case "cylinders":
  19780. parseCylinder(parsedGeometryData, scene);
  19781. break;
  19782. case "toruses":
  19783. parseTorus(parsedGeometryData, scene);
  19784. break;
  19785. case "grounds":
  19786. parseGround(parsedGeometryData, scene);
  19787. break;
  19788. case "planes":
  19789. parsePlane(parsedGeometryData, scene);
  19790. break;
  19791. case "torusKnots":
  19792. parseTorusKnot(parsedGeometryData, scene);
  19793. break;
  19794. case "vertexData":
  19795. parseVertexData(parsedGeometryData, scene, rootUrl);
  19796. break;
  19797. }
  19798. found = true;
  19799. }
  19800. });
  19801. }
  19802. });
  19803. }
  19804. }
  19805. // Material ?
  19806. if (parsedMesh.materialId) {
  19807. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19808. if (!materialFound) {
  19809. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19810. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19811. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19812. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19813. var subMatId = parsedMultiMaterial.materials[matIndex];
  19814. loadedMaterialsIds.push(subMatId);
  19815. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19816. }
  19817. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19818. parseMultiMaterial(parsedMultiMaterial, scene);
  19819. materialFound = true;
  19820. break;
  19821. }
  19822. }
  19823. }
  19824. if (!materialFound) {
  19825. loadedMaterialsIds.push(parsedMesh.materialId);
  19826. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19827. }
  19828. }
  19829. // Skeleton ?
  19830. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19831. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19832. if (!skeletonAlreadyLoaded) {
  19833. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19834. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19835. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19836. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19837. loadedSkeletonsIds.push(parsedSkeleton.id);
  19838. }
  19839. }
  19840. }
  19841. }
  19842. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19843. meshes.push(mesh);
  19844. }
  19845. }
  19846. // Connecting parents
  19847. for (index = 0; index < scene.meshes.length; index++) {
  19848. var currentMesh = scene.meshes[index];
  19849. if (currentMesh._waitingParentId) {
  19850. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19851. currentMesh._waitingParentId = undefined;
  19852. }
  19853. }
  19854. // Particles
  19855. if (parsedData.particleSystems) {
  19856. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19857. var parsedParticleSystem = parsedData.particleSystems[index];
  19858. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19859. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19860. }
  19861. }
  19862. }
  19863. return true;
  19864. },
  19865. load: function (scene, data, rootUrl) {
  19866. var parsedData = JSON.parse(data);
  19867. // Scene
  19868. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19869. scene.autoClear = parsedData.autoClear;
  19870. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19871. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19872. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19873. // Fog
  19874. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19875. scene.fogMode = parsedData.fogMode;
  19876. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19877. scene.fogStart = parsedData.fogStart;
  19878. scene.fogEnd = parsedData.fogEnd;
  19879. scene.fogDensity = parsedData.fogDensity;
  19880. }
  19881. // Lights
  19882. for (var index = 0; index < parsedData.lights.length; index++) {
  19883. var parsedLight = parsedData.lights[index];
  19884. parseLight(parsedLight, scene);
  19885. }
  19886. // Materials
  19887. if (parsedData.materials) {
  19888. for (index = 0; index < parsedData.materials.length; index++) {
  19889. var parsedMaterial = parsedData.materials[index];
  19890. parseMaterial(parsedMaterial, scene, rootUrl);
  19891. }
  19892. }
  19893. if (parsedData.multiMaterials) {
  19894. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19895. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19896. parseMultiMaterial(parsedMultiMaterial, scene);
  19897. }
  19898. }
  19899. // Skeletons
  19900. if (parsedData.skeletons) {
  19901. for (index = 0; index < parsedData.skeletons.length; index++) {
  19902. var parsedSkeleton = parsedData.skeletons[index];
  19903. parseSkeleton(parsedSkeleton, scene);
  19904. }
  19905. }
  19906. // Geometries
  19907. var geometries = parsedData.geometries;
  19908. if (geometries) {
  19909. // Boxes
  19910. var boxes = geometries.boxes;
  19911. if (boxes) {
  19912. for (index = 0; index < boxes.length; index++) {
  19913. var parsedBox = boxes[index];
  19914. parseBox(parsedBox, scene);
  19915. }
  19916. }
  19917. // Spheres
  19918. var spheres = geometries.spheres;
  19919. if (spheres) {
  19920. for (index = 0; index < spheres.length; index++) {
  19921. var parsedSphere = spheres[index];
  19922. parseSphere(parsedSphere, scene);
  19923. }
  19924. }
  19925. // Cylinders
  19926. var cylinders = geometries.cylinders;
  19927. if (cylinders) {
  19928. for (index = 0; index < cylinders.length; index++) {
  19929. var parsedCylinder = cylinders[index];
  19930. parseCylinder(parsedCylinder, scene);
  19931. }
  19932. }
  19933. // Toruses
  19934. var toruses = geometries.toruses;
  19935. if (toruses) {
  19936. for (index = 0; index < toruses.length; index++) {
  19937. var parsedTorus = toruses[index];
  19938. parseTorus(parsedTorus, scene);
  19939. }
  19940. }
  19941. // Grounds
  19942. var grounds = geometries.grounds;
  19943. if (grounds) {
  19944. for (index = 0; index < grounds.length; index++) {
  19945. var parsedGround = grounds[index];
  19946. parseGround(parsedGround, scene);
  19947. }
  19948. }
  19949. // Planes
  19950. var planes = geometries.planes;
  19951. if (planes) {
  19952. for (index = 0; index < planes.length; index++) {
  19953. var parsedPlane = planes[index];
  19954. parsePlane(parsedPlane, scene);
  19955. }
  19956. }
  19957. // TorusKnots
  19958. var torusKnots = geometries.torusKnots;
  19959. if (torusKnots) {
  19960. for (index = 0; index < torusKnots.length; index++) {
  19961. var parsedTorusKnot = torusKnots[index];
  19962. parseTorusKnot(parsedTorusKnot, scene);
  19963. }
  19964. }
  19965. // VertexData
  19966. var vertexData = geometries.vertexData;
  19967. if (vertexData) {
  19968. for (index = 0; index < vertexData.length; index++) {
  19969. var parsedVertexData = vertexData[index];
  19970. parseVertexData(parsedVertexData, scene, rootUrl);
  19971. }
  19972. }
  19973. }
  19974. // Meshes
  19975. for (index = 0; index < parsedData.meshes.length; index++) {
  19976. var parsedMesh = parsedData.meshes[index];
  19977. parseMesh(parsedMesh, scene, rootUrl);
  19978. }
  19979. // Cameras
  19980. for (index = 0; index < parsedData.cameras.length; index++) {
  19981. var parsedCamera = parsedData.cameras[index];
  19982. parseCamera(parsedCamera, scene);
  19983. }
  19984. if (parsedData.activeCameraID) {
  19985. scene.setActiveCameraByID(parsedData.activeCameraID);
  19986. }
  19987. // Browsing all the graph to connect the dots
  19988. for (index = 0; index < scene.cameras.length; index++) {
  19989. var camera = scene.cameras[index];
  19990. if (camera._waitingParentId) {
  19991. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19992. camera._waitingParentId = undefined;
  19993. }
  19994. }
  19995. for (index = 0; index < scene.lights.length; index++) {
  19996. var light = scene.lights[index];
  19997. if (light._waitingParentId) {
  19998. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19999. light._waitingParentId = undefined;
  20000. }
  20001. }
  20002. // Sounds
  20003. if (parsedData.sounds) {
  20004. for (index = 0; index < parsedData.sounds.length; index++) {
  20005. var parsedSound = parsedData.sounds[index];
  20006. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20007. parseSound(parsedSound, scene, rootUrl);
  20008. }
  20009. else {
  20010. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20011. }
  20012. }
  20013. }
  20014. // Connect parents & children and parse actions
  20015. for (index = 0; index < scene.meshes.length; index++) {
  20016. var mesh = scene.meshes[index];
  20017. if (mesh._waitingParentId) {
  20018. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20019. mesh._waitingParentId = undefined;
  20020. }
  20021. if (mesh._waitingActions) {
  20022. parseActions(mesh._waitingActions, mesh, scene);
  20023. mesh._waitingActions = undefined;
  20024. }
  20025. }
  20026. // Particles Systems
  20027. if (parsedData.particleSystems) {
  20028. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20029. var parsedParticleSystem = parsedData.particleSystems[index];
  20030. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20031. }
  20032. }
  20033. // Lens flares
  20034. if (parsedData.lensFlareSystems) {
  20035. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20036. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20037. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20038. }
  20039. }
  20040. // Shadows
  20041. if (parsedData.shadowGenerators) {
  20042. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20043. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20044. parseShadowGenerator(parsedShadowGenerator, scene);
  20045. }
  20046. }
  20047. // Actions (scene)
  20048. if (parsedData.actions) {
  20049. parseActions(parsedData.actions, null, scene);
  20050. }
  20051. // Finish
  20052. return true;
  20053. }
  20054. });
  20055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20056. })(BABYLON || (BABYLON = {}));
  20057. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  20058. var BABYLON;
  20059. (function (BABYLON) {
  20060. var SpriteManager = (function () {
  20061. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20063. this.name = name;
  20064. this.cellSize = cellSize;
  20065. this.sprites = new Array();
  20066. this.renderingGroupId = 0;
  20067. this.fogEnabled = true;
  20068. this._vertexDeclaration = [4, 4, 4, 4];
  20069. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20070. this._capacity = capacity;
  20071. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20072. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20073. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20074. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20075. this._scene = scene;
  20076. this._scene.spriteManagers.push(this);
  20077. // VBO
  20078. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20079. var indices = [];
  20080. var index = 0;
  20081. for (var count = 0; count < capacity; count++) {
  20082. indices.push(index);
  20083. indices.push(index + 1);
  20084. indices.push(index + 2);
  20085. indices.push(index);
  20086. indices.push(index + 2);
  20087. indices.push(index + 3);
  20088. index += 4;
  20089. }
  20090. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20091. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20092. // Effects
  20093. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20094. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20095. }
  20096. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20097. var arrayOffset = index * 16;
  20098. if (offsetX === 0)
  20099. offsetX = this._epsilon;
  20100. else if (offsetX === 1)
  20101. offsetX = 1 - this._epsilon;
  20102. if (offsetY === 0)
  20103. offsetY = this._epsilon;
  20104. else if (offsetY === 1)
  20105. offsetY = 1 - this._epsilon;
  20106. this._vertices[arrayOffset] = sprite.position.x;
  20107. this._vertices[arrayOffset + 1] = sprite.position.y;
  20108. this._vertices[arrayOffset + 2] = sprite.position.z;
  20109. this._vertices[arrayOffset + 3] = sprite.angle;
  20110. this._vertices[arrayOffset + 4] = sprite.width;
  20111. this._vertices[arrayOffset + 5] = sprite.height;
  20112. this._vertices[arrayOffset + 6] = offsetX;
  20113. this._vertices[arrayOffset + 7] = offsetY;
  20114. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20115. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20116. var offset = (sprite.cellIndex / rowSize) >> 0;
  20117. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20118. this._vertices[arrayOffset + 11] = offset;
  20119. // Color
  20120. this._vertices[arrayOffset + 12] = sprite.color.r;
  20121. this._vertices[arrayOffset + 13] = sprite.color.g;
  20122. this._vertices[arrayOffset + 14] = sprite.color.b;
  20123. this._vertices[arrayOffset + 15] = sprite.color.a;
  20124. };
  20125. SpriteManager.prototype.render = function () {
  20126. // Check
  20127. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20128. return;
  20129. var engine = this._scene.getEngine();
  20130. var baseSize = this._spriteTexture.getBaseSize();
  20131. // Sprites
  20132. var deltaTime = engine.getDeltaTime();
  20133. var max = Math.min(this._capacity, this.sprites.length);
  20134. var rowSize = baseSize.width / this.cellSize;
  20135. var offset = 0;
  20136. for (var index = 0; index < max; index++) {
  20137. var sprite = this.sprites[index];
  20138. if (!sprite) {
  20139. continue;
  20140. }
  20141. sprite._animate(deltaTime);
  20142. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20143. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20144. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20145. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20146. }
  20147. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20148. // Render
  20149. var effect = this._effectBase;
  20150. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20151. effect = this._effectFog;
  20152. }
  20153. engine.enableEffect(effect);
  20154. var viewMatrix = this._scene.getViewMatrix();
  20155. effect.setTexture("diffuseSampler", this._spriteTexture);
  20156. effect.setMatrix("view", viewMatrix);
  20157. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20158. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20159. // Fog
  20160. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20161. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20162. effect.setColor3("vFogColor", this._scene.fogColor);
  20163. }
  20164. // VBOs
  20165. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20166. // Draw order
  20167. engine.setDepthFunctionToLessOrEqual();
  20168. effect.setBool("alphaTest", true);
  20169. engine.setColorWrite(false);
  20170. engine.draw(true, 0, max * 6);
  20171. engine.setColorWrite(true);
  20172. effect.setBool("alphaTest", false);
  20173. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20174. engine.draw(true, 0, max * 6);
  20175. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20176. };
  20177. SpriteManager.prototype.dispose = function () {
  20178. if (this._vertexBuffer) {
  20179. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20180. this._vertexBuffer = null;
  20181. }
  20182. if (this._indexBuffer) {
  20183. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20184. this._indexBuffer = null;
  20185. }
  20186. if (this._spriteTexture) {
  20187. this._spriteTexture.dispose();
  20188. this._spriteTexture = null;
  20189. }
  20190. // Remove from scene
  20191. var index = this._scene.spriteManagers.indexOf(this);
  20192. this._scene.spriteManagers.splice(index, 1);
  20193. // Callback
  20194. if (this.onDispose) {
  20195. this.onDispose();
  20196. }
  20197. };
  20198. return SpriteManager;
  20199. })();
  20200. BABYLON.SpriteManager = SpriteManager;
  20201. })(BABYLON || (BABYLON = {}));
  20202. //# sourceMappingURL=babylon.spriteManager.js.map
  20203. var BABYLON;
  20204. (function (BABYLON) {
  20205. var Sprite = (function () {
  20206. function Sprite(name, manager) {
  20207. this.name = name;
  20208. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20209. this.width = 1.0;
  20210. this.height = 1.0;
  20211. this.angle = 0;
  20212. this.cellIndex = 0;
  20213. this.invertU = 0;
  20214. this.invertV = 0;
  20215. this.animations = new Array();
  20216. this._animationStarted = false;
  20217. this._loopAnimation = false;
  20218. this._fromIndex = 0;
  20219. this._toIndex = 0;
  20220. this._delay = 0;
  20221. this._direction = 1;
  20222. this._frameCount = 0;
  20223. this._time = 0;
  20224. this._manager = manager;
  20225. this._manager.sprites.push(this);
  20226. this.position = BABYLON.Vector3.Zero();
  20227. }
  20228. Object.defineProperty(Sprite.prototype, "size", {
  20229. get: function () {
  20230. return this.width;
  20231. },
  20232. set: function (value) {
  20233. this.width = value;
  20234. this.height = value;
  20235. },
  20236. enumerable: true,
  20237. configurable: true
  20238. });
  20239. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20240. this._fromIndex = from;
  20241. this._toIndex = to;
  20242. this._loopAnimation = loop;
  20243. this._delay = delay;
  20244. this._animationStarted = true;
  20245. this._direction = from < to ? 1 : -1;
  20246. this.cellIndex = from;
  20247. this._time = 0;
  20248. };
  20249. Sprite.prototype.stopAnimation = function () {
  20250. this._animationStarted = false;
  20251. };
  20252. Sprite.prototype._animate = function (deltaTime) {
  20253. if (!this._animationStarted)
  20254. return;
  20255. this._time += deltaTime;
  20256. if (this._time > this._delay) {
  20257. this._time = this._time % this._delay;
  20258. this.cellIndex += this._direction;
  20259. if (this.cellIndex == this._toIndex) {
  20260. if (this._loopAnimation) {
  20261. this.cellIndex = this._fromIndex;
  20262. }
  20263. else {
  20264. this._animationStarted = false;
  20265. if (this.disposeWhenFinishedAnimating) {
  20266. this.dispose();
  20267. }
  20268. }
  20269. }
  20270. }
  20271. };
  20272. Sprite.prototype.dispose = function () {
  20273. for (var i = 0; i < this._manager.sprites.length; i++) {
  20274. if (this._manager.sprites[i] == this) {
  20275. this._manager.sprites.splice(i, 1);
  20276. }
  20277. }
  20278. };
  20279. return Sprite;
  20280. })();
  20281. BABYLON.Sprite = Sprite;
  20282. })(BABYLON || (BABYLON = {}));
  20283. //# sourceMappingURL=babylon.sprite.js.map
  20284. var BABYLON;
  20285. (function (BABYLON) {
  20286. var Layer = (function () {
  20287. function Layer(name, imgUrl, scene, isBackground, color) {
  20288. this.name = name;
  20289. this._vertexDeclaration = [2];
  20290. this._vertexStrideSize = 2 * 4;
  20291. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20292. this.isBackground = isBackground === undefined ? true : isBackground;
  20293. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20294. this._scene = scene;
  20295. this._scene.layers.push(this);
  20296. // VBO
  20297. var vertices = [];
  20298. vertices.push(1, 1);
  20299. vertices.push(-1, 1);
  20300. vertices.push(-1, -1);
  20301. vertices.push(1, -1);
  20302. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20303. // Indices
  20304. var indices = [];
  20305. indices.push(0);
  20306. indices.push(1);
  20307. indices.push(2);
  20308. indices.push(0);
  20309. indices.push(2);
  20310. indices.push(3);
  20311. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20312. // Effects
  20313. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20314. }
  20315. Layer.prototype.render = function () {
  20316. // Check
  20317. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20318. return;
  20319. var engine = this._scene.getEngine();
  20320. // Render
  20321. engine.enableEffect(this._effect);
  20322. engine.setState(false);
  20323. // Texture
  20324. this._effect.setTexture("textureSampler", this.texture);
  20325. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20326. // Color
  20327. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20328. // VBOs
  20329. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20330. // Draw order
  20331. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20332. engine.draw(true, 0, 6);
  20333. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20334. };
  20335. Layer.prototype.dispose = function () {
  20336. if (this._vertexBuffer) {
  20337. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20338. this._vertexBuffer = null;
  20339. }
  20340. if (this._indexBuffer) {
  20341. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20342. this._indexBuffer = null;
  20343. }
  20344. if (this.texture) {
  20345. this.texture.dispose();
  20346. this.texture = null;
  20347. }
  20348. // Remove from scene
  20349. var index = this._scene.layers.indexOf(this);
  20350. this._scene.layers.splice(index, 1);
  20351. // Callback
  20352. if (this.onDispose) {
  20353. this.onDispose();
  20354. }
  20355. };
  20356. return Layer;
  20357. })();
  20358. BABYLON.Layer = Layer;
  20359. })(BABYLON || (BABYLON = {}));
  20360. //# sourceMappingURL=babylon.layer.js.map
  20361. var BABYLON;
  20362. (function (BABYLON) {
  20363. var Particle = (function () {
  20364. function Particle() {
  20365. this.position = BABYLON.Vector3.Zero();
  20366. this.direction = BABYLON.Vector3.Zero();
  20367. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20368. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20369. this.lifeTime = 1.0;
  20370. this.age = 0;
  20371. this.size = 0;
  20372. this.angle = 0;
  20373. this.angularSpeed = 0;
  20374. }
  20375. Particle.prototype.copyTo = function (other) {
  20376. other.position.copyFrom(this.position);
  20377. other.direction.copyFrom(this.direction);
  20378. other.color.copyFrom(this.color);
  20379. other.colorStep.copyFrom(this.colorStep);
  20380. other.lifeTime = this.lifeTime;
  20381. other.age = this.age;
  20382. other.size = this.size;
  20383. other.angle = this.angle;
  20384. other.angularSpeed = this.angularSpeed;
  20385. };
  20386. return Particle;
  20387. })();
  20388. BABYLON.Particle = Particle;
  20389. })(BABYLON || (BABYLON = {}));
  20390. //# sourceMappingURL=babylon.particle.js.map
  20391. var BABYLON;
  20392. (function (BABYLON) {
  20393. var randomNumber = function (min, max) {
  20394. if (min === max) {
  20395. return (min);
  20396. }
  20397. var random = Math.random();
  20398. return ((random * (max - min)) + min);
  20399. };
  20400. var ParticleSystem = (function () {
  20401. function ParticleSystem(name, capacity, scene, customEffect) {
  20402. var _this = this;
  20403. this.name = name;
  20404. this.renderingGroupId = 0;
  20405. this.emitter = null;
  20406. this.emitRate = 10;
  20407. this.manualEmitCount = -1;
  20408. this.updateSpeed = 0.01;
  20409. this.targetStopDuration = 0;
  20410. this.disposeOnStop = false;
  20411. this.minEmitPower = 1;
  20412. this.maxEmitPower = 1;
  20413. this.minLifeTime = 1;
  20414. this.maxLifeTime = 1;
  20415. this.minSize = 1;
  20416. this.maxSize = 1;
  20417. this.minAngularSpeed = 0;
  20418. this.maxAngularSpeed = 0;
  20419. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20420. this.forceDepthWrite = false;
  20421. this.gravity = BABYLON.Vector3.Zero();
  20422. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20423. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20424. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20425. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20426. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20427. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20428. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20429. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20430. this.particles = new Array();
  20431. this._vertexDeclaration = [3, 4, 4];
  20432. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20433. this._stockParticles = new Array();
  20434. this._newPartsExcess = 0;
  20435. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20436. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20437. this._scaledDirection = BABYLON.Vector3.Zero();
  20438. this._scaledGravity = BABYLON.Vector3.Zero();
  20439. this._currentRenderId = -1;
  20440. this._started = false;
  20441. this._stopped = false;
  20442. this._actualFrame = 0;
  20443. this.id = name;
  20444. this._capacity = capacity;
  20445. this._scene = scene;
  20446. this._customEffect = customEffect;
  20447. scene.particleSystems.push(this);
  20448. // VBO
  20449. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20450. var indices = [];
  20451. var index = 0;
  20452. for (var count = 0; count < capacity; count++) {
  20453. indices.push(index);
  20454. indices.push(index + 1);
  20455. indices.push(index + 2);
  20456. indices.push(index);
  20457. indices.push(index + 2);
  20458. indices.push(index + 3);
  20459. index += 4;
  20460. }
  20461. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20462. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20463. // Default behaviors
  20464. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  20465. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20466. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20467. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20468. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20469. };
  20470. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  20471. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20472. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20473. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20474. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20475. };
  20476. this.updateFunction = function (particles) {
  20477. for (var index = 0; index < particles.length; index++) {
  20478. var particle = particles[index];
  20479. particle.age += _this._scaledUpdateSpeed;
  20480. if (particle.age >= particle.lifeTime) {
  20481. _this.recycleParticle(particle);
  20482. index--;
  20483. continue;
  20484. }
  20485. else {
  20486. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20487. particle.color.addInPlace(_this._scaledColorStep);
  20488. if (particle.color.a < 0)
  20489. particle.color.a = 0;
  20490. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20491. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20492. particle.position.addInPlace(_this._scaledDirection);
  20493. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20494. particle.direction.addInPlace(_this._scaledGravity);
  20495. }
  20496. }
  20497. };
  20498. }
  20499. ParticleSystem.prototype.recycleParticle = function (particle) {
  20500. var lastParticle = this.particles.pop();
  20501. if (lastParticle !== particle) {
  20502. lastParticle.copyTo(particle);
  20503. this._stockParticles.push(lastParticle);
  20504. }
  20505. };
  20506. ParticleSystem.prototype.getCapacity = function () {
  20507. return this._capacity;
  20508. };
  20509. ParticleSystem.prototype.isAlive = function () {
  20510. return this._alive;
  20511. };
  20512. ParticleSystem.prototype.isStarted = function () {
  20513. return this._started;
  20514. };
  20515. ParticleSystem.prototype.start = function () {
  20516. this._started = true;
  20517. this._stopped = false;
  20518. this._actualFrame = 0;
  20519. };
  20520. ParticleSystem.prototype.stop = function () {
  20521. this._stopped = true;
  20522. };
  20523. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20524. var offset = index * 11;
  20525. this._vertices[offset] = particle.position.x;
  20526. this._vertices[offset + 1] = particle.position.y;
  20527. this._vertices[offset + 2] = particle.position.z;
  20528. this._vertices[offset + 3] = particle.color.r;
  20529. this._vertices[offset + 4] = particle.color.g;
  20530. this._vertices[offset + 5] = particle.color.b;
  20531. this._vertices[offset + 6] = particle.color.a;
  20532. this._vertices[offset + 7] = particle.angle;
  20533. this._vertices[offset + 8] = particle.size;
  20534. this._vertices[offset + 9] = offsetX;
  20535. this._vertices[offset + 10] = offsetY;
  20536. };
  20537. ParticleSystem.prototype._update = function (newParticles) {
  20538. // Update current
  20539. this._alive = this.particles.length > 0;
  20540. this.updateFunction(this.particles);
  20541. // Add new ones
  20542. var worldMatrix;
  20543. if (this.emitter.position) {
  20544. worldMatrix = this.emitter.getWorldMatrix();
  20545. }
  20546. else {
  20547. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20548. }
  20549. for (var index = 0; index < newParticles; index++) {
  20550. if (this.particles.length === this._capacity) {
  20551. break;
  20552. }
  20553. if (this._stockParticles.length !== 0) {
  20554. var particle = this._stockParticles.pop();
  20555. particle.age = 0;
  20556. }
  20557. else {
  20558. particle = new BABYLON.Particle();
  20559. }
  20560. this.particles.push(particle);
  20561. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20562. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  20563. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20564. particle.size = randomNumber(this.minSize, this.maxSize);
  20565. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20566. this.startPositionFunction(worldMatrix, particle.position);
  20567. var step = randomNumber(0, 1.0);
  20568. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20569. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20570. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20571. }
  20572. };
  20573. ParticleSystem.prototype._getEffect = function () {
  20574. if (this._customEffect) {
  20575. return this._customEffect;
  20576. }
  20577. ;
  20578. var defines = [];
  20579. if (this._scene.clipPlane) {
  20580. defines.push("#define CLIPPLANE");
  20581. }
  20582. // Effect
  20583. var join = defines.join("\n");
  20584. if (this._cachedDefines !== join) {
  20585. this._cachedDefines = join;
  20586. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20587. }
  20588. return this._effect;
  20589. };
  20590. ParticleSystem.prototype.animate = function () {
  20591. if (!this._started)
  20592. return;
  20593. var effect = this._getEffect();
  20594. // Check
  20595. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20596. return;
  20597. if (this._currentRenderId === this._scene.getRenderId()) {
  20598. return;
  20599. }
  20600. this._currentRenderId = this._scene.getRenderId();
  20601. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20602. // determine the number of particles we need to create
  20603. var emitCout;
  20604. if (this.manualEmitCount > -1) {
  20605. emitCout = this.manualEmitCount;
  20606. this.manualEmitCount = 0;
  20607. }
  20608. else {
  20609. emitCout = this.emitRate;
  20610. }
  20611. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20612. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20613. if (this._newPartsExcess > 1.0) {
  20614. newParticles += this._newPartsExcess >> 0;
  20615. this._newPartsExcess -= this._newPartsExcess >> 0;
  20616. }
  20617. this._alive = false;
  20618. if (!this._stopped) {
  20619. this._actualFrame += this._scaledUpdateSpeed;
  20620. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20621. this.stop();
  20622. }
  20623. else {
  20624. newParticles = 0;
  20625. }
  20626. this._update(newParticles);
  20627. // Stopped?
  20628. if (this._stopped) {
  20629. if (!this._alive) {
  20630. this._started = false;
  20631. if (this.disposeOnStop) {
  20632. this._scene._toBeDisposed.push(this);
  20633. }
  20634. }
  20635. }
  20636. // Update VBO
  20637. var offset = 0;
  20638. for (var index = 0; index < this.particles.length; index++) {
  20639. var particle = this.particles[index];
  20640. this._appendParticleVertex(offset++, particle, 0, 0);
  20641. this._appendParticleVertex(offset++, particle, 1, 0);
  20642. this._appendParticleVertex(offset++, particle, 1, 1);
  20643. this._appendParticleVertex(offset++, particle, 0, 1);
  20644. }
  20645. var engine = this._scene.getEngine();
  20646. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20647. };
  20648. ParticleSystem.prototype.render = function () {
  20649. var effect = this._getEffect();
  20650. // Check
  20651. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20652. return 0;
  20653. var engine = this._scene.getEngine();
  20654. // Render
  20655. engine.enableEffect(effect);
  20656. engine.setState(false);
  20657. var viewMatrix = this._scene.getViewMatrix();
  20658. effect.setTexture("diffuseSampler", this.particleTexture);
  20659. effect.setMatrix("view", viewMatrix);
  20660. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20661. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20662. if (this._scene.clipPlane) {
  20663. var clipPlane = this._scene.clipPlane;
  20664. var invView = viewMatrix.clone();
  20665. invView.invert();
  20666. effect.setMatrix("invView", invView);
  20667. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20668. }
  20669. // VBOs
  20670. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20671. // Draw order
  20672. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20673. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  20674. }
  20675. else {
  20676. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20677. }
  20678. if (this.forceDepthWrite) {
  20679. engine.setDepthWrite(true);
  20680. }
  20681. engine.draw(true, 0, this.particles.length * 6);
  20682. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20683. return this.particles.length;
  20684. };
  20685. ParticleSystem.prototype.dispose = function () {
  20686. if (this._vertexBuffer) {
  20687. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20688. this._vertexBuffer = null;
  20689. }
  20690. if (this._indexBuffer) {
  20691. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20692. this._indexBuffer = null;
  20693. }
  20694. if (this.particleTexture) {
  20695. this.particleTexture.dispose();
  20696. this.particleTexture = null;
  20697. }
  20698. // Remove from scene
  20699. var index = this._scene.particleSystems.indexOf(this);
  20700. this._scene.particleSystems.splice(index, 1);
  20701. // Callback
  20702. if (this.onDispose) {
  20703. this.onDispose();
  20704. }
  20705. };
  20706. // Clone
  20707. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20708. var result = new ParticleSystem(name, this._capacity, this._scene);
  20709. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20710. if (newEmitter === undefined) {
  20711. newEmitter = this.emitter;
  20712. }
  20713. result.emitter = newEmitter;
  20714. if (this.particleTexture) {
  20715. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20716. }
  20717. result.start();
  20718. return result;
  20719. };
  20720. // Statics
  20721. ParticleSystem.BLENDMODE_ONEONE = 0;
  20722. ParticleSystem.BLENDMODE_STANDARD = 1;
  20723. return ParticleSystem;
  20724. })();
  20725. BABYLON.ParticleSystem = ParticleSystem;
  20726. })(BABYLON || (BABYLON = {}));
  20727. //# sourceMappingURL=babylon.particleSystem.js.map
  20728. var BABYLON;
  20729. (function (BABYLON) {
  20730. var Animation = (function () {
  20731. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  20732. this.name = name;
  20733. this.targetProperty = targetProperty;
  20734. this.framePerSecond = framePerSecond;
  20735. this.dataType = dataType;
  20736. this.loopMode = loopMode;
  20737. this._offsetsCache = {};
  20738. this._highLimitsCache = {};
  20739. this._stopped = false;
  20740. this.targetPropertyPath = targetProperty.split(".");
  20741. this.dataType = dataType;
  20742. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  20743. }
  20744. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  20745. var dataType = undefined;
  20746. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  20747. dataType = Animation.ANIMATIONTYPE_FLOAT;
  20748. }
  20749. else if (from instanceof BABYLON.Quaternion) {
  20750. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  20751. }
  20752. else if (from instanceof BABYLON.Vector3) {
  20753. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  20754. }
  20755. else if (from instanceof BABYLON.Vector2) {
  20756. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  20757. }
  20758. else if (from instanceof BABYLON.Color3) {
  20759. dataType = Animation.ANIMATIONTYPE_COLOR3;
  20760. }
  20761. if (dataType == undefined) {
  20762. return null;
  20763. }
  20764. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  20765. var keys = [];
  20766. keys.push({ frame: 0, value: from });
  20767. keys.push({ frame: totalFrame, value: to });
  20768. animation.setKeys(keys);
  20769. mesh.animations.push(animation);
  20770. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  20771. };
  20772. // Methods
  20773. Animation.prototype.isStopped = function () {
  20774. return this._stopped;
  20775. };
  20776. Animation.prototype.getKeys = function () {
  20777. return this._keys;
  20778. };
  20779. Animation.prototype.getEasingFunction = function () {
  20780. return this._easingFunction;
  20781. };
  20782. Animation.prototype.setEasingFunction = function (easingFunction) {
  20783. this._easingFunction = easingFunction;
  20784. };
  20785. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  20786. return startValue + (endValue - startValue) * gradient;
  20787. };
  20788. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  20789. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  20790. };
  20791. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  20792. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  20793. };
  20794. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  20795. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  20796. };
  20797. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  20798. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  20799. };
  20800. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  20801. var startScale = new BABYLON.Vector3(0, 0, 0);
  20802. var startRotation = new BABYLON.Quaternion();
  20803. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  20804. startValue.decompose(startScale, startRotation, startTranslation);
  20805. var endScale = new BABYLON.Vector3(0, 0, 0);
  20806. var endRotation = new BABYLON.Quaternion();
  20807. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  20808. endValue.decompose(endScale, endRotation, endTranslation);
  20809. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  20810. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  20811. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  20812. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  20813. return result;
  20814. };
  20815. Animation.prototype.clone = function () {
  20816. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  20817. clone.setKeys(this._keys);
  20818. return clone;
  20819. };
  20820. Animation.prototype.setKeys = function (values) {
  20821. this._keys = values.slice(0);
  20822. this._offsetsCache = {};
  20823. this._highLimitsCache = {};
  20824. };
  20825. Animation.prototype._getKeyValue = function (value) {
  20826. if (typeof value === "function") {
  20827. return value();
  20828. }
  20829. return value;
  20830. };
  20831. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  20832. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  20833. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  20834. }
  20835. this.currentFrame = currentFrame;
  20836. // Try to get a hash to find the right key
  20837. 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));
  20838. if (this._keys[startKey].frame >= currentFrame) {
  20839. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  20840. startKey--;
  20841. }
  20842. }
  20843. for (var key = startKey; key < this._keys.length; key++) {
  20844. if (this._keys[key + 1].frame >= currentFrame) {
  20845. var startValue = this._getKeyValue(this._keys[key].value);
  20846. var endValue = this._getKeyValue(this._keys[key + 1].value);
  20847. // gradient : percent of currentFrame between the frame inf and the frame sup
  20848. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  20849. // check for easingFunction and correction of gradient
  20850. if (this._easingFunction != null) {
  20851. gradient = this._easingFunction.ease(gradient);
  20852. }
  20853. switch (this.dataType) {
  20854. // Float
  20855. case Animation.ANIMATIONTYPE_FLOAT:
  20856. switch (loopMode) {
  20857. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20858. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20859. return this.floatInterpolateFunction(startValue, endValue, gradient);
  20860. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20861. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  20862. }
  20863. break;
  20864. // Quaternion
  20865. case Animation.ANIMATIONTYPE_QUATERNION:
  20866. var quaternion = null;
  20867. switch (loopMode) {
  20868. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20869. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20870. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  20871. break;
  20872. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20873. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20874. break;
  20875. }
  20876. return quaternion;
  20877. // Vector3
  20878. case Animation.ANIMATIONTYPE_VECTOR3:
  20879. switch (loopMode) {
  20880. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20881. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20882. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  20883. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20884. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20885. }
  20886. // Vector2
  20887. case Animation.ANIMATIONTYPE_VECTOR2:
  20888. switch (loopMode) {
  20889. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20890. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20891. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  20892. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20893. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20894. }
  20895. // Color3
  20896. case Animation.ANIMATIONTYPE_COLOR3:
  20897. switch (loopMode) {
  20898. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20899. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20900. return this.color3InterpolateFunction(startValue, endValue, gradient);
  20901. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20902. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20903. }
  20904. // Matrix
  20905. case Animation.ANIMATIONTYPE_MATRIX:
  20906. switch (loopMode) {
  20907. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20908. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20909. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  20910. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20911. return startValue;
  20912. }
  20913. default:
  20914. break;
  20915. }
  20916. break;
  20917. }
  20918. }
  20919. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  20920. };
  20921. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  20922. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  20923. this._stopped = true;
  20924. return false;
  20925. }
  20926. var returnValue = true;
  20927. // Adding a start key at frame 0 if missing
  20928. if (this._keys[0].frame !== 0) {
  20929. var newKey = { frame: 0, value: this._keys[0].value };
  20930. this._keys.splice(0, 0, newKey);
  20931. }
  20932. // Check limits
  20933. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  20934. from = this._keys[0].frame;
  20935. }
  20936. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  20937. to = this._keys[this._keys.length - 1].frame;
  20938. }
  20939. // Compute ratio
  20940. var range = to - from;
  20941. var offsetValue;
  20942. // ratio represents the frame delta between from and to
  20943. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  20944. var highLimitValue = 0;
  20945. if (ratio > range && !loop) {
  20946. returnValue = false;
  20947. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  20948. }
  20949. else {
  20950. // Get max value if required
  20951. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  20952. var keyOffset = to.toString() + from.toString();
  20953. if (!this._offsetsCache[keyOffset]) {
  20954. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20955. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20956. switch (this.dataType) {
  20957. // Float
  20958. case Animation.ANIMATIONTYPE_FLOAT:
  20959. this._offsetsCache[keyOffset] = toValue - fromValue;
  20960. break;
  20961. // Quaternion
  20962. case Animation.ANIMATIONTYPE_QUATERNION:
  20963. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20964. break;
  20965. // Vector3
  20966. case Animation.ANIMATIONTYPE_VECTOR3:
  20967. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20968. // Vector2
  20969. case Animation.ANIMATIONTYPE_VECTOR2:
  20970. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20971. // Color3
  20972. case Animation.ANIMATIONTYPE_COLOR3:
  20973. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20974. default:
  20975. break;
  20976. }
  20977. this._highLimitsCache[keyOffset] = toValue;
  20978. }
  20979. highLimitValue = this._highLimitsCache[keyOffset];
  20980. offsetValue = this._offsetsCache[keyOffset];
  20981. }
  20982. }
  20983. if (offsetValue === undefined) {
  20984. switch (this.dataType) {
  20985. // Float
  20986. case Animation.ANIMATIONTYPE_FLOAT:
  20987. offsetValue = 0;
  20988. break;
  20989. // Quaternion
  20990. case Animation.ANIMATIONTYPE_QUATERNION:
  20991. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  20992. break;
  20993. // Vector3
  20994. case Animation.ANIMATIONTYPE_VECTOR3:
  20995. offsetValue = BABYLON.Vector3.Zero();
  20996. break;
  20997. // Vector2
  20998. case Animation.ANIMATIONTYPE_VECTOR2:
  20999. offsetValue = BABYLON.Vector2.Zero();
  21000. break;
  21001. // Color3
  21002. case Animation.ANIMATIONTYPE_COLOR3:
  21003. offsetValue = BABYLON.Color3.Black();
  21004. }
  21005. }
  21006. // Compute value
  21007. var repeatCount = (ratio / range) >> 0;
  21008. var currentFrame = returnValue ? from + ratio % range : to;
  21009. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21010. // Set value
  21011. if (this.targetPropertyPath.length > 1) {
  21012. var property = this._target[this.targetPropertyPath[0]];
  21013. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21014. property = property[this.targetPropertyPath[index]];
  21015. }
  21016. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21017. }
  21018. else {
  21019. this._target[this.targetPropertyPath[0]] = currentValue;
  21020. }
  21021. if (this._target.markAsDirty) {
  21022. this._target.markAsDirty(this.targetProperty);
  21023. }
  21024. if (!returnValue) {
  21025. this._stopped = true;
  21026. }
  21027. return returnValue;
  21028. };
  21029. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21030. get: function () {
  21031. return Animation._ANIMATIONTYPE_FLOAT;
  21032. },
  21033. enumerable: true,
  21034. configurable: true
  21035. });
  21036. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21037. get: function () {
  21038. return Animation._ANIMATIONTYPE_VECTOR3;
  21039. },
  21040. enumerable: true,
  21041. configurable: true
  21042. });
  21043. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21044. get: function () {
  21045. return Animation._ANIMATIONTYPE_VECTOR2;
  21046. },
  21047. enumerable: true,
  21048. configurable: true
  21049. });
  21050. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21051. get: function () {
  21052. return Animation._ANIMATIONTYPE_QUATERNION;
  21053. },
  21054. enumerable: true,
  21055. configurable: true
  21056. });
  21057. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21058. get: function () {
  21059. return Animation._ANIMATIONTYPE_MATRIX;
  21060. },
  21061. enumerable: true,
  21062. configurable: true
  21063. });
  21064. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21065. get: function () {
  21066. return Animation._ANIMATIONTYPE_COLOR3;
  21067. },
  21068. enumerable: true,
  21069. configurable: true
  21070. });
  21071. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21072. get: function () {
  21073. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21074. },
  21075. enumerable: true,
  21076. configurable: true
  21077. });
  21078. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21079. get: function () {
  21080. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21081. },
  21082. enumerable: true,
  21083. configurable: true
  21084. });
  21085. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21086. get: function () {
  21087. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21088. },
  21089. enumerable: true,
  21090. configurable: true
  21091. });
  21092. // Statics
  21093. Animation._ANIMATIONTYPE_FLOAT = 0;
  21094. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21095. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21096. Animation._ANIMATIONTYPE_MATRIX = 3;
  21097. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21098. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21099. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21100. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21101. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21102. return Animation;
  21103. })();
  21104. BABYLON.Animation = Animation;
  21105. })(BABYLON || (BABYLON = {}));
  21106. //# sourceMappingURL=babylon.animation.js.map
  21107. var BABYLON;
  21108. (function (BABYLON) {
  21109. var Animatable = (function () {
  21110. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21111. if (fromFrame === void 0) { fromFrame = 0; }
  21112. if (toFrame === void 0) { toFrame = 100; }
  21113. if (loopAnimation === void 0) { loopAnimation = false; }
  21114. if (speedRatio === void 0) { speedRatio = 1.0; }
  21115. this.target = target;
  21116. this.fromFrame = fromFrame;
  21117. this.toFrame = toFrame;
  21118. this.loopAnimation = loopAnimation;
  21119. this.speedRatio = speedRatio;
  21120. this.onAnimationEnd = onAnimationEnd;
  21121. this._animations = new Array();
  21122. this._paused = false;
  21123. this.animationStarted = false;
  21124. if (animations) {
  21125. this.appendAnimations(target, animations);
  21126. }
  21127. this._scene = scene;
  21128. scene._activeAnimatables.push(this);
  21129. }
  21130. // Methods
  21131. Animatable.prototype.appendAnimations = function (target, animations) {
  21132. for (var index = 0; index < animations.length; index++) {
  21133. var animation = animations[index];
  21134. animation._target = target;
  21135. this._animations.push(animation);
  21136. }
  21137. };
  21138. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21139. var animations = this._animations;
  21140. for (var index = 0; index < animations.length; index++) {
  21141. if (animations[index].targetProperty === property) {
  21142. return animations[index];
  21143. }
  21144. }
  21145. return null;
  21146. };
  21147. Animatable.prototype.pause = function () {
  21148. if (this._paused) {
  21149. return;
  21150. }
  21151. this._paused = true;
  21152. };
  21153. Animatable.prototype.restart = function () {
  21154. this._paused = false;
  21155. };
  21156. Animatable.prototype.stop = function () {
  21157. var index = this._scene._activeAnimatables.indexOf(this);
  21158. if (index > -1) {
  21159. this._scene._activeAnimatables.splice(index, 1);
  21160. }
  21161. if (this.onAnimationEnd) {
  21162. this.onAnimationEnd();
  21163. }
  21164. };
  21165. Animatable.prototype._animate = function (delay) {
  21166. if (this._paused) {
  21167. if (!this._pausedDelay) {
  21168. this._pausedDelay = delay;
  21169. }
  21170. return true;
  21171. }
  21172. if (!this._localDelayOffset) {
  21173. this._localDelayOffset = delay;
  21174. }
  21175. else if (this._pausedDelay) {
  21176. this._localDelayOffset += delay - this._pausedDelay;
  21177. this._pausedDelay = null;
  21178. }
  21179. // Animating
  21180. var running = false;
  21181. var animations = this._animations;
  21182. for (var index = 0; index < animations.length; index++) {
  21183. var animation = animations[index];
  21184. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21185. running = running || isRunning;
  21186. }
  21187. if (!running) {
  21188. // Remove from active animatables
  21189. index = this._scene._activeAnimatables.indexOf(this);
  21190. this._scene._activeAnimatables.splice(index, 1);
  21191. }
  21192. if (!running && this.onAnimationEnd) {
  21193. this.onAnimationEnd();
  21194. }
  21195. return running;
  21196. };
  21197. return Animatable;
  21198. })();
  21199. BABYLON.Animatable = Animatable;
  21200. })(BABYLON || (BABYLON = {}));
  21201. //# sourceMappingURL=babylon.animatable.js.map
  21202. var BABYLON;
  21203. (function (BABYLON) {
  21204. var EasingFunction = (function () {
  21205. function EasingFunction() {
  21206. // Properties
  21207. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21208. }
  21209. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21210. get: function () {
  21211. return EasingFunction._EASINGMODE_EASEIN;
  21212. },
  21213. enumerable: true,
  21214. configurable: true
  21215. });
  21216. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21217. get: function () {
  21218. return EasingFunction._EASINGMODE_EASEOUT;
  21219. },
  21220. enumerable: true,
  21221. configurable: true
  21222. });
  21223. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21224. get: function () {
  21225. return EasingFunction._EASINGMODE_EASEINOUT;
  21226. },
  21227. enumerable: true,
  21228. configurable: true
  21229. });
  21230. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21231. var n = Math.min(Math.max(easingMode, 0), 2);
  21232. this._easingMode = n;
  21233. };
  21234. EasingFunction.prototype.getEasingMode = function () {
  21235. return this._easingMode;
  21236. };
  21237. EasingFunction.prototype.easeInCore = function (gradient) {
  21238. throw new Error('You must implement this method');
  21239. };
  21240. EasingFunction.prototype.ease = function (gradient) {
  21241. switch (this._easingMode) {
  21242. case EasingFunction.EASINGMODE_EASEIN:
  21243. return this.easeInCore(gradient);
  21244. case EasingFunction.EASINGMODE_EASEOUT:
  21245. return (1 - this.easeInCore(1 - gradient));
  21246. }
  21247. if (gradient >= 0.5) {
  21248. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21249. }
  21250. return (this.easeInCore(gradient * 2) * 0.5);
  21251. };
  21252. //Statics
  21253. EasingFunction._EASINGMODE_EASEIN = 0;
  21254. EasingFunction._EASINGMODE_EASEOUT = 1;
  21255. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21256. return EasingFunction;
  21257. })();
  21258. BABYLON.EasingFunction = EasingFunction;
  21259. var CircleEase = (function (_super) {
  21260. __extends(CircleEase, _super);
  21261. function CircleEase() {
  21262. _super.apply(this, arguments);
  21263. }
  21264. CircleEase.prototype.easeInCore = function (gradient) {
  21265. gradient = Math.max(0, Math.min(1, gradient));
  21266. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21267. };
  21268. return CircleEase;
  21269. })(EasingFunction);
  21270. BABYLON.CircleEase = CircleEase;
  21271. var BackEase = (function (_super) {
  21272. __extends(BackEase, _super);
  21273. function BackEase(amplitude) {
  21274. if (amplitude === void 0) { amplitude = 1; }
  21275. _super.call(this);
  21276. this.amplitude = amplitude;
  21277. }
  21278. BackEase.prototype.easeInCore = function (gradient) {
  21279. var num = Math.max(0, this.amplitude);
  21280. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21281. };
  21282. return BackEase;
  21283. })(EasingFunction);
  21284. BABYLON.BackEase = BackEase;
  21285. var BounceEase = (function (_super) {
  21286. __extends(BounceEase, _super);
  21287. function BounceEase(bounces, bounciness) {
  21288. if (bounces === void 0) { bounces = 3; }
  21289. if (bounciness === void 0) { bounciness = 2; }
  21290. _super.call(this);
  21291. this.bounces = bounces;
  21292. this.bounciness = bounciness;
  21293. }
  21294. BounceEase.prototype.easeInCore = function (gradient) {
  21295. var y = Math.max(0.0, this.bounces);
  21296. var bounciness = this.bounciness;
  21297. if (bounciness <= 1.0) {
  21298. bounciness = 1.001;
  21299. }
  21300. var num9 = Math.pow(bounciness, y);
  21301. var num5 = 1.0 - bounciness;
  21302. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21303. var num15 = gradient * num4;
  21304. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21305. var num3 = Math.floor(num65);
  21306. var num13 = num3 + 1.0;
  21307. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21308. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21309. var num7 = (num8 + num12) * 0.5;
  21310. var num6 = gradient - num7;
  21311. var num2 = num7 - num8;
  21312. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21313. };
  21314. return BounceEase;
  21315. })(EasingFunction);
  21316. BABYLON.BounceEase = BounceEase;
  21317. var CubicEase = (function (_super) {
  21318. __extends(CubicEase, _super);
  21319. function CubicEase() {
  21320. _super.apply(this, arguments);
  21321. }
  21322. CubicEase.prototype.easeInCore = function (gradient) {
  21323. return (gradient * gradient * gradient);
  21324. };
  21325. return CubicEase;
  21326. })(EasingFunction);
  21327. BABYLON.CubicEase = CubicEase;
  21328. var ElasticEase = (function (_super) {
  21329. __extends(ElasticEase, _super);
  21330. function ElasticEase(oscillations, springiness) {
  21331. if (oscillations === void 0) { oscillations = 3; }
  21332. if (springiness === void 0) { springiness = 3; }
  21333. _super.call(this);
  21334. this.oscillations = oscillations;
  21335. this.springiness = springiness;
  21336. }
  21337. ElasticEase.prototype.easeInCore = function (gradient) {
  21338. var num2;
  21339. var num3 = Math.max(0.0, this.oscillations);
  21340. var num = Math.max(0.0, this.springiness);
  21341. if (num == 0) {
  21342. num2 = gradient;
  21343. }
  21344. else {
  21345. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21346. }
  21347. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21348. };
  21349. return ElasticEase;
  21350. })(EasingFunction);
  21351. BABYLON.ElasticEase = ElasticEase;
  21352. var ExponentialEase = (function (_super) {
  21353. __extends(ExponentialEase, _super);
  21354. function ExponentialEase(exponent) {
  21355. if (exponent === void 0) { exponent = 2; }
  21356. _super.call(this);
  21357. this.exponent = exponent;
  21358. }
  21359. ExponentialEase.prototype.easeInCore = function (gradient) {
  21360. if (this.exponent <= 0) {
  21361. return gradient;
  21362. }
  21363. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21364. };
  21365. return ExponentialEase;
  21366. })(EasingFunction);
  21367. BABYLON.ExponentialEase = ExponentialEase;
  21368. var PowerEase = (function (_super) {
  21369. __extends(PowerEase, _super);
  21370. function PowerEase(power) {
  21371. if (power === void 0) { power = 2; }
  21372. _super.call(this);
  21373. this.power = power;
  21374. }
  21375. PowerEase.prototype.easeInCore = function (gradient) {
  21376. var y = Math.max(0.0, this.power);
  21377. return Math.pow(gradient, y);
  21378. };
  21379. return PowerEase;
  21380. })(EasingFunction);
  21381. BABYLON.PowerEase = PowerEase;
  21382. var QuadraticEase = (function (_super) {
  21383. __extends(QuadraticEase, _super);
  21384. function QuadraticEase() {
  21385. _super.apply(this, arguments);
  21386. }
  21387. QuadraticEase.prototype.easeInCore = function (gradient) {
  21388. return (gradient * gradient);
  21389. };
  21390. return QuadraticEase;
  21391. })(EasingFunction);
  21392. BABYLON.QuadraticEase = QuadraticEase;
  21393. var QuarticEase = (function (_super) {
  21394. __extends(QuarticEase, _super);
  21395. function QuarticEase() {
  21396. _super.apply(this, arguments);
  21397. }
  21398. QuarticEase.prototype.easeInCore = function (gradient) {
  21399. return (gradient * gradient * gradient * gradient);
  21400. };
  21401. return QuarticEase;
  21402. })(EasingFunction);
  21403. BABYLON.QuarticEase = QuarticEase;
  21404. var QuinticEase = (function (_super) {
  21405. __extends(QuinticEase, _super);
  21406. function QuinticEase() {
  21407. _super.apply(this, arguments);
  21408. }
  21409. QuinticEase.prototype.easeInCore = function (gradient) {
  21410. return (gradient * gradient * gradient * gradient * gradient);
  21411. };
  21412. return QuinticEase;
  21413. })(EasingFunction);
  21414. BABYLON.QuinticEase = QuinticEase;
  21415. var SineEase = (function (_super) {
  21416. __extends(SineEase, _super);
  21417. function SineEase() {
  21418. _super.apply(this, arguments);
  21419. }
  21420. SineEase.prototype.easeInCore = function (gradient) {
  21421. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21422. };
  21423. return SineEase;
  21424. })(EasingFunction);
  21425. BABYLON.SineEase = SineEase;
  21426. var BezierCurveEase = (function (_super) {
  21427. __extends(BezierCurveEase, _super);
  21428. function BezierCurveEase(x1, y1, x2, y2) {
  21429. if (x1 === void 0) { x1 = 0; }
  21430. if (y1 === void 0) { y1 = 0; }
  21431. if (x2 === void 0) { x2 = 1; }
  21432. if (y2 === void 0) { y2 = 1; }
  21433. _super.call(this);
  21434. this.x1 = x1;
  21435. this.y1 = y1;
  21436. this.x2 = x2;
  21437. this.y2 = y2;
  21438. }
  21439. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21440. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21441. };
  21442. return BezierCurveEase;
  21443. })(EasingFunction);
  21444. BABYLON.BezierCurveEase = BezierCurveEase;
  21445. })(BABYLON || (BABYLON = {}));
  21446. //# sourceMappingURL=babylon.easing.js.map
  21447. var BABYLON;
  21448. (function (BABYLON) {
  21449. var Octree = (function () {
  21450. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  21451. if (maxDepth === void 0) { maxDepth = 2; }
  21452. this.maxDepth = maxDepth;
  21453. this.dynamicContent = new Array();
  21454. this._maxBlockCapacity = maxBlockCapacity || 64;
  21455. this._selectionContent = new BABYLON.SmartArray(1024);
  21456. this._creationFunc = creationFunc;
  21457. }
  21458. // Methods
  21459. Octree.prototype.update = function (worldMin, worldMax, entries) {
  21460. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  21461. };
  21462. Octree.prototype.addMesh = function (entry) {
  21463. for (var index = 0; index < this.blocks.length; index++) {
  21464. var block = this.blocks[index];
  21465. block.addEntry(entry);
  21466. }
  21467. };
  21468. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  21469. this._selectionContent.reset();
  21470. for (var index = 0; index < this.blocks.length; index++) {
  21471. var block = this.blocks[index];
  21472. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  21473. }
  21474. if (allowDuplicate) {
  21475. this._selectionContent.concat(this.dynamicContent);
  21476. }
  21477. else {
  21478. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21479. }
  21480. return this._selectionContent;
  21481. };
  21482. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  21483. this._selectionContent.reset();
  21484. for (var index = 0; index < this.blocks.length; index++) {
  21485. var block = this.blocks[index];
  21486. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  21487. }
  21488. if (allowDuplicate) {
  21489. this._selectionContent.concat(this.dynamicContent);
  21490. }
  21491. else {
  21492. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21493. }
  21494. return this._selectionContent;
  21495. };
  21496. Octree.prototype.intersectsRay = function (ray) {
  21497. this._selectionContent.reset();
  21498. for (var index = 0; index < this.blocks.length; index++) {
  21499. var block = this.blocks[index];
  21500. block.intersectsRay(ray, this._selectionContent);
  21501. }
  21502. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21503. return this._selectionContent;
  21504. };
  21505. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  21506. target.blocks = new Array();
  21507. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  21508. // Segmenting space
  21509. for (var x = 0; x < 2; x++) {
  21510. for (var y = 0; y < 2; y++) {
  21511. for (var z = 0; z < 2; z++) {
  21512. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  21513. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  21514. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  21515. block.addEntries(entries);
  21516. target.blocks.push(block);
  21517. }
  21518. }
  21519. }
  21520. };
  21521. Octree.CreationFuncForMeshes = function (entry, block) {
  21522. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21523. block.entries.push(entry);
  21524. }
  21525. };
  21526. Octree.CreationFuncForSubMeshes = function (entry, block) {
  21527. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21528. block.entries.push(entry);
  21529. }
  21530. };
  21531. return Octree;
  21532. })();
  21533. BABYLON.Octree = Octree;
  21534. })(BABYLON || (BABYLON = {}));
  21535. //# sourceMappingURL=babylon.octree.js.map
  21536. var BABYLON;
  21537. (function (BABYLON) {
  21538. var OctreeBlock = (function () {
  21539. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  21540. this.entries = new Array();
  21541. this._boundingVectors = new Array();
  21542. this._capacity = capacity;
  21543. this._depth = depth;
  21544. this._maxDepth = maxDepth;
  21545. this._creationFunc = creationFunc;
  21546. this._minPoint = minPoint;
  21547. this._maxPoint = maxPoint;
  21548. this._boundingVectors.push(minPoint.clone());
  21549. this._boundingVectors.push(maxPoint.clone());
  21550. this._boundingVectors.push(minPoint.clone());
  21551. this._boundingVectors[2].x = maxPoint.x;
  21552. this._boundingVectors.push(minPoint.clone());
  21553. this._boundingVectors[3].y = maxPoint.y;
  21554. this._boundingVectors.push(minPoint.clone());
  21555. this._boundingVectors[4].z = maxPoint.z;
  21556. this._boundingVectors.push(maxPoint.clone());
  21557. this._boundingVectors[5].z = minPoint.z;
  21558. this._boundingVectors.push(maxPoint.clone());
  21559. this._boundingVectors[6].x = minPoint.x;
  21560. this._boundingVectors.push(maxPoint.clone());
  21561. this._boundingVectors[7].y = minPoint.y;
  21562. }
  21563. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  21564. // Property
  21565. get: function () {
  21566. return this._capacity;
  21567. },
  21568. enumerable: true,
  21569. configurable: true
  21570. });
  21571. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  21572. get: function () {
  21573. return this._minPoint;
  21574. },
  21575. enumerable: true,
  21576. configurable: true
  21577. });
  21578. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  21579. get: function () {
  21580. return this._maxPoint;
  21581. },
  21582. enumerable: true,
  21583. configurable: true
  21584. });
  21585. // Methods
  21586. OctreeBlock.prototype.addEntry = function (entry) {
  21587. if (this.blocks) {
  21588. for (var index = 0; index < this.blocks.length; index++) {
  21589. var block = this.blocks[index];
  21590. block.addEntry(entry);
  21591. }
  21592. return;
  21593. }
  21594. this._creationFunc(entry, this);
  21595. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  21596. this.createInnerBlocks();
  21597. }
  21598. };
  21599. OctreeBlock.prototype.addEntries = function (entries) {
  21600. for (var index = 0; index < entries.length; index++) {
  21601. var mesh = entries[index];
  21602. this.addEntry(mesh);
  21603. }
  21604. };
  21605. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  21606. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  21607. if (this.blocks) {
  21608. for (var index = 0; index < this.blocks.length; index++) {
  21609. var block = this.blocks[index];
  21610. block.select(frustumPlanes, selection, allowDuplicate);
  21611. }
  21612. return;
  21613. }
  21614. if (allowDuplicate) {
  21615. selection.concat(this.entries);
  21616. }
  21617. else {
  21618. selection.concatWithNoDuplicate(this.entries);
  21619. }
  21620. }
  21621. };
  21622. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  21623. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  21624. if (this.blocks) {
  21625. for (var index = 0; index < this.blocks.length; index++) {
  21626. var block = this.blocks[index];
  21627. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  21628. }
  21629. return;
  21630. }
  21631. if (allowDuplicate) {
  21632. selection.concat(this.entries);
  21633. }
  21634. else {
  21635. selection.concatWithNoDuplicate(this.entries);
  21636. }
  21637. }
  21638. };
  21639. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  21640. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  21641. if (this.blocks) {
  21642. for (var index = 0; index < this.blocks.length; index++) {
  21643. var block = this.blocks[index];
  21644. block.intersectsRay(ray, selection);
  21645. }
  21646. return;
  21647. }
  21648. selection.concatWithNoDuplicate(this.entries);
  21649. }
  21650. };
  21651. OctreeBlock.prototype.createInnerBlocks = function () {
  21652. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  21653. };
  21654. return OctreeBlock;
  21655. })();
  21656. BABYLON.OctreeBlock = OctreeBlock;
  21657. })(BABYLON || (BABYLON = {}));
  21658. //# sourceMappingURL=babylon.octreeBlock.js.map
  21659. var BABYLON;
  21660. (function (BABYLON) {
  21661. var Bone = (function () {
  21662. function Bone(name, skeleton, parentBone, matrix) {
  21663. this.name = name;
  21664. this.children = new Array();
  21665. this.animations = new Array();
  21666. this._worldTransform = new BABYLON.Matrix();
  21667. this._absoluteTransform = new BABYLON.Matrix();
  21668. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21669. this._skeleton = skeleton;
  21670. this._matrix = matrix;
  21671. this._baseMatrix = matrix;
  21672. skeleton.bones.push(this);
  21673. if (parentBone) {
  21674. this._parent = parentBone;
  21675. parentBone.children.push(this);
  21676. }
  21677. else {
  21678. this._parent = null;
  21679. }
  21680. this._updateDifferenceMatrix();
  21681. }
  21682. // Members
  21683. Bone.prototype.getParent = function () {
  21684. return this._parent;
  21685. };
  21686. Bone.prototype.getLocalMatrix = function () {
  21687. return this._matrix;
  21688. };
  21689. Bone.prototype.getBaseMatrix = function () {
  21690. return this._baseMatrix;
  21691. };
  21692. Bone.prototype.getWorldMatrix = function () {
  21693. return this._worldTransform;
  21694. };
  21695. Bone.prototype.getInvertedAbsoluteTransform = function () {
  21696. return this._invertedAbsoluteTransform;
  21697. };
  21698. Bone.prototype.getAbsoluteMatrix = function () {
  21699. var matrix = this._matrix.clone();
  21700. var parent = this._parent;
  21701. while (parent) {
  21702. matrix = matrix.multiply(parent.getLocalMatrix());
  21703. parent = parent.getParent();
  21704. }
  21705. return matrix;
  21706. };
  21707. // Methods
  21708. Bone.prototype.updateMatrix = function (matrix) {
  21709. this._matrix = matrix;
  21710. this._skeleton._markAsDirty();
  21711. this._updateDifferenceMatrix();
  21712. };
  21713. Bone.prototype._updateDifferenceMatrix = function () {
  21714. if (this._parent) {
  21715. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  21716. }
  21717. else {
  21718. this._absoluteTransform.copyFrom(this._matrix);
  21719. }
  21720. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  21721. for (var index = 0; index < this.children.length; index++) {
  21722. this.children[index]._updateDifferenceMatrix();
  21723. }
  21724. };
  21725. Bone.prototype.markAsDirty = function () {
  21726. this._skeleton._markAsDirty();
  21727. };
  21728. return Bone;
  21729. })();
  21730. BABYLON.Bone = Bone;
  21731. })(BABYLON || (BABYLON = {}));
  21732. //# sourceMappingURL=babylon.bone.js.map
  21733. var BABYLON;
  21734. (function (BABYLON) {
  21735. var Skeleton = (function () {
  21736. function Skeleton(name, id, scene) {
  21737. this.name = name;
  21738. this.id = id;
  21739. this.bones = new Array();
  21740. this._isDirty = true;
  21741. this._identity = BABYLON.Matrix.Identity();
  21742. this.bones = [];
  21743. this._scene = scene;
  21744. scene.skeletons.push(this);
  21745. this.prepare();
  21746. //make sure it will recalculate the matrix next time prepare is called.
  21747. this._isDirty = true;
  21748. }
  21749. // Members
  21750. Skeleton.prototype.getTransformMatrices = function () {
  21751. return this._transformMatrices;
  21752. };
  21753. // Methods
  21754. Skeleton.prototype._markAsDirty = function () {
  21755. this._isDirty = true;
  21756. };
  21757. Skeleton.prototype.prepare = function () {
  21758. if (!this._isDirty) {
  21759. return;
  21760. }
  21761. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  21762. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  21763. }
  21764. for (var index = 0; index < this.bones.length; index++) {
  21765. var bone = this.bones[index];
  21766. var parentBone = bone.getParent();
  21767. if (parentBone) {
  21768. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  21769. }
  21770. else {
  21771. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  21772. }
  21773. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  21774. }
  21775. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  21776. this._isDirty = false;
  21777. this._scene._activeBones += this.bones.length;
  21778. };
  21779. Skeleton.prototype.getAnimatables = function () {
  21780. if (!this._animatables || this._animatables.length !== this.bones.length) {
  21781. this._animatables = [];
  21782. for (var index = 0; index < this.bones.length; index++) {
  21783. this._animatables.push(this.bones[index]);
  21784. }
  21785. }
  21786. return this._animatables;
  21787. };
  21788. Skeleton.prototype.clone = function (name, id) {
  21789. var result = new Skeleton(name, id || name, this._scene);
  21790. for (var index = 0; index < this.bones.length; index++) {
  21791. var source = this.bones[index];
  21792. var parentBone = null;
  21793. if (source.getParent()) {
  21794. var parentIndex = this.bones.indexOf(source.getParent());
  21795. parentBone = result.bones[parentIndex];
  21796. }
  21797. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  21798. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  21799. }
  21800. return result;
  21801. };
  21802. return Skeleton;
  21803. })();
  21804. BABYLON.Skeleton = Skeleton;
  21805. })(BABYLON || (BABYLON = {}));
  21806. //# sourceMappingURL=babylon.skeleton.js.map
  21807. var BABYLON;
  21808. (function (BABYLON) {
  21809. var PostProcess = (function () {
  21810. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  21811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  21812. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  21813. this.name = name;
  21814. this.width = -1;
  21815. this.height = -1;
  21816. this._reusable = false;
  21817. this._textures = new BABYLON.SmartArray(2);
  21818. this._currentRenderTextureInd = 0;
  21819. if (camera != null) {
  21820. this._camera = camera;
  21821. this._scene = camera.getScene();
  21822. camera.attachPostProcess(this);
  21823. this._engine = this._scene.getEngine();
  21824. }
  21825. else {
  21826. this._engine = engine;
  21827. }
  21828. this._renderRatio = ratio;
  21829. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  21830. this._reusable = reusable || false;
  21831. this._textureType = textureType;
  21832. samplers = samplers || [];
  21833. samplers.push("textureSampler");
  21834. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  21835. }
  21836. PostProcess.prototype.isReusable = function () {
  21837. return this._reusable;
  21838. };
  21839. PostProcess.prototype.activate = function (camera, sourceTexture) {
  21840. camera = camera || this._camera;
  21841. var scene = camera.getScene();
  21842. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  21843. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  21844. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  21845. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  21846. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  21847. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  21848. if (this._textures.length > 0) {
  21849. for (var i = 0; i < this._textures.length; i++) {
  21850. this._engine._releaseTexture(this._textures.data[i]);
  21851. }
  21852. this._textures.reset();
  21853. }
  21854. this.width = desiredWidth;
  21855. this.height = desiredHeight;
  21856. 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 }));
  21857. if (this._reusable) {
  21858. 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 }));
  21859. }
  21860. if (this.onSizeChanged) {
  21861. this.onSizeChanged();
  21862. }
  21863. }
  21864. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  21865. if (this.onActivate) {
  21866. this.onActivate(camera);
  21867. }
  21868. // Clear
  21869. if (this.clearColor) {
  21870. this._engine.clear(this.clearColor, true, true);
  21871. }
  21872. else {
  21873. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  21874. }
  21875. if (this._reusable) {
  21876. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  21877. }
  21878. };
  21879. PostProcess.prototype.apply = function () {
  21880. // Check
  21881. if (!this._effect.isReady())
  21882. return null;
  21883. // States
  21884. this._engine.enableEffect(this._effect);
  21885. this._engine.setState(false);
  21886. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21887. this._engine.setDepthBuffer(false);
  21888. this._engine.setDepthWrite(false);
  21889. // Texture
  21890. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  21891. // Parameters
  21892. if (this.onApply) {
  21893. this.onApply(this._effect);
  21894. }
  21895. return this._effect;
  21896. };
  21897. PostProcess.prototype.dispose = function (camera) {
  21898. camera = camera || this._camera;
  21899. if (this._textures.length > 0) {
  21900. for (var i = 0; i < this._textures.length; i++) {
  21901. this._engine._releaseTexture(this._textures.data[i]);
  21902. }
  21903. this._textures.reset();
  21904. }
  21905. if (!camera) {
  21906. return;
  21907. }
  21908. camera.detachPostProcess(this);
  21909. var index = camera._postProcesses.indexOf(this);
  21910. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  21911. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  21912. }
  21913. };
  21914. return PostProcess;
  21915. })();
  21916. BABYLON.PostProcess = PostProcess;
  21917. })(BABYLON || (BABYLON = {}));
  21918. //# sourceMappingURL=babylon.postProcess.js.map
  21919. var BABYLON;
  21920. (function (BABYLON) {
  21921. var PostProcessManager = (function () {
  21922. function PostProcessManager(scene) {
  21923. this._vertexDeclaration = [2];
  21924. this._vertexStrideSize = 2 * 4;
  21925. this._scene = scene;
  21926. }
  21927. PostProcessManager.prototype._prepareBuffers = function () {
  21928. if (this._vertexBuffer) {
  21929. return;
  21930. }
  21931. // VBO
  21932. var vertices = [];
  21933. vertices.push(1, 1);
  21934. vertices.push(-1, 1);
  21935. vertices.push(-1, -1);
  21936. vertices.push(1, -1);
  21937. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  21938. // Indices
  21939. var indices = [];
  21940. indices.push(0);
  21941. indices.push(1);
  21942. indices.push(2);
  21943. indices.push(0);
  21944. indices.push(2);
  21945. indices.push(3);
  21946. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  21947. };
  21948. // Methods
  21949. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  21950. var postProcesses = this._scene.activeCamera._postProcesses;
  21951. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21952. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21953. return false;
  21954. }
  21955. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  21956. return true;
  21957. };
  21958. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  21959. var engine = this._scene.getEngine();
  21960. for (var index = 0; index < postProcesses.length; index++) {
  21961. if (index < postProcesses.length - 1) {
  21962. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  21963. }
  21964. else {
  21965. if (targetTexture) {
  21966. engine.bindFramebuffer(targetTexture);
  21967. }
  21968. else {
  21969. engine.restoreDefaultFramebuffer();
  21970. }
  21971. }
  21972. var pp = postProcesses[index];
  21973. var effect = pp.apply();
  21974. if (effect) {
  21975. if (pp.onBeforeRender) {
  21976. pp.onBeforeRender(effect);
  21977. }
  21978. // VBOs
  21979. this._prepareBuffers();
  21980. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21981. // Draw order
  21982. engine.draw(true, 0, 6);
  21983. if (pp.onAfterRender) {
  21984. pp.onAfterRender(effect);
  21985. }
  21986. }
  21987. }
  21988. // Restore depth buffer
  21989. engine.setDepthBuffer(true);
  21990. engine.setDepthWrite(true);
  21991. };
  21992. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  21993. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  21994. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21995. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21996. return;
  21997. }
  21998. var engine = this._scene.getEngine();
  21999. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22000. if (index < postProcessesTakenIndices.length - 1) {
  22001. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22002. }
  22003. else {
  22004. if (targetTexture) {
  22005. engine.bindFramebuffer(targetTexture);
  22006. }
  22007. else {
  22008. engine.restoreDefaultFramebuffer();
  22009. }
  22010. }
  22011. if (doNotPresent) {
  22012. break;
  22013. }
  22014. var pp = postProcesses[postProcessesTakenIndices[index]];
  22015. var effect = pp.apply();
  22016. if (effect) {
  22017. if (pp.onBeforeRender) {
  22018. pp.onBeforeRender(effect);
  22019. }
  22020. // VBOs
  22021. this._prepareBuffers();
  22022. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22023. // Draw order
  22024. engine.draw(true, 0, 6);
  22025. if (pp.onAfterRender) {
  22026. pp.onAfterRender(effect);
  22027. }
  22028. }
  22029. }
  22030. // Restore depth buffer
  22031. engine.setDepthBuffer(true);
  22032. engine.setDepthWrite(true);
  22033. };
  22034. PostProcessManager.prototype.dispose = function () {
  22035. if (this._vertexBuffer) {
  22036. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22037. this._vertexBuffer = null;
  22038. }
  22039. if (this._indexBuffer) {
  22040. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22041. this._indexBuffer = null;
  22042. }
  22043. };
  22044. return PostProcessManager;
  22045. })();
  22046. BABYLON.PostProcessManager = PostProcessManager;
  22047. })(BABYLON || (BABYLON = {}));
  22048. //# sourceMappingURL=babylon.postProcessManager.js.map
  22049. var BABYLON;
  22050. (function (BABYLON) {
  22051. var PassPostProcess = (function (_super) {
  22052. __extends(PassPostProcess, _super);
  22053. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22054. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22055. }
  22056. return PassPostProcess;
  22057. })(BABYLON.PostProcess);
  22058. BABYLON.PassPostProcess = PassPostProcess;
  22059. })(BABYLON || (BABYLON = {}));
  22060. //# sourceMappingURL=babylon.passPostProcess.js.map
  22061. var BABYLON;
  22062. (function (BABYLON) {
  22063. var BlurPostProcess = (function (_super) {
  22064. __extends(BlurPostProcess, _super);
  22065. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22066. var _this = this;
  22067. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22068. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22069. this.direction = direction;
  22070. this.blurWidth = blurWidth;
  22071. this.onApply = function (effect) {
  22072. effect.setFloat2("screenSize", _this.width, _this.height);
  22073. effect.setVector2("direction", _this.direction);
  22074. effect.setFloat("blurWidth", _this.blurWidth);
  22075. };
  22076. }
  22077. return BlurPostProcess;
  22078. })(BABYLON.PostProcess);
  22079. BABYLON.BlurPostProcess = BlurPostProcess;
  22080. })(BABYLON || (BABYLON = {}));
  22081. //# sourceMappingURL=babylon.blurPostProcess.js.map
  22082. var BABYLON;
  22083. (function (BABYLON) {
  22084. var RefractionPostProcess = (function (_super) {
  22085. __extends(RefractionPostProcess, _super);
  22086. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22087. var _this = this;
  22088. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22089. this.color = color;
  22090. this.depth = depth;
  22091. this.colorLevel = colorLevel;
  22092. this.onActivate = function (cam) {
  22093. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22094. };
  22095. this.onApply = function (effect) {
  22096. effect.setColor3("baseColor", _this.color);
  22097. effect.setFloat("depth", _this.depth);
  22098. effect.setFloat("colorLevel", _this.colorLevel);
  22099. effect.setTexture("refractionSampler", _this._refRexture);
  22100. };
  22101. }
  22102. // Methods
  22103. RefractionPostProcess.prototype.dispose = function (camera) {
  22104. if (this._refRexture) {
  22105. this._refRexture.dispose();
  22106. }
  22107. _super.prototype.dispose.call(this, camera);
  22108. };
  22109. return RefractionPostProcess;
  22110. })(BABYLON.PostProcess);
  22111. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22112. })(BABYLON || (BABYLON = {}));
  22113. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  22114. var BABYLON;
  22115. (function (BABYLON) {
  22116. var BlackAndWhitePostProcess = (function (_super) {
  22117. __extends(BlackAndWhitePostProcess, _super);
  22118. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22119. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22120. }
  22121. return BlackAndWhitePostProcess;
  22122. })(BABYLON.PostProcess);
  22123. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22124. })(BABYLON || (BABYLON = {}));
  22125. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  22126. var BABYLON;
  22127. (function (BABYLON) {
  22128. var ConvolutionPostProcess = (function (_super) {
  22129. __extends(ConvolutionPostProcess, _super);
  22130. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22131. var _this = this;
  22132. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22133. this.kernel = kernel;
  22134. this.onApply = function (effect) {
  22135. effect.setFloat2("screenSize", _this.width, _this.height);
  22136. effect.setArray("kernel", _this.kernel);
  22137. };
  22138. }
  22139. // Statics
  22140. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22141. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22142. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22143. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22144. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22145. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22146. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22147. return ConvolutionPostProcess;
  22148. })(BABYLON.PostProcess);
  22149. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22150. })(BABYLON || (BABYLON = {}));
  22151. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  22152. var BABYLON;
  22153. (function (BABYLON) {
  22154. var FilterPostProcess = (function (_super) {
  22155. __extends(FilterPostProcess, _super);
  22156. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22157. var _this = this;
  22158. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22159. this.kernelMatrix = kernelMatrix;
  22160. this.onApply = function (effect) {
  22161. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22162. };
  22163. }
  22164. return FilterPostProcess;
  22165. })(BABYLON.PostProcess);
  22166. BABYLON.FilterPostProcess = FilterPostProcess;
  22167. })(BABYLON || (BABYLON = {}));
  22168. //# sourceMappingURL=babylon.filterPostProcess.js.map
  22169. var BABYLON;
  22170. (function (BABYLON) {
  22171. var FxaaPostProcess = (function (_super) {
  22172. __extends(FxaaPostProcess, _super);
  22173. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22174. var _this = this;
  22175. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22176. this.onSizeChanged = function () {
  22177. _this.texelWidth = 1.0 / _this.width;
  22178. _this.texelHeight = 1.0 / _this.height;
  22179. };
  22180. this.onApply = function (effect) {
  22181. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22182. };
  22183. }
  22184. return FxaaPostProcess;
  22185. })(BABYLON.PostProcess);
  22186. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22187. })(BABYLON || (BABYLON = {}));
  22188. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  22189. var BABYLON;
  22190. (function (BABYLON) {
  22191. var StereoscopicInterlacePostProcess = (function (_super) {
  22192. __extends(StereoscopicInterlacePostProcess, _super);
  22193. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  22194. var _this = this;
  22195. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  22196. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22197. this.onSizeChanged = function () {
  22198. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22199. };
  22200. this.onApply = function (effect) {
  22201. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22202. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22203. };
  22204. }
  22205. return StereoscopicInterlacePostProcess;
  22206. })(BABYLON.PostProcess);
  22207. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  22208. })(BABYLON || (BABYLON = {}));
  22209. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  22210. var BABYLON;
  22211. (function (BABYLON) {
  22212. var LensFlare = (function () {
  22213. function LensFlare(size, position, color, imgUrl, system) {
  22214. this.size = size;
  22215. this.position = position;
  22216. this.dispose = function () {
  22217. if (this.texture) {
  22218. this.texture.dispose();
  22219. }
  22220. // Remove from scene
  22221. var index = this._system.lensFlares.indexOf(this);
  22222. this._system.lensFlares.splice(index, 1);
  22223. };
  22224. this.color = color || new BABYLON.Color3(1, 1, 1);
  22225. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  22226. this._system = system;
  22227. system.lensFlares.push(this);
  22228. }
  22229. return LensFlare;
  22230. })();
  22231. BABYLON.LensFlare = LensFlare;
  22232. })(BABYLON || (BABYLON = {}));
  22233. //# sourceMappingURL=babylon.lensFlare.js.map
  22234. var BABYLON;
  22235. (function (BABYLON) {
  22236. var LensFlareSystem = (function () {
  22237. function LensFlareSystem(name, emitter, scene) {
  22238. this.name = name;
  22239. this.lensFlares = new Array();
  22240. this.borderLimit = 300;
  22241. this._vertexDeclaration = [2];
  22242. this._vertexStrideSize = 2 * 4;
  22243. this._isEnabled = true;
  22244. this._scene = scene;
  22245. this._emitter = emitter;
  22246. scene.lensFlareSystems.push(this);
  22247. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  22248. // VBO
  22249. var vertices = [];
  22250. vertices.push(1, 1);
  22251. vertices.push(-1, 1);
  22252. vertices.push(-1, -1);
  22253. vertices.push(1, -1);
  22254. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  22255. // Indices
  22256. var indices = [];
  22257. indices.push(0);
  22258. indices.push(1);
  22259. indices.push(2);
  22260. indices.push(0);
  22261. indices.push(2);
  22262. indices.push(3);
  22263. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22264. // Effects
  22265. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  22266. }
  22267. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  22268. get: function () {
  22269. return this._isEnabled;
  22270. },
  22271. set: function (value) {
  22272. this._isEnabled = value;
  22273. },
  22274. enumerable: true,
  22275. configurable: true
  22276. });
  22277. LensFlareSystem.prototype.getScene = function () {
  22278. return this._scene;
  22279. };
  22280. LensFlareSystem.prototype.getEmitter = function () {
  22281. return this._emitter;
  22282. };
  22283. LensFlareSystem.prototype.getEmitterPosition = function () {
  22284. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  22285. };
  22286. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  22287. var position = this.getEmitterPosition();
  22288. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  22289. this._positionX = position.x;
  22290. this._positionY = position.y;
  22291. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  22292. if (position.z > 0) {
  22293. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  22294. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  22295. return true;
  22296. }
  22297. }
  22298. return false;
  22299. };
  22300. LensFlareSystem.prototype._isVisible = function () {
  22301. if (!this._isEnabled) {
  22302. return false;
  22303. }
  22304. var emitterPosition = this.getEmitterPosition();
  22305. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  22306. var distance = direction.length();
  22307. direction.normalize();
  22308. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  22309. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  22310. return !pickInfo.hit || pickInfo.distance > distance;
  22311. };
  22312. LensFlareSystem.prototype.render = function () {
  22313. if (!this._effect.isReady())
  22314. return false;
  22315. var engine = this._scene.getEngine();
  22316. var viewport = this._scene.activeCamera.viewport;
  22317. var globalViewport = viewport.toGlobal(engine);
  22318. // Position
  22319. if (!this.computeEffectivePosition(globalViewport)) {
  22320. return false;
  22321. }
  22322. // Visibility
  22323. if (!this._isVisible()) {
  22324. return false;
  22325. }
  22326. // Intensity
  22327. var awayX;
  22328. var awayY;
  22329. if (this._positionX < this.borderLimit + globalViewport.x) {
  22330. awayX = this.borderLimit + globalViewport.x - this._positionX;
  22331. }
  22332. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  22333. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  22334. }
  22335. else {
  22336. awayX = 0;
  22337. }
  22338. if (this._positionY < this.borderLimit + globalViewport.y) {
  22339. awayY = this.borderLimit + globalViewport.y - this._positionY;
  22340. }
  22341. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  22342. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  22343. }
  22344. else {
  22345. awayY = 0;
  22346. }
  22347. var away = (awayX > awayY) ? awayX : awayY;
  22348. if (away > this.borderLimit) {
  22349. away = this.borderLimit;
  22350. }
  22351. var intensity = 1.0 - (away / this.borderLimit);
  22352. if (intensity < 0) {
  22353. return false;
  22354. }
  22355. if (intensity > 1.0) {
  22356. intensity = 1.0;
  22357. }
  22358. // Position
  22359. var centerX = globalViewport.x + globalViewport.width / 2;
  22360. var centerY = globalViewport.y + globalViewport.height / 2;
  22361. var distX = centerX - this._positionX;
  22362. var distY = centerY - this._positionY;
  22363. // Effects
  22364. engine.enableEffect(this._effect);
  22365. engine.setState(false);
  22366. engine.setDepthBuffer(false);
  22367. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  22368. // VBOs
  22369. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  22370. // Flares
  22371. for (var index = 0; index < this.lensFlares.length; index++) {
  22372. var flare = this.lensFlares[index];
  22373. var x = centerX - (distX * flare.position);
  22374. var y = centerY - (distY * flare.position);
  22375. var cw = flare.size;
  22376. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  22377. var cx = 2 * (x / globalViewport.width) - 1.0;
  22378. var cy = 1.0 - 2 * (y / globalViewport.height);
  22379. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  22380. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  22381. // Texture
  22382. this._effect.setTexture("textureSampler", flare.texture);
  22383. // Color
  22384. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  22385. // Draw order
  22386. engine.draw(true, 0, 6);
  22387. }
  22388. engine.setDepthBuffer(true);
  22389. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22390. return true;
  22391. };
  22392. LensFlareSystem.prototype.dispose = function () {
  22393. if (this._vertexBuffer) {
  22394. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22395. this._vertexBuffer = null;
  22396. }
  22397. if (this._indexBuffer) {
  22398. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22399. this._indexBuffer = null;
  22400. }
  22401. while (this.lensFlares.length) {
  22402. this.lensFlares[0].dispose();
  22403. }
  22404. // Remove from scene
  22405. var index = this._scene.lensFlareSystems.indexOf(this);
  22406. this._scene.lensFlareSystems.splice(index, 1);
  22407. };
  22408. return LensFlareSystem;
  22409. })();
  22410. BABYLON.LensFlareSystem = LensFlareSystem;
  22411. })(BABYLON || (BABYLON = {}));
  22412. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  22413. var BABYLON;
  22414. (function (BABYLON) {
  22415. var CannonJSPlugin = (function () {
  22416. function CannonJSPlugin() {
  22417. this._registeredMeshes = [];
  22418. this._physicsMaterials = [];
  22419. this.updateBodyPosition = function (mesh) {
  22420. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22421. var registeredMesh = this._registeredMeshes[index];
  22422. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22423. var body = registeredMesh.body;
  22424. var center = mesh.getBoundingInfo().boundingBox.center;
  22425. body.position.set(center.x, center.z, center.y);
  22426. body.quaternion.x = mesh.rotationQuaternion.x;
  22427. body.quaternion.z = mesh.rotationQuaternion.y;
  22428. body.quaternion.y = mesh.rotationQuaternion.z;
  22429. body.quaternion.w = -mesh.rotationQuaternion.w;
  22430. return;
  22431. }
  22432. }
  22433. };
  22434. }
  22435. CannonJSPlugin.prototype.initialize = function (iterations) {
  22436. if (iterations === void 0) { iterations = 10; }
  22437. this._world = new CANNON.World();
  22438. this._world.broadphase = new CANNON.NaiveBroadphase();
  22439. this._world.solver.iterations = iterations;
  22440. };
  22441. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22442. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22443. };
  22444. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22445. this._world.step(delta);
  22446. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22447. var registeredMesh = this._registeredMeshes[index];
  22448. if (registeredMesh.isChild) {
  22449. continue;
  22450. }
  22451. // Body position
  22452. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22453. var deltaPos = registeredMesh.delta;
  22454. if (deltaPos) {
  22455. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22456. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22457. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22458. }
  22459. else {
  22460. registeredMesh.mesh.position.x = bodyX;
  22461. registeredMesh.mesh.position.y = bodyZ;
  22462. registeredMesh.mesh.position.z = bodyY;
  22463. }
  22464. if (!registeredMesh.mesh.rotationQuaternion) {
  22465. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22466. }
  22467. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22468. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22469. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22470. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22471. }
  22472. };
  22473. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22474. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22475. };
  22476. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22477. this.unregisterMesh(mesh);
  22478. mesh.computeWorldMatrix(true);
  22479. switch (impostor) {
  22480. case BABYLON.PhysicsEngine.SphereImpostor:
  22481. var bbox = mesh.getBoundingInfo().boundingBox;
  22482. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22483. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22484. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22485. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22486. case BABYLON.PhysicsEngine.BoxImpostor:
  22487. bbox = mesh.getBoundingInfo().boundingBox;
  22488. var min = bbox.minimumWorld;
  22489. var max = bbox.maximumWorld;
  22490. var box = max.subtract(min).scale(0.5);
  22491. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22492. case BABYLON.PhysicsEngine.PlaneImpostor:
  22493. return this._createPlane(mesh, options);
  22494. case BABYLON.PhysicsEngine.MeshImpostor:
  22495. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22496. var rawFaces = mesh.getIndices();
  22497. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22498. }
  22499. return null;
  22500. };
  22501. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22502. var shape = new CANNON.Sphere(radius);
  22503. if (!options) {
  22504. return shape;
  22505. }
  22506. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22507. };
  22508. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22509. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22510. if (!options) {
  22511. return shape;
  22512. }
  22513. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22514. };
  22515. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22516. var shape = new CANNON.Plane();
  22517. if (!options) {
  22518. return shape;
  22519. }
  22520. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22521. };
  22522. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22523. var verts = [], faces = [];
  22524. mesh.computeWorldMatrix(true);
  22525. // Get vertices
  22526. for (var i = 0; i < rawVerts.length; i += 3) {
  22527. var transformed = BABYLON.Vector3.Zero();
  22528. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22529. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22530. }
  22531. // Get faces
  22532. for (var j = 0; j < rawFaces.length; j += 3) {
  22533. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22534. }
  22535. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22536. if (!options) {
  22537. return shape;
  22538. }
  22539. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22540. };
  22541. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22542. var index;
  22543. var mat;
  22544. for (index = 0; index < this._physicsMaterials.length; index++) {
  22545. mat = this._physicsMaterials[index];
  22546. if (mat.friction === friction && mat.restitution === restitution) {
  22547. return mat;
  22548. }
  22549. }
  22550. var currentMat = new CANNON.Material();
  22551. currentMat.friction = friction;
  22552. currentMat.restitution = restitution;
  22553. this._physicsMaterials.push(currentMat);
  22554. for (index = 0; index < this._physicsMaterials.length; index++) {
  22555. mat = this._physicsMaterials[index];
  22556. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22557. contactMaterial.contactEquationStiffness = 1e10;
  22558. contactMaterial.contactEquationRegularizationTime = 10;
  22559. this._world.addContactMaterial(contactMaterial);
  22560. }
  22561. return currentMat;
  22562. };
  22563. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22564. var initialRotation = null;
  22565. if (mesh.rotationQuaternion) {
  22566. initialRotation = mesh.rotationQuaternion.clone();
  22567. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22568. }
  22569. // The delta between the mesh position and the mesh bounding box center
  22570. var bbox = mesh.getBoundingInfo().boundingBox;
  22571. var deltaPosition = mesh.position.subtract(bbox.center);
  22572. var material = this._addMaterial(friction, restitution);
  22573. var body = new CANNON.RigidBody(mass, shape, material);
  22574. if (initialRotation) {
  22575. body.quaternion.x = initialRotation.x;
  22576. body.quaternion.z = initialRotation.y;
  22577. body.quaternion.y = initialRotation.z;
  22578. body.quaternion.w = -initialRotation.w;
  22579. }
  22580. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22581. this._world.add(body);
  22582. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22583. return body;
  22584. };
  22585. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22586. var compoundShape = new CANNON.Compound();
  22587. for (var index = 0; index < parts.length; index++) {
  22588. var mesh = parts[index].mesh;
  22589. var shape = this.registerMesh(mesh, parts[index].impostor);
  22590. if (index == 0) {
  22591. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22592. }
  22593. else {
  22594. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22595. }
  22596. }
  22597. var initialMesh = parts[0].mesh;
  22598. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22599. body.parts = parts;
  22600. return body;
  22601. };
  22602. CannonJSPlugin.prototype._unbindBody = function (body) {
  22603. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22604. var registeredMesh = this._registeredMeshes[index];
  22605. if (registeredMesh.body === body) {
  22606. registeredMesh.body = null;
  22607. registeredMesh.delta = 0;
  22608. }
  22609. }
  22610. };
  22611. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22612. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22613. var registeredMesh = this._registeredMeshes[index];
  22614. if (registeredMesh.mesh === mesh) {
  22615. // Remove body
  22616. if (registeredMesh.body) {
  22617. this._world.remove(registeredMesh.body);
  22618. this._unbindBody(registeredMesh.body);
  22619. }
  22620. this._registeredMeshes.splice(index, 1);
  22621. return;
  22622. }
  22623. }
  22624. };
  22625. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22626. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22627. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22628. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22629. var registeredMesh = this._registeredMeshes[index];
  22630. if (registeredMesh.mesh === mesh) {
  22631. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22632. return;
  22633. }
  22634. }
  22635. };
  22636. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22637. var body1 = null, body2 = null;
  22638. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22639. var registeredMesh = this._registeredMeshes[index];
  22640. if (registeredMesh.mesh === mesh1) {
  22641. body1 = registeredMesh.body;
  22642. }
  22643. else if (registeredMesh.mesh === mesh2) {
  22644. body2 = registeredMesh.body;
  22645. }
  22646. }
  22647. if (!body1 || !body2) {
  22648. return false;
  22649. }
  22650. 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));
  22651. this._world.addConstraint(constraint);
  22652. return true;
  22653. };
  22654. CannonJSPlugin.prototype.dispose = function () {
  22655. while (this._registeredMeshes.length) {
  22656. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22657. }
  22658. };
  22659. CannonJSPlugin.prototype.isSupported = function () {
  22660. return window.CANNON !== undefined;
  22661. };
  22662. return CannonJSPlugin;
  22663. })();
  22664. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22665. })(BABYLON || (BABYLON = {}));
  22666. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22667. var BABYLON;
  22668. (function (BABYLON) {
  22669. var OimoJSPlugin = (function () {
  22670. function OimoJSPlugin() {
  22671. this._registeredMeshes = [];
  22672. /**
  22673. * Update the body position according to the mesh position
  22674. * @param mesh
  22675. */
  22676. this.updateBodyPosition = function (mesh) {
  22677. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22678. var registeredMesh = this._registeredMeshes[index];
  22679. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22680. var body = registeredMesh.body.body;
  22681. mesh.computeWorldMatrix(true);
  22682. var center = mesh.getBoundingInfo().boundingBox.center;
  22683. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  22684. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  22685. body.sleeping = false;
  22686. return;
  22687. }
  22688. // Case where the parent has been updated
  22689. if (registeredMesh.mesh.parent === mesh) {
  22690. mesh.computeWorldMatrix(true);
  22691. registeredMesh.mesh.computeWorldMatrix(true);
  22692. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  22693. var absoluteRotation = mesh.rotation;
  22694. body = registeredMesh.body.body;
  22695. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  22696. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  22697. body.sleeping = false;
  22698. return;
  22699. }
  22700. }
  22701. };
  22702. }
  22703. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  22704. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22705. };
  22706. OimoJSPlugin.prototype.initialize = function (iterations) {
  22707. this._world = new OIMO.World();
  22708. this._world.clear();
  22709. };
  22710. OimoJSPlugin.prototype.setGravity = function (gravity) {
  22711. this._world.gravity = gravity;
  22712. };
  22713. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22714. var body = null;
  22715. this.unregisterMesh(mesh);
  22716. mesh.computeWorldMatrix(true);
  22717. var initialRotation = null;
  22718. if (mesh.rotationQuaternion) {
  22719. initialRotation = mesh.rotationQuaternion.clone();
  22720. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22721. mesh.computeWorldMatrix(true);
  22722. }
  22723. var bbox = mesh.getBoundingInfo().boundingBox;
  22724. // The delta between the mesh position and the mesh bounding box center
  22725. var deltaPosition = mesh.position.subtract(bbox.center);
  22726. // Transform delta position with the rotation
  22727. if (initialRotation) {
  22728. var m = new BABYLON.Matrix();
  22729. initialRotation.toRotationMatrix(m);
  22730. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  22731. }
  22732. // register mesh
  22733. switch (impostor) {
  22734. case BABYLON.PhysicsEngine.SphereImpostor:
  22735. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22736. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22737. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22738. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22739. body = new OIMO.Body({
  22740. type: 'sphere',
  22741. size: [size],
  22742. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22743. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22744. move: options.mass != 0,
  22745. config: [options.mass, options.friction, options.restitution],
  22746. world: this._world
  22747. });
  22748. break;
  22749. case BABYLON.PhysicsEngine.PlaneImpostor:
  22750. //Oimo "fakes" a cylinder as a box, so why don't we!
  22751. case BABYLON.PhysicsEngine.CylinderImpostor:
  22752. case BABYLON.PhysicsEngine.BoxImpostor:
  22753. var min = bbox.minimumWorld;
  22754. var max = bbox.maximumWorld;
  22755. var box = max.subtract(min);
  22756. var sizeX = this._checkWithEpsilon(box.x);
  22757. var sizeY = this._checkWithEpsilon(box.y);
  22758. var sizeZ = this._checkWithEpsilon(box.z);
  22759. body = new OIMO.Body({
  22760. type: 'box',
  22761. size: [sizeX, sizeY, sizeZ],
  22762. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22763. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22764. move: options.mass != 0,
  22765. config: [options.mass, options.friction, options.restitution],
  22766. world: this._world
  22767. });
  22768. break;
  22769. }
  22770. //If quaternion was set as the rotation of the object
  22771. if (initialRotation) {
  22772. //We have to access the rigid body's properties to set the quaternion.
  22773. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  22774. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  22775. //update the internal rotation matrix
  22776. body.body.syncShapes();
  22777. }
  22778. this._registeredMeshes.push({
  22779. mesh: mesh,
  22780. body: body,
  22781. delta: deltaPosition
  22782. });
  22783. return body;
  22784. };
  22785. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22786. var types = [], sizes = [], positions = [], rotations = [];
  22787. var initialMesh = parts[0].mesh;
  22788. for (var index = 0; index < parts.length; index++) {
  22789. var part = parts[index];
  22790. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  22791. types.push(bodyParameters.type);
  22792. sizes.push.apply(sizes, bodyParameters.size);
  22793. positions.push.apply(positions, bodyParameters.pos);
  22794. rotations.push.apply(rotations, bodyParameters.rot);
  22795. }
  22796. var body = new OIMO.Body({
  22797. type: types,
  22798. size: sizes,
  22799. pos: positions,
  22800. rot: rotations,
  22801. move: options.mass != 0,
  22802. config: [options.mass, options.friction, options.restitution],
  22803. world: this._world
  22804. });
  22805. this._registeredMeshes.push({
  22806. mesh: initialMesh,
  22807. body: body
  22808. });
  22809. return body;
  22810. };
  22811. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  22812. var bodyParameters = null;
  22813. var mesh = part.mesh;
  22814. // We need the bounding box/sphere info to compute the physics body
  22815. mesh.computeWorldMatrix();
  22816. switch (part.impostor) {
  22817. case BABYLON.PhysicsEngine.SphereImpostor:
  22818. var bbox = mesh.getBoundingInfo().boundingBox;
  22819. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22820. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22821. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22822. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22823. bodyParameters = {
  22824. type: 'sphere',
  22825. /* bug with oimo : sphere needs 3 sizes in this case */
  22826. size: [size, -1, -1],
  22827. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  22828. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22829. };
  22830. break;
  22831. case BABYLON.PhysicsEngine.PlaneImpostor:
  22832. case BABYLON.PhysicsEngine.BoxImpostor:
  22833. bbox = mesh.getBoundingInfo().boundingBox;
  22834. var min = bbox.minimumWorld;
  22835. var max = bbox.maximumWorld;
  22836. var box = max.subtract(min);
  22837. var sizeX = this._checkWithEpsilon(box.x);
  22838. var sizeY = this._checkWithEpsilon(box.y);
  22839. var sizeZ = this._checkWithEpsilon(box.z);
  22840. var relativePosition = mesh.position;
  22841. bodyParameters = {
  22842. type: 'box',
  22843. size: [sizeX, sizeY, sizeZ],
  22844. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  22845. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22846. };
  22847. break;
  22848. }
  22849. return bodyParameters;
  22850. };
  22851. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  22852. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22853. var registeredMesh = this._registeredMeshes[index];
  22854. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22855. if (registeredMesh.body) {
  22856. this._world.removeRigidBody(registeredMesh.body.body);
  22857. this._unbindBody(registeredMesh.body);
  22858. }
  22859. this._registeredMeshes.splice(index, 1);
  22860. return;
  22861. }
  22862. }
  22863. };
  22864. OimoJSPlugin.prototype._unbindBody = function (body) {
  22865. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22866. var registeredMesh = this._registeredMeshes[index];
  22867. if (registeredMesh.body === body) {
  22868. registeredMesh.body = null;
  22869. }
  22870. }
  22871. };
  22872. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22873. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22874. var registeredMesh = this._registeredMeshes[index];
  22875. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22876. // Get object mass to have a behaviour similar to cannon.js
  22877. var mass = registeredMesh.body.body.massInfo.mass;
  22878. // The force is scaled with the mass of object
  22879. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  22880. return;
  22881. }
  22882. }
  22883. };
  22884. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22885. var body1 = null, body2 = null;
  22886. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22887. var registeredMesh = this._registeredMeshes[index];
  22888. if (registeredMesh.mesh === mesh1) {
  22889. body1 = registeredMesh.body.body;
  22890. }
  22891. else if (registeredMesh.mesh === mesh2) {
  22892. body2 = registeredMesh.body.body;
  22893. }
  22894. }
  22895. if (!body1 || !body2) {
  22896. return false;
  22897. }
  22898. if (!options) {
  22899. options = {};
  22900. }
  22901. new OIMO.Link({
  22902. type: options.type,
  22903. body1: body1,
  22904. body2: body2,
  22905. min: options.min,
  22906. max: options.max,
  22907. axe1: options.axe1,
  22908. axe2: options.axe2,
  22909. pos1: [pivot1.x, pivot1.y, pivot1.z],
  22910. pos2: [pivot2.x, pivot2.y, pivot2.z],
  22911. collision: options.collision,
  22912. spring: options.spring,
  22913. world: this._world
  22914. });
  22915. return true;
  22916. };
  22917. OimoJSPlugin.prototype.dispose = function () {
  22918. this._world.clear();
  22919. while (this._registeredMeshes.length) {
  22920. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22921. }
  22922. };
  22923. OimoJSPlugin.prototype.isSupported = function () {
  22924. return OIMO !== undefined;
  22925. };
  22926. OimoJSPlugin.prototype._getLastShape = function (body) {
  22927. var lastShape = body.shapes;
  22928. while (lastShape.next) {
  22929. lastShape = lastShape.next;
  22930. }
  22931. return lastShape;
  22932. };
  22933. OimoJSPlugin.prototype.runOneStep = function (time) {
  22934. this._world.step();
  22935. // Update the position of all registered meshes
  22936. var i = this._registeredMeshes.length;
  22937. var m;
  22938. while (i--) {
  22939. var body = this._registeredMeshes[i].body.body;
  22940. var mesh = this._registeredMeshes[i].mesh;
  22941. var delta = this._registeredMeshes[i].delta;
  22942. if (!body.sleeping) {
  22943. if (body.shapes.next) {
  22944. var parentShape = this._getLastShape(body);
  22945. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  22946. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  22947. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  22948. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  22949. if (!mesh.rotationQuaternion) {
  22950. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22951. }
  22952. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  22953. mesh.computeWorldMatrix();
  22954. }
  22955. else {
  22956. m = body.getMatrix();
  22957. mtx = BABYLON.Matrix.FromArray(m);
  22958. // Body position
  22959. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  22960. if (!delta) {
  22961. mesh.position.x = bodyX;
  22962. mesh.position.y = bodyY;
  22963. mesh.position.z = bodyZ;
  22964. }
  22965. else {
  22966. mesh.position.x = bodyX + delta.x;
  22967. mesh.position.y = bodyY + delta.y;
  22968. mesh.position.z = bodyZ + delta.z;
  22969. }
  22970. if (!mesh.rotationQuaternion) {
  22971. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22972. }
  22973. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  22974. mesh.computeWorldMatrix();
  22975. }
  22976. }
  22977. }
  22978. };
  22979. return OimoJSPlugin;
  22980. })();
  22981. BABYLON.OimoJSPlugin = OimoJSPlugin;
  22982. })(BABYLON || (BABYLON = {}));
  22983. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  22984. var BABYLON;
  22985. (function (BABYLON) {
  22986. var PhysicsEngine = (function () {
  22987. function PhysicsEngine(plugin) {
  22988. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22989. }
  22990. PhysicsEngine.prototype._initialize = function (gravity) {
  22991. this._currentPlugin.initialize();
  22992. this._setGravity(gravity);
  22993. };
  22994. PhysicsEngine.prototype._runOneStep = function (delta) {
  22995. if (delta > 0.1) {
  22996. delta = 0.1;
  22997. }
  22998. else if (delta <= 0) {
  22999. delta = 1.0 / 60.0;
  23000. }
  23001. this._currentPlugin.runOneStep(delta);
  23002. };
  23003. PhysicsEngine.prototype._setGravity = function (gravity) {
  23004. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23005. this._currentPlugin.setGravity(this.gravity);
  23006. };
  23007. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23008. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23009. };
  23010. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23011. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23012. };
  23013. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23014. this._currentPlugin.unregisterMesh(mesh);
  23015. };
  23016. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23017. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23018. };
  23019. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23020. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23021. };
  23022. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23023. this._currentPlugin.updateBodyPosition(mesh);
  23024. };
  23025. PhysicsEngine.prototype.dispose = function () {
  23026. this._currentPlugin.dispose();
  23027. };
  23028. PhysicsEngine.prototype.isSupported = function () {
  23029. return this._currentPlugin.isSupported();
  23030. };
  23031. // Statics
  23032. PhysicsEngine.NoImpostor = 0;
  23033. PhysicsEngine.SphereImpostor = 1;
  23034. PhysicsEngine.BoxImpostor = 2;
  23035. PhysicsEngine.PlaneImpostor = 3;
  23036. PhysicsEngine.MeshImpostor = 4;
  23037. PhysicsEngine.CapsuleImpostor = 5;
  23038. PhysicsEngine.ConeImpostor = 6;
  23039. PhysicsEngine.CylinderImpostor = 7;
  23040. PhysicsEngine.ConvexHullImpostor = 8;
  23041. PhysicsEngine.Epsilon = 0.001;
  23042. return PhysicsEngine;
  23043. })();
  23044. BABYLON.PhysicsEngine = PhysicsEngine;
  23045. })(BABYLON || (BABYLON = {}));
  23046. //# sourceMappingURL=babylon.physicsEngine.js.map
  23047. var BABYLON;
  23048. (function (BABYLON) {
  23049. var serializeLight = function (light) {
  23050. var serializationObject = {};
  23051. serializationObject.name = light.name;
  23052. serializationObject.id = light.id;
  23053. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23054. if (light instanceof BABYLON.PointLight) {
  23055. serializationObject.type = 0;
  23056. serializationObject.position = light.position.asArray();
  23057. }
  23058. else if (light instanceof BABYLON.DirectionalLight) {
  23059. serializationObject.type = 1;
  23060. var directionalLight = light;
  23061. serializationObject.position = directionalLight.position.asArray();
  23062. serializationObject.direction = directionalLight.direction.asArray();
  23063. }
  23064. else if (light instanceof BABYLON.SpotLight) {
  23065. serializationObject.type = 2;
  23066. var spotLight = light;
  23067. serializationObject.position = spotLight.position.asArray();
  23068. serializationObject.direction = spotLight.position.asArray();
  23069. serializationObject.angle = spotLight.angle;
  23070. serializationObject.exponent = spotLight.exponent;
  23071. }
  23072. else if (light instanceof BABYLON.HemisphericLight) {
  23073. serializationObject.type = 3;
  23074. var hemisphericLight = light;
  23075. serializationObject.direction = hemisphericLight.direction.asArray();
  23076. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23077. }
  23078. if (light.intensity) {
  23079. serializationObject.intensity = light.intensity;
  23080. }
  23081. serializationObject.range = light.range;
  23082. serializationObject.diffuse = light.diffuse.asArray();
  23083. serializationObject.specular = light.specular.asArray();
  23084. return serializationObject;
  23085. };
  23086. var serializeFresnelParameter = function (fresnelParameter) {
  23087. var serializationObject = {};
  23088. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23089. serializationObject.leftColor = fresnelParameter.leftColor;
  23090. serializationObject.rightColor = fresnelParameter.rightColor;
  23091. serializationObject.bias = fresnelParameter.bias;
  23092. serializationObject.power = fresnelParameter.power;
  23093. return serializationObject;
  23094. };
  23095. var appendAnimations = function (source, destination) {
  23096. if (source.animations) {
  23097. destination.animations = [];
  23098. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23099. var animation = source.animations[animationIndex];
  23100. destination.animations.push(serializeAnimation(animation));
  23101. }
  23102. }
  23103. };
  23104. var serializeCamera = function (camera) {
  23105. var serializationObject = {};
  23106. serializationObject.name = camera.name;
  23107. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23108. serializationObject.id = camera.id;
  23109. serializationObject.position = camera.position.asArray();
  23110. // Parent
  23111. if (camera.parent) {
  23112. serializationObject.parentId = camera.parent.id;
  23113. }
  23114. serializationObject.fov = camera.fov;
  23115. serializationObject.minZ = camera.minZ;
  23116. serializationObject.maxZ = camera.maxZ;
  23117. serializationObject.inertia = camera.inertia;
  23118. //setting the type
  23119. if (camera instanceof BABYLON.FreeCamera) {
  23120. serializationObject.type = "FreeCamera";
  23121. }
  23122. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23123. serializationObject.type = "ArcRotateCamera";
  23124. }
  23125. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23126. serializationObject.type = "AnaglyphArcRotateCamera";
  23127. }
  23128. else if (camera instanceof BABYLON.GamepadCamera) {
  23129. serializationObject.type = "GamepadCamera";
  23130. }
  23131. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23132. serializationObject.type = "AnaglyphFreeCamera";
  23133. }
  23134. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23135. serializationObject.type = "DeviceOrientationCamera";
  23136. }
  23137. else if (camera instanceof BABYLON.FollowCamera) {
  23138. serializationObject.type = "FollowCamera";
  23139. }
  23140. else if (camera instanceof BABYLON.TouchCamera) {
  23141. serializationObject.type = "TouchCamera";
  23142. }
  23143. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23144. serializationObject.type = "VirtualJoysticksCamera";
  23145. }
  23146. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23147. serializationObject.type = "WebVRFreeCamera";
  23148. }
  23149. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23150. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23151. }
  23152. //special properties of specific cameras
  23153. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23154. var arcCamera = camera;
  23155. serializationObject.alpha = arcCamera.alpha;
  23156. serializationObject.beta = arcCamera.beta;
  23157. serializationObject.radius = arcCamera.radius;
  23158. if (arcCamera.target && arcCamera.target.id) {
  23159. serializationObject.lockedTargetId = arcCamera.target.id;
  23160. }
  23161. }
  23162. else if (camera instanceof BABYLON.FollowCamera) {
  23163. var followCam = camera;
  23164. serializationObject.radius = followCam.radius;
  23165. serializationObject.heightOffset = followCam.heightOffset;
  23166. serializationObject.rotationOffset = followCam.rotationOffset;
  23167. }
  23168. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23169. //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.
  23170. if (camera['_interaxialDistance'] !== undefined) {
  23171. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  23172. }
  23173. }
  23174. //general properties that not all cameras have. The [] is due to typescript's type safety
  23175. if (camera['speed'] !== undefined) {
  23176. serializationObject.speed = camera['speed'];
  23177. }
  23178. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23179. serializationObject.target = camera['target'].asArray();
  23180. }
  23181. // Target
  23182. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23183. serializationObject.rotation = camera['rotation'].asArray();
  23184. }
  23185. // Locked target
  23186. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23187. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23188. }
  23189. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23190. serializationObject.applyGravity = camera['applyGravity'] || false;
  23191. if (camera['ellipsoid']) {
  23192. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23193. }
  23194. // Animations
  23195. appendAnimations(camera, serializationObject);
  23196. // Layer mask
  23197. serializationObject.layerMask = camera.layerMask;
  23198. return serializationObject;
  23199. };
  23200. var serializeAnimation = function (animation) {
  23201. var serializationObject = {};
  23202. serializationObject.name = animation.name;
  23203. serializationObject.property = animation.targetProperty;
  23204. serializationObject.framePerSecond = animation.framePerSecond;
  23205. serializationObject.dataType = animation.dataType;
  23206. serializationObject.loopBehavior = animation.loopMode;
  23207. var dataType = animation.dataType;
  23208. serializationObject.keys = [];
  23209. var keys = animation.getKeys();
  23210. for (var index = 0; index < keys.length; index++) {
  23211. var animationKey = keys[index];
  23212. var key = {};
  23213. key.frame = animationKey.frame;
  23214. switch (dataType) {
  23215. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23216. key.values = [animationKey.value];
  23217. break;
  23218. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23219. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23220. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23221. key.values = animationKey.value.asArray();
  23222. break;
  23223. }
  23224. serializationObject.keys.push(key);
  23225. }
  23226. return serializationObject;
  23227. };
  23228. var serializeMultiMaterial = function (material) {
  23229. var serializationObject = {};
  23230. serializationObject.name = material.name;
  23231. serializationObject.id = material.id;
  23232. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23233. serializationObject.materials = [];
  23234. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  23235. var subMat = material.subMaterials[matIndex];
  23236. if (subMat) {
  23237. serializationObject.materials.push(subMat.id);
  23238. }
  23239. else {
  23240. serializationObject.materials.push(null);
  23241. }
  23242. }
  23243. return serializationObject;
  23244. };
  23245. var serializeMaterial = function (material) {
  23246. var serializationObject = {};
  23247. serializationObject.name = material.name;
  23248. serializationObject.ambient = material.ambientColor.asArray();
  23249. serializationObject.diffuse = material.diffuseColor.asArray();
  23250. serializationObject.specular = material.specularColor.asArray();
  23251. serializationObject.specularPower = material.specularPower;
  23252. serializationObject.emissive = material.emissiveColor.asArray();
  23253. serializationObject.alpha = material.alpha;
  23254. serializationObject.id = material.id;
  23255. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23256. serializationObject.backFaceCulling = material.backFaceCulling;
  23257. if (material.diffuseTexture) {
  23258. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  23259. }
  23260. if (material.diffuseFresnelParameters) {
  23261. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  23262. }
  23263. if (material.ambientTexture) {
  23264. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  23265. }
  23266. if (material.opacityTexture) {
  23267. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  23268. }
  23269. if (material.opacityFresnelParameters) {
  23270. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  23271. }
  23272. if (material.reflectionTexture) {
  23273. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  23274. }
  23275. if (material.reflectionFresnelParameters) {
  23276. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  23277. }
  23278. if (material.emissiveTexture) {
  23279. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  23280. }
  23281. if (material.emissiveFresnelParameters) {
  23282. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  23283. }
  23284. if (material.specularTexture) {
  23285. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  23286. }
  23287. if (material.bumpTexture) {
  23288. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  23289. }
  23290. return serializationObject;
  23291. };
  23292. var serializeTexture = function (texture) {
  23293. var serializationObject = {};
  23294. if (!texture.name) {
  23295. return null;
  23296. }
  23297. if (texture instanceof BABYLON.CubeTexture) {
  23298. serializationObject.name = texture.name;
  23299. serializationObject.hasAlpha = texture.hasAlpha;
  23300. serializationObject.level = texture.level;
  23301. serializationObject.coordinatesMode = texture.coordinatesMode;
  23302. return serializationObject;
  23303. }
  23304. if (texture instanceof BABYLON.MirrorTexture) {
  23305. var mirrorTexture = texture;
  23306. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  23307. serializationObject.renderList = [];
  23308. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  23309. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  23310. }
  23311. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  23312. }
  23313. else if (texture instanceof BABYLON.RenderTargetTexture) {
  23314. var renderTargetTexture = texture;
  23315. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  23316. serializationObject.renderList = [];
  23317. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  23318. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  23319. }
  23320. }
  23321. var regularTexture = texture;
  23322. serializationObject.name = texture.name;
  23323. serializationObject.hasAlpha = texture.hasAlpha;
  23324. serializationObject.level = texture.level;
  23325. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  23326. serializationObject.coordinatesMode = texture.coordinatesMode;
  23327. serializationObject.uOffset = regularTexture.uOffset;
  23328. serializationObject.vOffset = regularTexture.vOffset;
  23329. serializationObject.uScale = regularTexture.uScale;
  23330. serializationObject.vScale = regularTexture.vScale;
  23331. serializationObject.uAng = regularTexture.uAng;
  23332. serializationObject.vAng = regularTexture.vAng;
  23333. serializationObject.wAng = regularTexture.wAng;
  23334. serializationObject.wrapU = texture.wrapU;
  23335. serializationObject.wrapV = texture.wrapV;
  23336. // Animations
  23337. appendAnimations(texture, serializationObject);
  23338. return serializationObject;
  23339. };
  23340. var serializeSkeleton = function (skeleton) {
  23341. var serializationObject = {};
  23342. serializationObject.name = skeleton.name;
  23343. serializationObject.id = skeleton.id;
  23344. serializationObject.bones = [];
  23345. for (var index = 0; index < skeleton.bones.length; index++) {
  23346. var bone = skeleton.bones[index];
  23347. var serializedBone = {
  23348. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  23349. name: bone.name,
  23350. matrix: bone.getLocalMatrix().toArray()
  23351. };
  23352. serializationObject.bones.push(serializedBone);
  23353. if (bone.animations && bone.animations.length > 0) {
  23354. serializedBone.animation = serializeAnimation(bone.animations[0]);
  23355. }
  23356. }
  23357. return serializationObject;
  23358. };
  23359. var serializeParticleSystem = function (particleSystem) {
  23360. var serializationObject = {};
  23361. serializationObject.emitterId = particleSystem.emitter.id;
  23362. serializationObject.capacity = particleSystem.getCapacity();
  23363. if (particleSystem.particleTexture) {
  23364. serializationObject.textureName = particleSystem.particleTexture.name;
  23365. }
  23366. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  23367. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  23368. serializationObject.minSize = particleSystem.minSize;
  23369. serializationObject.maxSize = particleSystem.maxSize;
  23370. serializationObject.minLifeTime = particleSystem.minLifeTime;
  23371. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  23372. serializationObject.emitRate = particleSystem.emitRate;
  23373. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  23374. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  23375. serializationObject.gravity = particleSystem.gravity.asArray();
  23376. serializationObject.direction1 = particleSystem.direction1.asArray();
  23377. serializationObject.direction2 = particleSystem.direction2.asArray();
  23378. serializationObject.color1 = particleSystem.color1.asArray();
  23379. serializationObject.color2 = particleSystem.color2.asArray();
  23380. serializationObject.colorDead = particleSystem.colorDead.asArray();
  23381. serializationObject.updateSpeed = particleSystem.updateSpeed;
  23382. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  23383. serializationObject.textureMask = particleSystem.textureMask.asArray();
  23384. serializationObject.blendMode = particleSystem.blendMode;
  23385. return serializationObject;
  23386. };
  23387. var serializeLensFlareSystem = function (lensFlareSystem) {
  23388. var serializationObject = {};
  23389. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  23390. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  23391. serializationObject.flares = [];
  23392. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  23393. var flare = lensFlareSystem.lensFlares[index];
  23394. serializationObject.flares.push({
  23395. size: flare.size,
  23396. position: flare.position,
  23397. color: flare.color.asArray(),
  23398. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  23399. });
  23400. }
  23401. return serializationObject;
  23402. };
  23403. var serializeShadowGenerator = function (light) {
  23404. var serializationObject = {};
  23405. var shadowGenerator = light.getShadowGenerator();
  23406. serializationObject.lightId = light.id;
  23407. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  23408. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  23409. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  23410. serializationObject.renderList = [];
  23411. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  23412. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  23413. serializationObject.renderList.push(mesh.id);
  23414. }
  23415. return serializationObject;
  23416. };
  23417. var serializedGeometries = [];
  23418. var serializeGeometry = function (geometry, serializationGeometries) {
  23419. if (serializedGeometries[geometry.id]) {
  23420. return;
  23421. }
  23422. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  23423. serializationGeometries.boxes.push(serializeBox(geometry));
  23424. }
  23425. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  23426. serializationGeometries.spheres.push(serializeSphere(geometry));
  23427. }
  23428. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  23429. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  23430. }
  23431. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  23432. serializationGeometries.toruses.push(serializeTorus(geometry));
  23433. }
  23434. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  23435. serializationGeometries.grounds.push(serializeGround(geometry));
  23436. }
  23437. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  23438. serializationGeometries.planes.push(serializePlane(geometry));
  23439. }
  23440. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  23441. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  23442. }
  23443. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  23444. throw new Error("Unknow primitive type");
  23445. }
  23446. else {
  23447. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  23448. }
  23449. serializedGeometries[geometry.id] = true;
  23450. };
  23451. var serializeGeometryBase = function (geometry) {
  23452. var serializationObject = {};
  23453. serializationObject.id = geometry.id;
  23454. if (BABYLON.Tags.HasTags(geometry)) {
  23455. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  23456. }
  23457. return serializationObject;
  23458. };
  23459. var serializeVertexData = function (vertexData) {
  23460. var serializationObject = serializeGeometryBase(vertexData);
  23461. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23462. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23463. }
  23464. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23465. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23466. }
  23467. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23468. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23469. }
  23470. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23471. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  23472. }
  23473. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23474. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  23475. }
  23476. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23477. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23478. serializationObject.matricesIndices._isExpanded = true;
  23479. }
  23480. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23481. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23482. }
  23483. serializationObject.indices = vertexData.getIndices();
  23484. return serializationObject;
  23485. };
  23486. var serializePrimitive = function (primitive) {
  23487. var serializationObject = serializeGeometryBase(primitive);
  23488. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  23489. return serializationObject;
  23490. };
  23491. var serializeBox = function (box) {
  23492. var serializationObject = serializePrimitive(box);
  23493. serializationObject.size = box.size;
  23494. return serializationObject;
  23495. };
  23496. var serializeSphere = function (sphere) {
  23497. var serializationObject = serializePrimitive(sphere);
  23498. serializationObject.segments = sphere.segments;
  23499. serializationObject.diameter = sphere.diameter;
  23500. return serializationObject;
  23501. };
  23502. var serializeCylinder = function (cylinder) {
  23503. var serializationObject = serializePrimitive(cylinder);
  23504. serializationObject.height = cylinder.height;
  23505. serializationObject.diameterTop = cylinder.diameterTop;
  23506. serializationObject.diameterBottom = cylinder.diameterBottom;
  23507. serializationObject.tessellation = cylinder.tessellation;
  23508. return serializationObject;
  23509. };
  23510. var serializeTorus = function (torus) {
  23511. var serializationObject = serializePrimitive(torus);
  23512. serializationObject.diameter = torus.diameter;
  23513. serializationObject.thickness = torus.thickness;
  23514. serializationObject.tessellation = torus.tessellation;
  23515. return serializationObject;
  23516. };
  23517. var serializeGround = function (ground) {
  23518. var serializationObject = serializePrimitive(ground);
  23519. serializationObject.width = ground.width;
  23520. serializationObject.height = ground.height;
  23521. serializationObject.subdivisions = ground.subdivisions;
  23522. return serializationObject;
  23523. };
  23524. var serializePlane = function (plane) {
  23525. var serializationObject = serializePrimitive(plane);
  23526. serializationObject.size = plane.size;
  23527. return serializationObject;
  23528. };
  23529. var serializeTorusKnot = function (torusKnot) {
  23530. var serializationObject = serializePrimitive(torusKnot);
  23531. serializationObject.radius = torusKnot.radius;
  23532. serializationObject.tube = torusKnot.tube;
  23533. serializationObject.radialSegments = torusKnot.radialSegments;
  23534. serializationObject.tubularSegments = torusKnot.tubularSegments;
  23535. serializationObject.p = torusKnot.p;
  23536. serializationObject.q = torusKnot.q;
  23537. return serializationObject;
  23538. };
  23539. var serializeMesh = function (mesh, serializationScene) {
  23540. var serializationObject = {};
  23541. serializationObject.name = mesh.name;
  23542. serializationObject.id = mesh.id;
  23543. if (BABYLON.Tags.HasTags(mesh)) {
  23544. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  23545. }
  23546. serializationObject.position = mesh.position.asArray();
  23547. if (mesh.rotationQuaternion) {
  23548. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  23549. }
  23550. else if (mesh.rotation) {
  23551. serializationObject.rotation = mesh.rotation.asArray();
  23552. }
  23553. serializationObject.scaling = mesh.scaling.asArray();
  23554. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  23555. serializationObject.isEnabled = mesh.isEnabled();
  23556. serializationObject.isVisible = mesh.isVisible;
  23557. serializationObject.infiniteDistance = mesh.infiniteDistance;
  23558. serializationObject.pickable = mesh.isPickable;
  23559. serializationObject.receiveShadows = mesh.receiveShadows;
  23560. serializationObject.billboardMode = mesh.billboardMode;
  23561. serializationObject.visibility = mesh.visibility;
  23562. serializationObject.checkCollisions = mesh.checkCollisions;
  23563. // Parent
  23564. if (mesh.parent) {
  23565. serializationObject.parentId = mesh.parent.id;
  23566. }
  23567. // Geometry
  23568. var geometry = mesh._geometry;
  23569. if (geometry) {
  23570. var geometryId = geometry.id;
  23571. serializationObject.geometryId = geometryId;
  23572. if (!mesh.getScene().getGeometryByID(geometryId)) {
  23573. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize too be able to reload the mesh with its geometry
  23574. serializeGeometry(geometry, serializationScene.geometries);
  23575. }
  23576. // SubMeshes
  23577. serializationObject.subMeshes = [];
  23578. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23579. var subMesh = mesh.subMeshes[subIndex];
  23580. serializationObject.subMeshes.push({
  23581. materialIndex: subMesh.materialIndex,
  23582. verticesStart: subMesh.verticesStart,
  23583. verticesCount: subMesh.verticesCount,
  23584. indexStart: subMesh.indexStart,
  23585. indexCount: subMesh.indexCount
  23586. });
  23587. }
  23588. }
  23589. // Material
  23590. if (mesh.material) {
  23591. serializationObject.materialId = mesh.material.id;
  23592. }
  23593. else {
  23594. mesh.material = null;
  23595. }
  23596. // Skeleton
  23597. if (mesh.skeleton) {
  23598. serializationObject.skeletonId = mesh.skeleton.id;
  23599. }
  23600. // Physics
  23601. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  23602. serializationObject.physicsMass = mesh.getPhysicsMass();
  23603. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  23604. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  23605. switch (mesh.getPhysicsImpostor()) {
  23606. case BABYLON.PhysicsEngine.BoxImpostor:
  23607. serializationObject.physicsImpostor = 1;
  23608. break;
  23609. case BABYLON.PhysicsEngine.SphereImpostor:
  23610. serializationObject.physicsImpostor = 2;
  23611. break;
  23612. }
  23613. }
  23614. // Instances
  23615. serializationObject.instances = [];
  23616. for (var index = 0; index < mesh.instances.length; index++) {
  23617. var instance = mesh.instances[index];
  23618. var serializationInstance = {
  23619. name: instance.name,
  23620. position: instance.position,
  23621. rotation: instance.rotation,
  23622. rotationQuaternion: instance.rotationQuaternion,
  23623. scaling: instance.scaling
  23624. };
  23625. serializationObject.instances.push(serializationInstance);
  23626. // Animations
  23627. appendAnimations(instance, serializationInstance);
  23628. }
  23629. // Animations
  23630. appendAnimations(mesh, serializationObject);
  23631. // Layer mask
  23632. serializationObject.layerMask = mesh.layerMask;
  23633. return serializationObject;
  23634. };
  23635. var SceneSerializer = (function () {
  23636. function SceneSerializer() {
  23637. }
  23638. SceneSerializer.Serialize = function (scene) {
  23639. var serializationObject = {};
  23640. // Scene
  23641. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  23642. serializationObject.autoClear = scene.autoClear;
  23643. serializationObject.clearColor = scene.clearColor.asArray();
  23644. serializationObject.ambientColor = scene.ambientColor.asArray();
  23645. serializationObject.gravity = scene.gravity.asArray();
  23646. // Fog
  23647. if (scene.fogMode && scene.fogMode !== 0) {
  23648. serializationObject.fogMode = scene.fogMode;
  23649. serializationObject.fogColor = scene.fogColor.asArray();
  23650. serializationObject.fogStart = scene.fogStart;
  23651. serializationObject.fogEnd = scene.fogEnd;
  23652. serializationObject.fogDensity = scene.fogDensity;
  23653. }
  23654. // Lights
  23655. serializationObject.lights = [];
  23656. for (var index = 0; index < scene.lights.length; index++) {
  23657. var light = scene.lights[index];
  23658. serializationObject.lights.push(serializeLight(light));
  23659. }
  23660. // Cameras
  23661. serializationObject.cameras = [];
  23662. for (index = 0; index < scene.cameras.length; index++) {
  23663. var camera = scene.cameras[index];
  23664. serializationObject.cameras.push(serializeCamera(camera));
  23665. }
  23666. if (scene.activeCamera) {
  23667. serializationObject.activeCameraID = scene.activeCamera.id;
  23668. }
  23669. // Materials
  23670. serializationObject.materials = [];
  23671. serializationObject.multiMaterials = [];
  23672. for (index = 0; index < scene.materials.length; index++) {
  23673. var material = scene.materials[index];
  23674. if (material instanceof BABYLON.StandardMaterial) {
  23675. serializationObject.materials.push(serializeMaterial(material));
  23676. }
  23677. else if (material instanceof BABYLON.MultiMaterial) {
  23678. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  23679. }
  23680. }
  23681. // Skeletons
  23682. serializationObject.skeletons = [];
  23683. for (index = 0; index < scene.skeletons.length; index++) {
  23684. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  23685. }
  23686. // Geometries
  23687. serializationObject.geometries = {};
  23688. serializationObject.geometries.boxes = [];
  23689. serializationObject.geometries.spheres = [];
  23690. serializationObject.geometries.cylinders = [];
  23691. serializationObject.geometries.toruses = [];
  23692. serializationObject.geometries.grounds = [];
  23693. serializationObject.geometries.planes = [];
  23694. serializationObject.geometries.torusKnots = [];
  23695. serializationObject.geometries.vertexData = [];
  23696. serializedGeometries = [];
  23697. var geometries = scene.getGeometries();
  23698. for (index = 0; index < geometries.length; index++) {
  23699. var geometry = geometries[index];
  23700. if (geometry.isReady()) {
  23701. serializeGeometry(geometry, serializationObject.geometries);
  23702. }
  23703. }
  23704. // Meshes
  23705. serializationObject.meshes = [];
  23706. for (index = 0; index < scene.meshes.length; index++) {
  23707. var abstractMesh = scene.meshes[index];
  23708. if (abstractMesh instanceof BABYLON.Mesh) {
  23709. var mesh = abstractMesh;
  23710. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  23711. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  23712. }
  23713. }
  23714. }
  23715. // Particles Systems
  23716. serializationObject.particleSystems = [];
  23717. for (index = 0; index < scene.particleSystems.length; index++) {
  23718. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  23719. }
  23720. // Lens flares
  23721. serializationObject.lensFlareSystems = [];
  23722. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  23723. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  23724. }
  23725. // Shadows
  23726. serializationObject.shadowGenerators = [];
  23727. for (index = 0; index < scene.lights.length; index++) {
  23728. light = scene.lights[index];
  23729. if (light.getShadowGenerator()) {
  23730. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  23731. }
  23732. }
  23733. return serializationObject;
  23734. };
  23735. return SceneSerializer;
  23736. })();
  23737. BABYLON.SceneSerializer = SceneSerializer;
  23738. })(BABYLON || (BABYLON = {}));
  23739. //# sourceMappingURL=babylon.sceneSerializer.js.map
  23740. var BABYLON;
  23741. (function (BABYLON) {
  23742. // Unique ID when we import meshes from Babylon to CSG
  23743. var currentCSGMeshId = 0;
  23744. // # class Vertex
  23745. // Represents a vertex of a polygon. Use your own vertex class instead of this
  23746. // one to provide additional features like texture coordinates and vertex
  23747. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  23748. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  23749. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  23750. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  23751. // is not used anywhere else.
  23752. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  23753. var Vertex = (function () {
  23754. function Vertex(pos, normal, uv) {
  23755. this.pos = pos;
  23756. this.normal = normal;
  23757. this.uv = uv;
  23758. }
  23759. Vertex.prototype.clone = function () {
  23760. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  23761. };
  23762. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  23763. // orientation of a polygon is flipped.
  23764. Vertex.prototype.flip = function () {
  23765. this.normal = this.normal.scale(-1);
  23766. };
  23767. // Create a new vertex between this vertex and `other` by linearly
  23768. // interpolating all properties using a parameter of `t`. Subclasses should
  23769. // override this to interpolate additional properties.
  23770. Vertex.prototype.interpolate = function (other, t) {
  23771. 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));
  23772. };
  23773. return Vertex;
  23774. })();
  23775. // # class Plane
  23776. // Represents a plane in 3D space.
  23777. var Plane = (function () {
  23778. function Plane(normal, w) {
  23779. this.normal = normal;
  23780. this.w = w;
  23781. }
  23782. Plane.FromPoints = function (a, b, c) {
  23783. var v0 = c.subtract(a);
  23784. var v1 = b.subtract(a);
  23785. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  23786. return null;
  23787. }
  23788. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  23789. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  23790. };
  23791. Plane.prototype.clone = function () {
  23792. return new Plane(this.normal.clone(), this.w);
  23793. };
  23794. Plane.prototype.flip = function () {
  23795. this.normal.scaleInPlace(-1);
  23796. this.w = -this.w;
  23797. };
  23798. // Split `polygon` by this plane if needed, then put the polygon or polygon
  23799. // fragments in the appropriate lists. Coplanar polygons go into either
  23800. // `coplanarFront` or `coplanarBack` depending on their orientation with
  23801. // respect to this plane. Polygons in front or in back of this plane go into
  23802. // either `front` or `back`.
  23803. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  23804. var COPLANAR = 0;
  23805. var FRONT = 1;
  23806. var BACK = 2;
  23807. var SPANNING = 3;
  23808. // Classify each point as well as the entire polygon into one of the above
  23809. // four classes.
  23810. var polygonType = 0;
  23811. var types = [];
  23812. for (var i = 0; i < polygon.vertices.length; i++) {
  23813. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  23814. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  23815. polygonType |= type;
  23816. types.push(type);
  23817. }
  23818. // Put the polygon in the correct list, splitting it when necessary.
  23819. switch (polygonType) {
  23820. case COPLANAR:
  23821. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  23822. break;
  23823. case FRONT:
  23824. front.push(polygon);
  23825. break;
  23826. case BACK:
  23827. back.push(polygon);
  23828. break;
  23829. case SPANNING:
  23830. var f = [], b = [];
  23831. for (i = 0; i < polygon.vertices.length; i++) {
  23832. var j = (i + 1) % polygon.vertices.length;
  23833. var ti = types[i], tj = types[j];
  23834. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  23835. if (ti != BACK)
  23836. f.push(vi);
  23837. if (ti != FRONT)
  23838. b.push(ti != BACK ? vi.clone() : vi);
  23839. if ((ti | tj) == SPANNING) {
  23840. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  23841. var v = vi.interpolate(vj, t);
  23842. f.push(v);
  23843. b.push(v.clone());
  23844. }
  23845. }
  23846. if (f.length >= 3) {
  23847. var poly = new Polygon(f, polygon.shared);
  23848. if (poly.plane)
  23849. front.push(poly);
  23850. }
  23851. if (b.length >= 3) {
  23852. poly = new Polygon(b, polygon.shared);
  23853. if (poly.plane)
  23854. back.push(poly);
  23855. }
  23856. break;
  23857. }
  23858. };
  23859. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  23860. // point is on the plane.
  23861. Plane.EPSILON = 1e-5;
  23862. return Plane;
  23863. })();
  23864. // # class Polygon
  23865. // Represents a convex polygon. The vertices used to initialize a polygon must
  23866. // be coplanar and form a convex loop.
  23867. //
  23868. // Each convex polygon has a `shared` property, which is shared between all
  23869. // polygons that are clones of each other or were split from the same polygon.
  23870. // This can be used to define per-polygon properties (such as surface color).
  23871. var Polygon = (function () {
  23872. function Polygon(vertices, shared) {
  23873. this.vertices = vertices;
  23874. this.shared = shared;
  23875. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  23876. }
  23877. Polygon.prototype.clone = function () {
  23878. var vertices = this.vertices.map(function (v) { return v.clone(); });
  23879. return new Polygon(vertices, this.shared);
  23880. };
  23881. Polygon.prototype.flip = function () {
  23882. this.vertices.reverse().map(function (v) { v.flip(); });
  23883. this.plane.flip();
  23884. };
  23885. return Polygon;
  23886. })();
  23887. // # class Node
  23888. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  23889. // by picking a polygon to split along. That polygon (and all other coplanar
  23890. // polygons) are added directly to that node and the other polygons are added to
  23891. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  23892. // no distinction between internal and leaf nodes.
  23893. var Node = (function () {
  23894. function Node(polygons) {
  23895. this.plane = null;
  23896. this.front = null;
  23897. this.back = null;
  23898. this.polygons = [];
  23899. if (polygons) {
  23900. this.build(polygons);
  23901. }
  23902. }
  23903. Node.prototype.clone = function () {
  23904. var node = new Node();
  23905. node.plane = this.plane && this.plane.clone();
  23906. node.front = this.front && this.front.clone();
  23907. node.back = this.back && this.back.clone();
  23908. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  23909. return node;
  23910. };
  23911. // Convert solid space to empty space and empty space to solid space.
  23912. Node.prototype.invert = function () {
  23913. for (var i = 0; i < this.polygons.length; i++) {
  23914. this.polygons[i].flip();
  23915. }
  23916. if (this.plane) {
  23917. this.plane.flip();
  23918. }
  23919. if (this.front) {
  23920. this.front.invert();
  23921. }
  23922. if (this.back) {
  23923. this.back.invert();
  23924. }
  23925. var temp = this.front;
  23926. this.front = this.back;
  23927. this.back = temp;
  23928. };
  23929. // Recursively remove all polygons in `polygons` that are inside this BSP
  23930. // tree.
  23931. Node.prototype.clipPolygons = function (polygons) {
  23932. if (!this.plane)
  23933. return polygons.slice();
  23934. var front = [], back = [];
  23935. for (var i = 0; i < polygons.length; i++) {
  23936. this.plane.splitPolygon(polygons[i], front, back, front, back);
  23937. }
  23938. if (this.front) {
  23939. front = this.front.clipPolygons(front);
  23940. }
  23941. if (this.back) {
  23942. back = this.back.clipPolygons(back);
  23943. }
  23944. else {
  23945. back = [];
  23946. }
  23947. return front.concat(back);
  23948. };
  23949. // Remove all polygons in this BSP tree that are inside the other BSP tree
  23950. // `bsp`.
  23951. Node.prototype.clipTo = function (bsp) {
  23952. this.polygons = bsp.clipPolygons(this.polygons);
  23953. if (this.front)
  23954. this.front.clipTo(bsp);
  23955. if (this.back)
  23956. this.back.clipTo(bsp);
  23957. };
  23958. // Return a list of all polygons in this BSP tree.
  23959. Node.prototype.allPolygons = function () {
  23960. var polygons = this.polygons.slice();
  23961. if (this.front)
  23962. polygons = polygons.concat(this.front.allPolygons());
  23963. if (this.back)
  23964. polygons = polygons.concat(this.back.allPolygons());
  23965. return polygons;
  23966. };
  23967. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  23968. // new polygons are filtered down to the bottom of the tree and become new
  23969. // nodes there. Each set of polygons is partitioned using the first polygon
  23970. // (no heuristic is used to pick a good split).
  23971. Node.prototype.build = function (polygons) {
  23972. if (!polygons.length)
  23973. return;
  23974. if (!this.plane)
  23975. this.plane = polygons[0].plane.clone();
  23976. var front = [], back = [];
  23977. for (var i = 0; i < polygons.length; i++) {
  23978. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  23979. }
  23980. if (front.length) {
  23981. if (!this.front)
  23982. this.front = new Node();
  23983. this.front.build(front);
  23984. }
  23985. if (back.length) {
  23986. if (!this.back)
  23987. this.back = new Node();
  23988. this.back.build(back);
  23989. }
  23990. };
  23991. return Node;
  23992. })();
  23993. var CSG = (function () {
  23994. function CSG() {
  23995. this.polygons = new Array();
  23996. }
  23997. // Convert BABYLON.Mesh to BABYLON.CSG
  23998. CSG.FromMesh = function (mesh) {
  23999. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  24000. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  24001. if (mesh instanceof BABYLON.Mesh) {
  24002. mesh.computeWorldMatrix(true);
  24003. matrix = mesh.getWorldMatrix();
  24004. meshPosition = mesh.position.clone();
  24005. meshRotation = mesh.rotation.clone();
  24006. if (mesh.rotationQuaternion) {
  24007. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  24008. }
  24009. meshScaling = mesh.scaling.clone();
  24010. }
  24011. else {
  24012. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  24013. }
  24014. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24015. var subMeshes = mesh.subMeshes;
  24016. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  24017. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  24018. vertices = [];
  24019. for (var j = 0; j < 3; j++) {
  24020. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  24021. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  24022. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  24023. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  24024. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  24025. vertex = new Vertex(position, normal, uv);
  24026. vertices.push(vertex);
  24027. }
  24028. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  24029. // To handle the case of degenerated triangle
  24030. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  24031. if (polygon.plane)
  24032. polygons.push(polygon);
  24033. }
  24034. }
  24035. var csg = CSG.FromPolygons(polygons);
  24036. csg.matrix = matrix;
  24037. csg.position = meshPosition;
  24038. csg.rotation = meshRotation;
  24039. csg.scaling = meshScaling;
  24040. csg.rotationQuaternion = meshRotationQuaternion;
  24041. currentCSGMeshId++;
  24042. return csg;
  24043. };
  24044. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  24045. CSG.FromPolygons = function (polygons) {
  24046. var csg = new CSG();
  24047. csg.polygons = polygons;
  24048. return csg;
  24049. };
  24050. CSG.prototype.clone = function () {
  24051. var csg = new CSG();
  24052. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  24053. csg.copyTransformAttributes(this);
  24054. return csg;
  24055. };
  24056. CSG.prototype.toPolygons = function () {
  24057. return this.polygons;
  24058. };
  24059. CSG.prototype.union = function (csg) {
  24060. var a = new Node(this.clone().polygons);
  24061. var b = new Node(csg.clone().polygons);
  24062. a.clipTo(b);
  24063. b.clipTo(a);
  24064. b.invert();
  24065. b.clipTo(a);
  24066. b.invert();
  24067. a.build(b.allPolygons());
  24068. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24069. };
  24070. CSG.prototype.unionInPlace = function (csg) {
  24071. var a = new Node(this.polygons);
  24072. var b = new Node(csg.polygons);
  24073. a.clipTo(b);
  24074. b.clipTo(a);
  24075. b.invert();
  24076. b.clipTo(a);
  24077. b.invert();
  24078. a.build(b.allPolygons());
  24079. this.polygons = a.allPolygons();
  24080. };
  24081. CSG.prototype.subtract = function (csg) {
  24082. var a = new Node(this.clone().polygons);
  24083. var b = new Node(csg.clone().polygons);
  24084. a.invert();
  24085. a.clipTo(b);
  24086. b.clipTo(a);
  24087. b.invert();
  24088. b.clipTo(a);
  24089. b.invert();
  24090. a.build(b.allPolygons());
  24091. a.invert();
  24092. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24093. };
  24094. CSG.prototype.subtractInPlace = function (csg) {
  24095. var a = new Node(this.polygons);
  24096. var b = new Node(csg.polygons);
  24097. a.invert();
  24098. a.clipTo(b);
  24099. b.clipTo(a);
  24100. b.invert();
  24101. b.clipTo(a);
  24102. b.invert();
  24103. a.build(b.allPolygons());
  24104. a.invert();
  24105. this.polygons = a.allPolygons();
  24106. };
  24107. CSG.prototype.intersect = function (csg) {
  24108. var a = new Node(this.clone().polygons);
  24109. var b = new Node(csg.clone().polygons);
  24110. a.invert();
  24111. b.clipTo(a);
  24112. b.invert();
  24113. a.clipTo(b);
  24114. b.clipTo(a);
  24115. a.build(b.allPolygons());
  24116. a.invert();
  24117. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24118. };
  24119. CSG.prototype.intersectInPlace = function (csg) {
  24120. var a = new Node(this.polygons);
  24121. var b = new Node(csg.polygons);
  24122. a.invert();
  24123. b.clipTo(a);
  24124. b.invert();
  24125. a.clipTo(b);
  24126. b.clipTo(a);
  24127. a.build(b.allPolygons());
  24128. a.invert();
  24129. this.polygons = a.allPolygons();
  24130. };
  24131. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24132. // not modified.
  24133. CSG.prototype.inverse = function () {
  24134. var csg = this.clone();
  24135. csg.inverseInPlace();
  24136. return csg;
  24137. };
  24138. CSG.prototype.inverseInPlace = function () {
  24139. this.polygons.map(function (p) { p.flip(); });
  24140. };
  24141. // This is used to keep meshes transformations so they can be restored
  24142. // when we build back a Babylon Mesh
  24143. // NB : All CSG operations are performed in world coordinates
  24144. CSG.prototype.copyTransformAttributes = function (csg) {
  24145. this.matrix = csg.matrix;
  24146. this.position = csg.position;
  24147. this.rotation = csg.rotation;
  24148. this.scaling = csg.scaling;
  24149. this.rotationQuaternion = csg.rotationQuaternion;
  24150. return this;
  24151. };
  24152. // Build Raw mesh from CSG
  24153. // Coordinates here are in world space
  24154. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  24155. var matrix = this.matrix.clone();
  24156. matrix.invert();
  24157. 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;
  24158. if (keepSubMeshes) {
  24159. // Sort Polygons, since subMeshes are indices range
  24160. polygons.sort(function (a, b) {
  24161. if (a.shared.meshId === b.shared.meshId) {
  24162. return a.shared.subMeshId - b.shared.subMeshId;
  24163. }
  24164. else {
  24165. return a.shared.meshId - b.shared.meshId;
  24166. }
  24167. });
  24168. }
  24169. for (var i = 0, il = polygons.length; i < il; i++) {
  24170. polygon = polygons[i];
  24171. // Building SubMeshes
  24172. if (!subMesh_dict[polygon.shared.meshId]) {
  24173. subMesh_dict[polygon.shared.meshId] = {};
  24174. }
  24175. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  24176. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  24177. indexStart: +Infinity,
  24178. indexEnd: -Infinity,
  24179. materialIndex: polygon.shared.materialIndex
  24180. };
  24181. }
  24182. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  24183. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  24184. polygonIndices[0] = 0;
  24185. polygonIndices[1] = j - 1;
  24186. polygonIndices[2] = j;
  24187. for (var k = 0; k < 3; k++) {
  24188. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  24189. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  24190. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  24191. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  24192. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  24193. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  24194. // Check if 2 points can be merged
  24195. if (!(typeof vertex_idx !== 'undefined' &&
  24196. normals[vertex_idx * 3] === localNormal.x &&
  24197. normals[vertex_idx * 3 + 1] === localNormal.y &&
  24198. normals[vertex_idx * 3 + 2] === localNormal.z &&
  24199. uvs[vertex_idx * 2] === uv.x &&
  24200. uvs[vertex_idx * 2 + 1] === uv.y)) {
  24201. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  24202. uvs.push(uv.x, uv.y);
  24203. normals.push(normal.x, normal.y, normal.z);
  24204. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  24205. }
  24206. indices.push(vertex_idx);
  24207. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  24208. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  24209. currentIndex++;
  24210. }
  24211. }
  24212. }
  24213. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  24214. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24215. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  24216. mesh.setIndices(indices);
  24217. if (keepSubMeshes) {
  24218. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  24219. var materialIndexOffset = 0, materialMaxIndex;
  24220. mesh.subMeshes.length = 0;
  24221. for (var m in subMesh_dict) {
  24222. materialMaxIndex = -1;
  24223. for (var sm in subMesh_dict[m]) {
  24224. subMesh_obj = subMesh_dict[m][sm];
  24225. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  24226. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  24227. }
  24228. materialIndexOffset += ++materialMaxIndex;
  24229. }
  24230. }
  24231. return mesh;
  24232. };
  24233. // Build Mesh from CSG taking material and transforms into account
  24234. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  24235. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  24236. mesh.material = material;
  24237. mesh.position.copyFrom(this.position);
  24238. mesh.rotation.copyFrom(this.rotation);
  24239. if (this.rotationQuaternion) {
  24240. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  24241. }
  24242. mesh.scaling.copyFrom(this.scaling);
  24243. mesh.computeWorldMatrix(true);
  24244. return mesh;
  24245. };
  24246. return CSG;
  24247. })();
  24248. BABYLON.CSG = CSG;
  24249. })(BABYLON || (BABYLON = {}));
  24250. //# sourceMappingURL=babylon.csg.js.map
  24251. var BABYLON;
  24252. (function (BABYLON) {
  24253. var VRDistortionCorrectionPostProcess = (function (_super) {
  24254. __extends(VRDistortionCorrectionPostProcess, _super);
  24255. //ANY
  24256. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  24257. var _this = this;
  24258. _super.call(this, name, "vrDistortionCorrection", [
  24259. 'LensCenter',
  24260. 'Scale',
  24261. 'ScaleIn',
  24262. 'HmdWarpParam'
  24263. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  24264. this._isRightEye = isRightEye;
  24265. this._distortionFactors = vrMetrics.distortionK;
  24266. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  24267. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  24268. this.onSizeChanged = function () {
  24269. _this.aspectRatio = _this.width * .5 / _this.height;
  24270. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  24271. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  24272. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  24273. };
  24274. this.onApply = function (effect) {
  24275. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  24276. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  24277. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  24278. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  24279. };
  24280. }
  24281. return VRDistortionCorrectionPostProcess;
  24282. })(BABYLON.PostProcess);
  24283. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  24284. })(BABYLON || (BABYLON = {}));
  24285. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  24286. // Mainly based on these 2 articles :
  24287. // 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
  24288. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  24289. var BABYLON;
  24290. (function (BABYLON) {
  24291. (function (JoystickAxis) {
  24292. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  24293. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  24294. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  24295. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  24296. var JoystickAxis = BABYLON.JoystickAxis;
  24297. var VirtualJoystick = (function () {
  24298. function VirtualJoystick(leftJoystick) {
  24299. var _this = this;
  24300. if (leftJoystick) {
  24301. this._leftJoystick = true;
  24302. }
  24303. else {
  24304. this._leftJoystick = false;
  24305. }
  24306. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  24307. VirtualJoystick._globalJoystickIndex++;
  24308. // By default left & right arrow keys are moving the X
  24309. // and up & down keys are moving the Y
  24310. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24311. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24312. this.reverseLeftRight = false;
  24313. this.reverseUpDown = false;
  24314. // collections of pointers
  24315. this._touches = new BABYLON.SmartCollection();
  24316. this.deltaPosition = BABYLON.Vector3.Zero();
  24317. this._joystickSensibility = 25;
  24318. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24319. this._rotationSpeed = 25;
  24320. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  24321. this._rotateOnAxisRelativeToMesh = false;
  24322. // injecting a canvas element on top of the canvas 3D game
  24323. if (!VirtualJoystick.vjCanvas) {
  24324. window.addEventListener("resize", function () {
  24325. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24326. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24327. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  24328. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  24329. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  24330. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  24331. }, false);
  24332. VirtualJoystick.vjCanvas = document.createElement("canvas");
  24333. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24334. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24335. VirtualJoystick.vjCanvas.width = window.innerWidth;
  24336. VirtualJoystick.vjCanvas.height = window.innerHeight;
  24337. VirtualJoystick.vjCanvas.style.width = "100%";
  24338. VirtualJoystick.vjCanvas.style.height = "100%";
  24339. VirtualJoystick.vjCanvas.style.position = "absolute";
  24340. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  24341. VirtualJoystick.vjCanvas.style.top = "0px";
  24342. VirtualJoystick.vjCanvas.style.left = "0px";
  24343. VirtualJoystick.vjCanvas.style.zIndex = "5";
  24344. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  24345. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  24346. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  24347. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24348. document.body.appendChild(VirtualJoystick.vjCanvas);
  24349. }
  24350. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  24351. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  24352. this.pressed = false;
  24353. // default joystick color
  24354. this._joystickColor = "cyan";
  24355. this._joystickPointerID = -1;
  24356. // current joystick position
  24357. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  24358. // origin joystick position
  24359. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  24360. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  24361. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  24362. _this._onPointerDown(evt);
  24363. }, false);
  24364. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  24365. _this._onPointerMove(evt);
  24366. }, false);
  24367. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  24368. _this._onPointerUp(evt);
  24369. }, false);
  24370. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  24371. _this._onPointerUp(evt);
  24372. }, false);
  24373. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  24374. evt.preventDefault(); // Disables system menu
  24375. }, false);
  24376. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24377. }
  24378. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  24379. this._joystickSensibility = newJoystickSensibility;
  24380. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24381. };
  24382. VirtualJoystick.prototype._onPointerDown = function (e) {
  24383. var positionOnScreenCondition;
  24384. e.preventDefault();
  24385. if (this._leftJoystick === true) {
  24386. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  24387. }
  24388. else {
  24389. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  24390. }
  24391. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  24392. // First contact will be dedicated to the virtual joystick
  24393. this._joystickPointerID = e.pointerId;
  24394. this._joystickPointerStartPos.x = e.clientX;
  24395. this._joystickPointerStartPos.y = e.clientY;
  24396. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  24397. this._deltaJoystickVector.x = 0;
  24398. this._deltaJoystickVector.y = 0;
  24399. this.pressed = true;
  24400. this._touches.add(e.pointerId.toString(), e);
  24401. }
  24402. else {
  24403. // You can only trigger the action buttons with a joystick declared
  24404. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  24405. this._action();
  24406. this._touches.add(e.pointerId.toString(), e);
  24407. }
  24408. }
  24409. };
  24410. VirtualJoystick.prototype._onPointerMove = function (e) {
  24411. // If the current pointer is the one associated to the joystick (first touch contact)
  24412. if (this._joystickPointerID == e.pointerId) {
  24413. this._joystickPointerPos.x = e.clientX;
  24414. this._joystickPointerPos.y = e.clientY;
  24415. this._deltaJoystickVector = this._joystickPointerPos.clone();
  24416. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  24417. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  24418. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  24419. switch (this._axisTargetedByLeftAndRight) {
  24420. case JoystickAxis.X:
  24421. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  24422. break;
  24423. case JoystickAxis.Y:
  24424. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  24425. break;
  24426. case JoystickAxis.Z:
  24427. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  24428. break;
  24429. }
  24430. var directionUpDown = this.reverseUpDown ? 1 : -1;
  24431. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  24432. switch (this._axisTargetedByUpAndDown) {
  24433. case JoystickAxis.X:
  24434. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  24435. break;
  24436. case JoystickAxis.Y:
  24437. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  24438. break;
  24439. case JoystickAxis.Z:
  24440. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  24441. break;
  24442. }
  24443. }
  24444. else {
  24445. if (this._touches.item(e.pointerId.toString())) {
  24446. this._touches.item(e.pointerId.toString()).x = e.clientX;
  24447. this._touches.item(e.pointerId.toString()).y = e.clientY;
  24448. }
  24449. }
  24450. };
  24451. VirtualJoystick.prototype._onPointerUp = function (e) {
  24452. this._clearCanvas();
  24453. if (this._joystickPointerID == e.pointerId) {
  24454. this._joystickPointerID = -1;
  24455. this.pressed = false;
  24456. }
  24457. this._deltaJoystickVector.x = 0;
  24458. this._deltaJoystickVector.y = 0;
  24459. this._touches.remove(e.pointerId.toString());
  24460. };
  24461. /**
  24462. * Change the color of the virtual joystick
  24463. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  24464. */
  24465. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  24466. this._joystickColor = newColor;
  24467. };
  24468. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  24469. this._action = action;
  24470. };
  24471. // Define which axis you'd like to control for left & right
  24472. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  24473. switch (axis) {
  24474. case JoystickAxis.X:
  24475. case JoystickAxis.Y:
  24476. case JoystickAxis.Z:
  24477. this._axisTargetedByLeftAndRight = axis;
  24478. break;
  24479. default:
  24480. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24481. break;
  24482. }
  24483. };
  24484. // Define which axis you'd like to control for up & down
  24485. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  24486. switch (axis) {
  24487. case JoystickAxis.X:
  24488. case JoystickAxis.Y:
  24489. case JoystickAxis.Z:
  24490. this._axisTargetedByUpAndDown = axis;
  24491. break;
  24492. default:
  24493. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24494. break;
  24495. }
  24496. };
  24497. VirtualJoystick.prototype._clearCanvas = function () {
  24498. if (this._leftJoystick) {
  24499. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  24500. }
  24501. else {
  24502. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  24503. }
  24504. };
  24505. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  24506. var _this = this;
  24507. if (this.pressed) {
  24508. this._clearCanvas();
  24509. this._touches.forEach(function (touch) {
  24510. if (touch.pointerId === _this._joystickPointerID) {
  24511. VirtualJoystick.vjCanvasContext.beginPath();
  24512. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24513. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24514. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  24515. VirtualJoystick.vjCanvasContext.stroke();
  24516. VirtualJoystick.vjCanvasContext.beginPath();
  24517. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24518. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24519. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  24520. VirtualJoystick.vjCanvasContext.stroke();
  24521. VirtualJoystick.vjCanvasContext.beginPath();
  24522. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24523. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  24524. VirtualJoystick.vjCanvasContext.stroke();
  24525. }
  24526. else {
  24527. VirtualJoystick.vjCanvasContext.beginPath();
  24528. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  24529. VirtualJoystick.vjCanvasContext.beginPath();
  24530. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  24531. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24532. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  24533. VirtualJoystick.vjCanvasContext.stroke();
  24534. }
  24535. ;
  24536. });
  24537. }
  24538. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24539. };
  24540. VirtualJoystick.prototype.releaseCanvas = function () {
  24541. if (VirtualJoystick.vjCanvas) {
  24542. document.body.removeChild(VirtualJoystick.vjCanvas);
  24543. VirtualJoystick.vjCanvas = null;
  24544. }
  24545. };
  24546. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  24547. VirtualJoystick._globalJoystickIndex = 0;
  24548. return VirtualJoystick;
  24549. })();
  24550. BABYLON.VirtualJoystick = VirtualJoystick;
  24551. })(BABYLON || (BABYLON = {}));
  24552. //# sourceMappingURL=babylon.virtualJoystick.js.map
  24553. var BABYLON;
  24554. (function (BABYLON) {
  24555. // We're mainly based on the logic defined into the FreeCamera code
  24556. var VirtualJoysticksCamera = (function (_super) {
  24557. __extends(VirtualJoysticksCamera, _super);
  24558. function VirtualJoysticksCamera(name, position, scene) {
  24559. _super.call(this, name, position, scene);
  24560. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  24561. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  24562. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  24563. this._leftjoystick.setJoystickSensibility(0.15);
  24564. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  24565. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  24566. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  24567. this._rightjoystick.reverseUpDown = true;
  24568. this._rightjoystick.setJoystickSensibility(0.05);
  24569. this._rightjoystick.setJoystickColor("yellow");
  24570. }
  24571. VirtualJoysticksCamera.prototype._checkInputs = function () {
  24572. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24573. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  24574. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24575. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  24576. if (!this._leftjoystick.pressed) {
  24577. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  24578. }
  24579. if (!this._rightjoystick.pressed) {
  24580. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  24581. }
  24582. _super.prototype._checkInputs.call(this);
  24583. };
  24584. VirtualJoysticksCamera.prototype.dispose = function () {
  24585. this._leftjoystick.releaseCanvas();
  24586. _super.prototype.dispose.call(this);
  24587. };
  24588. return VirtualJoysticksCamera;
  24589. })(BABYLON.FreeCamera);
  24590. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  24591. })(BABYLON || (BABYLON = {}));
  24592. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  24593. var BABYLON;
  24594. (function (BABYLON) {
  24595. var ShaderMaterial = (function (_super) {
  24596. __extends(ShaderMaterial, _super);
  24597. function ShaderMaterial(name, scene, shaderPath, options) {
  24598. _super.call(this, name, scene);
  24599. this._textures = new Array();
  24600. this._floats = new Array();
  24601. this._floatsArrays = {};
  24602. this._colors3 = new Array();
  24603. this._colors4 = new Array();
  24604. this._vectors2 = new Array();
  24605. this._vectors3 = new Array();
  24606. this._matrices = new Array();
  24607. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  24608. this._shaderPath = shaderPath;
  24609. options.needAlphaBlending = options.needAlphaBlending || false;
  24610. options.needAlphaTesting = options.needAlphaTesting || false;
  24611. options.attributes = options.attributes || ["position", "normal", "uv"];
  24612. options.uniforms = options.uniforms || ["worldViewProjection"];
  24613. options.samplers = options.samplers || [];
  24614. this._options = options;
  24615. }
  24616. ShaderMaterial.prototype.needAlphaBlending = function () {
  24617. return this._options.needAlphaBlending;
  24618. };
  24619. ShaderMaterial.prototype.needAlphaTesting = function () {
  24620. return this._options.needAlphaTesting;
  24621. };
  24622. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  24623. if (this._options.uniforms.indexOf(uniformName) === -1) {
  24624. this._options.uniforms.push(uniformName);
  24625. }
  24626. };
  24627. ShaderMaterial.prototype.setTexture = function (name, texture) {
  24628. if (this._options.samplers.indexOf(name) === -1) {
  24629. this._options.samplers.push(name);
  24630. }
  24631. this._textures[name] = texture;
  24632. return this;
  24633. };
  24634. ShaderMaterial.prototype.setFloat = function (name, value) {
  24635. this._checkUniform(name);
  24636. this._floats[name] = value;
  24637. return this;
  24638. };
  24639. ShaderMaterial.prototype.setFloats = function (name, value) {
  24640. this._checkUniform(name);
  24641. this._floatsArrays[name] = value;
  24642. return this;
  24643. };
  24644. ShaderMaterial.prototype.setColor3 = function (name, value) {
  24645. this._checkUniform(name);
  24646. this._colors3[name] = value;
  24647. return this;
  24648. };
  24649. ShaderMaterial.prototype.setColor4 = function (name, value) {
  24650. this._checkUniform(name);
  24651. this._colors4[name] = value;
  24652. return this;
  24653. };
  24654. ShaderMaterial.prototype.setVector2 = function (name, value) {
  24655. this._checkUniform(name);
  24656. this._vectors2[name] = value;
  24657. return this;
  24658. };
  24659. ShaderMaterial.prototype.setVector3 = function (name, value) {
  24660. this._checkUniform(name);
  24661. this._vectors3[name] = value;
  24662. return this;
  24663. };
  24664. ShaderMaterial.prototype.setMatrix = function (name, value) {
  24665. this._checkUniform(name);
  24666. this._matrices[name] = value;
  24667. return this;
  24668. };
  24669. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  24670. var scene = this.getScene();
  24671. var engine = scene.getEngine();
  24672. if (!this.checkReadyOnEveryCall) {
  24673. if (this._renderId === scene.getRenderId()) {
  24674. return true;
  24675. }
  24676. }
  24677. // Instances
  24678. var defines = [];
  24679. var fallbacks = new BABYLON.EffectFallbacks();
  24680. if (useInstances) {
  24681. defines.push("#define INSTANCES");
  24682. }
  24683. // Bones
  24684. if (mesh && mesh.useBones) {
  24685. defines.push("#define BONES");
  24686. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24687. defines.push("#define BONES4");
  24688. fallbacks.addFallback(0, "BONES4");
  24689. }
  24690. // Alpha test
  24691. if (engine.getAlphaTesting()) {
  24692. defines.push("#define ALPHATEST");
  24693. }
  24694. var previousEffect = this._effect;
  24695. var join = defines.join("\n");
  24696. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  24697. if (!this._effect.isReady()) {
  24698. return false;
  24699. }
  24700. if (previousEffect !== this._effect) {
  24701. scene.resetCachedMaterial();
  24702. }
  24703. this._renderId = scene.getRenderId();
  24704. return true;
  24705. };
  24706. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24707. var scene = this.getScene();
  24708. if (this._options.uniforms.indexOf("world") !== -1) {
  24709. this._effect.setMatrix("world", world);
  24710. }
  24711. if (this._options.uniforms.indexOf("worldView") !== -1) {
  24712. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  24713. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  24714. }
  24715. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  24716. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  24717. }
  24718. };
  24719. ShaderMaterial.prototype.bind = function (world, mesh) {
  24720. // Std values
  24721. this.bindOnlyWorldMatrix(world);
  24722. if (this.getScene().getCachedMaterial() !== this) {
  24723. if (this._options.uniforms.indexOf("view") !== -1) {
  24724. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  24725. }
  24726. if (this._options.uniforms.indexOf("projection") !== -1) {
  24727. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  24728. }
  24729. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  24730. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24731. }
  24732. // Bones
  24733. if (mesh && mesh.useBones) {
  24734. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24735. }
  24736. // Texture
  24737. for (var name in this._textures) {
  24738. this._effect.setTexture(name, this._textures[name]);
  24739. }
  24740. // Float
  24741. for (name in this._floats) {
  24742. this._effect.setFloat(name, this._floats[name]);
  24743. }
  24744. // Float s
  24745. for (name in this._floatsArrays) {
  24746. this._effect.setArray(name, this._floatsArrays[name]);
  24747. }
  24748. // Color3
  24749. for (name in this._colors3) {
  24750. this._effect.setColor3(name, this._colors3[name]);
  24751. }
  24752. // Color4
  24753. for (name in this._colors4) {
  24754. var color = this._colors4[name];
  24755. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24756. }
  24757. // Vector2
  24758. for (name in this._vectors2) {
  24759. this._effect.setVector2(name, this._vectors2[name]);
  24760. }
  24761. // Vector3
  24762. for (name in this._vectors3) {
  24763. this._effect.setVector3(name, this._vectors3[name]);
  24764. }
  24765. // Matrix
  24766. for (name in this._matrices) {
  24767. this._effect.setMatrix(name, this._matrices[name]);
  24768. }
  24769. }
  24770. _super.prototype.bind.call(this, world, mesh);
  24771. };
  24772. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  24773. for (var name in this._textures) {
  24774. this._textures[name].dispose();
  24775. }
  24776. this._textures = [];
  24777. _super.prototype.dispose.call(this, forceDisposeEffect);
  24778. };
  24779. return ShaderMaterial;
  24780. })(BABYLON.Material);
  24781. BABYLON.ShaderMaterial = ShaderMaterial;
  24782. })(BABYLON || (BABYLON = {}));
  24783. //# sourceMappingURL=babylon.shaderMaterial.js.map
  24784. var BABYLON;
  24785. (function (BABYLON) {
  24786. var VertexData = (function () {
  24787. function VertexData() {
  24788. }
  24789. VertexData.prototype.set = function (data, kind) {
  24790. switch (kind) {
  24791. case BABYLON.VertexBuffer.PositionKind:
  24792. this.positions = data;
  24793. break;
  24794. case BABYLON.VertexBuffer.NormalKind:
  24795. this.normals = data;
  24796. break;
  24797. case BABYLON.VertexBuffer.UVKind:
  24798. this.uvs = data;
  24799. break;
  24800. case BABYLON.VertexBuffer.UV2Kind:
  24801. this.uv2s = data;
  24802. break;
  24803. case BABYLON.VertexBuffer.ColorKind:
  24804. this.colors = data;
  24805. break;
  24806. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24807. this.matricesIndices = data;
  24808. break;
  24809. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24810. this.matricesWeights = data;
  24811. break;
  24812. }
  24813. };
  24814. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24815. this._applyTo(mesh, updatable);
  24816. };
  24817. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24818. this._applyTo(geometry, updatable);
  24819. };
  24820. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24821. this._update(mesh);
  24822. };
  24823. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24824. this._update(geometry);
  24825. };
  24826. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24827. if (this.positions) {
  24828. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24829. }
  24830. if (this.normals) {
  24831. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24832. }
  24833. if (this.uvs) {
  24834. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24835. }
  24836. if (this.uv2s) {
  24837. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  24838. }
  24839. if (this.colors) {
  24840. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24841. }
  24842. if (this.matricesIndices) {
  24843. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24844. }
  24845. if (this.matricesWeights) {
  24846. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24847. }
  24848. if (this.indices) {
  24849. meshOrGeometry.setIndices(this.indices);
  24850. }
  24851. };
  24852. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24853. if (this.positions) {
  24854. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24855. }
  24856. if (this.normals) {
  24857. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24858. }
  24859. if (this.uvs) {
  24860. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24861. }
  24862. if (this.uv2s) {
  24863. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  24864. }
  24865. if (this.colors) {
  24866. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24867. }
  24868. if (this.matricesIndices) {
  24869. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24870. }
  24871. if (this.matricesWeights) {
  24872. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24873. }
  24874. if (this.indices) {
  24875. meshOrGeometry.setIndices(this.indices);
  24876. }
  24877. };
  24878. VertexData.prototype.transform = function (matrix) {
  24879. var transformed = BABYLON.Vector3.Zero();
  24880. if (this.positions) {
  24881. var position = BABYLON.Vector3.Zero();
  24882. for (var index = 0; index < this.positions.length; index += 3) {
  24883. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24884. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24885. this.positions[index] = transformed.x;
  24886. this.positions[index + 1] = transformed.y;
  24887. this.positions[index + 2] = transformed.z;
  24888. }
  24889. }
  24890. if (this.normals) {
  24891. var normal = BABYLON.Vector3.Zero();
  24892. for (index = 0; index < this.normals.length; index += 3) {
  24893. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24894. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24895. this.normals[index] = transformed.x;
  24896. this.normals[index + 1] = transformed.y;
  24897. this.normals[index + 2] = transformed.z;
  24898. }
  24899. }
  24900. };
  24901. VertexData.prototype.merge = function (other) {
  24902. if (other.indices) {
  24903. if (!this.indices) {
  24904. this.indices = [];
  24905. }
  24906. var offset = this.positions ? this.positions.length / 3 : 0;
  24907. for (var index = 0; index < other.indices.length; index++) {
  24908. this.indices.push(other.indices[index] + offset);
  24909. }
  24910. }
  24911. if (other.positions) {
  24912. if (!this.positions) {
  24913. this.positions = [];
  24914. }
  24915. for (index = 0; index < other.positions.length; index++) {
  24916. this.positions.push(other.positions[index]);
  24917. }
  24918. }
  24919. if (other.normals) {
  24920. if (!this.normals) {
  24921. this.normals = [];
  24922. }
  24923. for (index = 0; index < other.normals.length; index++) {
  24924. this.normals.push(other.normals[index]);
  24925. }
  24926. }
  24927. if (other.uvs) {
  24928. if (!this.uvs) {
  24929. this.uvs = [];
  24930. }
  24931. for (index = 0; index < other.uvs.length; index++) {
  24932. this.uvs.push(other.uvs[index]);
  24933. }
  24934. }
  24935. if (other.uv2s) {
  24936. if (!this.uv2s) {
  24937. this.uv2s = [];
  24938. }
  24939. for (index = 0; index < other.uv2s.length; index++) {
  24940. this.uv2s.push(other.uv2s[index]);
  24941. }
  24942. }
  24943. if (other.matricesIndices) {
  24944. if (!this.matricesIndices) {
  24945. this.matricesIndices = [];
  24946. }
  24947. for (index = 0; index < other.matricesIndices.length; index++) {
  24948. this.matricesIndices.push(other.matricesIndices[index]);
  24949. }
  24950. }
  24951. if (other.matricesWeights) {
  24952. if (!this.matricesWeights) {
  24953. this.matricesWeights = [];
  24954. }
  24955. for (index = 0; index < other.matricesWeights.length; index++) {
  24956. this.matricesWeights.push(other.matricesWeights[index]);
  24957. }
  24958. }
  24959. if (other.colors) {
  24960. if (!this.colors) {
  24961. this.colors = [];
  24962. }
  24963. for (index = 0; index < other.colors.length; index++) {
  24964. this.colors.push(other.colors[index]);
  24965. }
  24966. }
  24967. };
  24968. // Statics
  24969. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24970. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24971. };
  24972. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24973. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24974. };
  24975. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24976. var result = new VertexData();
  24977. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24978. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24979. }
  24980. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24981. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24982. }
  24983. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24984. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24985. }
  24986. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24987. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24988. }
  24989. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24990. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24991. }
  24992. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24993. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24994. }
  24995. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24996. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24997. }
  24998. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24999. return result;
  25000. };
  25001. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  25002. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25003. closeArray = closeArray || false;
  25004. closePath = closePath || false;
  25005. var defaultOffset = Math.floor(pathArray[0].length / 2);
  25006. offset = offset || defaultOffset;
  25007. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  25008. var positions = [];
  25009. var indices = [];
  25010. var normals = [];
  25011. var uvs = [];
  25012. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  25013. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  25014. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  25015. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  25016. var minlg; // minimal length among all paths from pathArray
  25017. var lg = []; // array of path lengths : nb of vertex per path
  25018. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  25019. var p; // path iterator
  25020. var i; // point iterator
  25021. var j; // point iterator
  25022. // if single path in pathArray
  25023. if (pathArray.length < 2) {
  25024. var ar1 = [];
  25025. var ar2 = [];
  25026. for (i = 0; i < pathArray[0].length - offset; i++) {
  25027. ar1.push(pathArray[0][i]);
  25028. ar2.push(pathArray[0][i + offset]);
  25029. }
  25030. pathArray = [ar1, ar2];
  25031. }
  25032. // positions and horizontal distances (u)
  25033. var idc = 0;
  25034. minlg = pathArray[0].length;
  25035. for (p = 0; p < pathArray.length; p++) {
  25036. uTotalDistance[p] = 0;
  25037. us[p] = [0];
  25038. var path = pathArray[p];
  25039. var l = path.length;
  25040. minlg = (minlg < l) ? minlg : l;
  25041. lg[p] = l;
  25042. idx[p] = idc;
  25043. j = 0;
  25044. while (j < l) {
  25045. positions.push(path[j].x, path[j].y, path[j].z);
  25046. if (j > 0) {
  25047. var vectlg = path[j].subtract(path[j - 1]).length();
  25048. var dist = vectlg + uTotalDistance[p];
  25049. us[p].push(dist);
  25050. uTotalDistance[p] = dist;
  25051. }
  25052. j++;
  25053. }
  25054. if (closePath) {
  25055. vectlg = path[0].subtract(path[j - 1]).length();
  25056. dist = vectlg + uTotalDistance[p];
  25057. uTotalDistance[p] = dist;
  25058. }
  25059. idc += l;
  25060. }
  25061. // vertical distances (v)
  25062. for (i = 0; i < minlg; i++) {
  25063. vTotalDistance[i] = 0;
  25064. vs[i] = [0];
  25065. var path1;
  25066. var path2;
  25067. for (p = 0; p < pathArray.length - 1; p++) {
  25068. path1 = pathArray[p];
  25069. path2 = pathArray[p + 1];
  25070. vectlg = path2[i].subtract(path1[i]).length();
  25071. dist = vectlg + vTotalDistance[i];
  25072. vs[i].push(dist);
  25073. vTotalDistance[i] = dist;
  25074. }
  25075. if (closeArray) {
  25076. path1 = pathArray[p];
  25077. path2 = pathArray[0];
  25078. vectlg = path2[i].subtract(path1[i]).length();
  25079. dist = vectlg + vTotalDistance[i];
  25080. vTotalDistance[i] = dist;
  25081. }
  25082. }
  25083. // uvs
  25084. var u;
  25085. var v;
  25086. for (p = 0; p < pathArray.length; p++) {
  25087. for (i = 0; i < minlg; i++) {
  25088. u = us[p][i] / uTotalDistance[p];
  25089. v = vs[i][p] / vTotalDistance[i];
  25090. uvs.push(u, v);
  25091. }
  25092. }
  25093. // indices
  25094. p = 0; // path index
  25095. var pi = 0; // positions array index
  25096. var l1 = lg[p] - 1; // path1 length
  25097. var l2 = lg[p + 1] - 1; // path2 length
  25098. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25099. var shft = idx[1] - idx[0]; // shift
  25100. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  25101. var t1; // two consecutive triangles, so 4 points : point1
  25102. var t2; // point2
  25103. var t3; // point3
  25104. var t4; // point4
  25105. while (pi <= min && p < path1nb) {
  25106. // 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
  25107. t1 = pi;
  25108. t2 = pi + shft;
  25109. t3 = pi + 1;
  25110. t4 = pi + shft + 1;
  25111. indices.push(pi, pi + shft, pi + 1);
  25112. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25113. pi += 1;
  25114. if (pi === min) {
  25115. if (closePath) {
  25116. indices.push(pi, pi + shft, idx[p]);
  25117. indices.push(idx[p] + shft, idx[p], pi + shft);
  25118. t3 = idx[p];
  25119. t4 = idx[p] + shft;
  25120. }
  25121. p++;
  25122. if (p === lg.length - 1) {
  25123. shft = idx[0] - idx[p];
  25124. l1 = lg[p] - 1;
  25125. l2 = lg[0] - 1;
  25126. }
  25127. else {
  25128. shft = idx[p + 1] - idx[p];
  25129. l1 = lg[p] - 1;
  25130. l2 = lg[p + 1] - 1;
  25131. }
  25132. pi = idx[p];
  25133. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25134. }
  25135. }
  25136. // normals
  25137. VertexData.ComputeNormals(positions, indices, normals);
  25138. // sides
  25139. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25140. // Result
  25141. var vertexData = new VertexData();
  25142. vertexData.indices = indices;
  25143. vertexData.positions = positions;
  25144. vertexData.normals = normals;
  25145. vertexData.uvs = uvs;
  25146. return vertexData;
  25147. };
  25148. VertexData.CreateBox = function (size, sideOrientation) {
  25149. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25150. var normalsSource = [
  25151. new BABYLON.Vector3(0, 0, 1),
  25152. new BABYLON.Vector3(0, 0, -1),
  25153. new BABYLON.Vector3(1, 0, 0),
  25154. new BABYLON.Vector3(-1, 0, 0),
  25155. new BABYLON.Vector3(0, 1, 0),
  25156. new BABYLON.Vector3(0, -1, 0)
  25157. ];
  25158. var indices = [];
  25159. var positions = [];
  25160. var normals = [];
  25161. var uvs = [];
  25162. size = size || 1;
  25163. // Create each face in turn.
  25164. for (var index = 0; index < normalsSource.length; index++) {
  25165. var normal = normalsSource[index];
  25166. // Get two vectors perpendicular to the face normal and to each other.
  25167. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25168. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25169. // Six indices (two triangles) per face.
  25170. var verticesLength = positions.length / 3;
  25171. indices.push(verticesLength);
  25172. indices.push(verticesLength + 1);
  25173. indices.push(verticesLength + 2);
  25174. indices.push(verticesLength);
  25175. indices.push(verticesLength + 2);
  25176. indices.push(verticesLength + 3);
  25177. // Four vertices per face.
  25178. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  25179. positions.push(vertex.x, vertex.y, vertex.z);
  25180. normals.push(normal.x, normal.y, normal.z);
  25181. uvs.push(1.0, 1.0);
  25182. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  25183. positions.push(vertex.x, vertex.y, vertex.z);
  25184. normals.push(normal.x, normal.y, normal.z);
  25185. uvs.push(0.0, 1.0);
  25186. vertex = normal.add(side1).add(side2).scale(size / 2);
  25187. positions.push(vertex.x, vertex.y, vertex.z);
  25188. normals.push(normal.x, normal.y, normal.z);
  25189. uvs.push(0.0, 0.0);
  25190. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  25191. positions.push(vertex.x, vertex.y, vertex.z);
  25192. normals.push(normal.x, normal.y, normal.z);
  25193. uvs.push(1.0, 0.0);
  25194. }
  25195. // sides
  25196. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25197. // Result
  25198. var vertexData = new VertexData();
  25199. vertexData.indices = indices;
  25200. vertexData.positions = positions;
  25201. vertexData.normals = normals;
  25202. vertexData.uvs = uvs;
  25203. return vertexData;
  25204. };
  25205. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  25206. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25207. segments = segments || 32;
  25208. diameter = diameter || 1;
  25209. var radius = diameter / 2;
  25210. var totalZRotationSteps = 2 + segments;
  25211. var totalYRotationSteps = 2 * totalZRotationSteps;
  25212. var indices = [];
  25213. var positions = [];
  25214. var normals = [];
  25215. var uvs = [];
  25216. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25217. var normalizedZ = zRotationStep / totalZRotationSteps;
  25218. var angleZ = (normalizedZ * Math.PI);
  25219. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25220. var normalizedY = yRotationStep / totalYRotationSteps;
  25221. var angleY = normalizedY * Math.PI * 2;
  25222. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25223. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25224. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25225. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25226. var vertex = complete.scale(radius);
  25227. var normal = BABYLON.Vector3.Normalize(vertex);
  25228. positions.push(vertex.x, vertex.y, vertex.z);
  25229. normals.push(normal.x, normal.y, normal.z);
  25230. uvs.push(normalizedZ, normalizedY);
  25231. }
  25232. if (zRotationStep > 0) {
  25233. var verticesCount = positions.length / 3;
  25234. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25235. indices.push((firstIndex));
  25236. indices.push((firstIndex + 1));
  25237. indices.push(firstIndex + totalYRotationSteps + 1);
  25238. indices.push((firstIndex + totalYRotationSteps + 1));
  25239. indices.push((firstIndex + 1));
  25240. indices.push((firstIndex + totalYRotationSteps + 2));
  25241. }
  25242. }
  25243. }
  25244. // Sides
  25245. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25246. // Result
  25247. var vertexData = new VertexData();
  25248. vertexData.indices = indices;
  25249. vertexData.positions = positions;
  25250. vertexData.normals = normals;
  25251. vertexData.uvs = uvs;
  25252. return vertexData;
  25253. };
  25254. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  25255. if (subdivisions === void 0) { subdivisions = 1; }
  25256. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25257. var radiusTop = diameterTop / 2;
  25258. var radiusBottom = diameterBottom / 2;
  25259. var indices = [];
  25260. var positions = [];
  25261. var normals = [];
  25262. var uvs = [];
  25263. height = height || 1;
  25264. diameterTop = diameterTop || 0.5;
  25265. diameterBottom = diameterBottom || 1;
  25266. tessellation = tessellation || 16;
  25267. subdivisions = subdivisions || 1;
  25268. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  25269. var getCircleVector = function (i) {
  25270. var angle = (i * 2.0 * Math.PI / tessellation);
  25271. var dx = Math.cos(angle);
  25272. var dz = Math.sin(angle);
  25273. return new BABYLON.Vector3(dx, 0, dz);
  25274. };
  25275. var createCylinderCap = function (isTop) {
  25276. var radius = isTop ? radiusTop : radiusBottom;
  25277. if (radius === 0) {
  25278. return;
  25279. }
  25280. var vbase = positions.length / 3;
  25281. var offset = new BABYLON.Vector3(0, height / 2, 0);
  25282. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25283. if (!isTop) {
  25284. offset.scaleInPlace(-1);
  25285. textureScale.x = -textureScale.x;
  25286. }
  25287. // Positions, normals & uvs
  25288. for (var i = 0; i < tessellation; i++) {
  25289. var circleVector = getCircleVector(i);
  25290. var position = circleVector.scale(radius).add(offset);
  25291. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  25292. positions.push(position.x, position.y, position.z);
  25293. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25294. }
  25295. // Indices
  25296. for (i = 0; i < tessellation - 2; i++) {
  25297. if (!isTop) {
  25298. indices.push(vbase);
  25299. indices.push(vbase + (i + 2) % tessellation);
  25300. indices.push(vbase + (i + 1) % tessellation);
  25301. }
  25302. else {
  25303. indices.push(vbase);
  25304. indices.push(vbase + (i + 1) % tessellation);
  25305. indices.push(vbase + (i + 2) % tessellation);
  25306. }
  25307. }
  25308. };
  25309. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  25310. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  25311. var stride = tessellation + 1;
  25312. // Positions, normals & uvs
  25313. for (var i = 0; i <= tessellation; i++) {
  25314. var circleVector = getCircleVector(i);
  25315. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  25316. var position, radius = radiusBottom;
  25317. for (var s = 0; s <= subdivisions; s++) {
  25318. // Update variables
  25319. position = circleVector.scale(radius);
  25320. position.addInPlace(base.add(offset.scale(s)));
  25321. textureCoordinate.y += 1 / subdivisions;
  25322. radius += (radiusTop - radiusBottom) / subdivisions;
  25323. // Push in arrays
  25324. positions.push(position.x, position.y, position.z);
  25325. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25326. }
  25327. }
  25328. subdivisions += 1;
  25329. // Indices
  25330. for (s = 0; s < subdivisions - 1; s++) {
  25331. for (i = 0; i <= tessellation; i++) {
  25332. indices.push(i * subdivisions + s);
  25333. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25334. indices.push(i * subdivisions + (s + 1));
  25335. indices.push(i * subdivisions + (s + 1));
  25336. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25337. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  25338. }
  25339. }
  25340. // Create flat triangle fan caps to seal the top and bottom.
  25341. createCylinderCap(true);
  25342. createCylinderCap(false);
  25343. // Normals
  25344. VertexData.ComputeNormals(positions, indices, normals);
  25345. // Sides
  25346. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25347. // Result
  25348. var vertexData = new VertexData();
  25349. vertexData.indices = indices;
  25350. vertexData.positions = positions;
  25351. vertexData.normals = normals;
  25352. vertexData.uvs = uvs;
  25353. return vertexData;
  25354. };
  25355. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  25356. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25357. var indices = [];
  25358. var positions = [];
  25359. var normals = [];
  25360. var uvs = [];
  25361. diameter = diameter || 1;
  25362. thickness = thickness || 0.5;
  25363. tessellation = tessellation || 16;
  25364. var stride = tessellation + 1;
  25365. for (var i = 0; i <= tessellation; i++) {
  25366. var u = i / tessellation;
  25367. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25368. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25369. for (var j = 0; j <= tessellation; j++) {
  25370. var v = 1 - j / tessellation;
  25371. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25372. var dx = Math.cos(innerAngle);
  25373. var dy = Math.sin(innerAngle);
  25374. // Create a vertex.
  25375. var normal = new BABYLON.Vector3(dx, dy, 0);
  25376. var position = normal.scale(thickness / 2);
  25377. var textureCoordinate = new BABYLON.Vector2(u, v);
  25378. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25379. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25380. positions.push(position.x, position.y, position.z);
  25381. normals.push(normal.x, normal.y, normal.z);
  25382. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25383. // And create indices for two triangles.
  25384. var nextI = (i + 1) % stride;
  25385. var nextJ = (j + 1) % stride;
  25386. indices.push(i * stride + j);
  25387. indices.push(i * stride + nextJ);
  25388. indices.push(nextI * stride + j);
  25389. indices.push(i * stride + nextJ);
  25390. indices.push(nextI * stride + nextJ);
  25391. indices.push(nextI * stride + j);
  25392. }
  25393. }
  25394. // Sides
  25395. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25396. // Result
  25397. var vertexData = new VertexData();
  25398. vertexData.indices = indices;
  25399. vertexData.positions = positions;
  25400. vertexData.normals = normals;
  25401. vertexData.uvs = uvs;
  25402. return vertexData;
  25403. };
  25404. VertexData.CreateLines = function (points) {
  25405. var indices = [];
  25406. var positions = [];
  25407. for (var index = 0; index < points.length; index++) {
  25408. positions.push(points[index].x, points[index].y, points[index].z);
  25409. if (index > 0) {
  25410. indices.push(index - 1);
  25411. indices.push(index);
  25412. }
  25413. }
  25414. // Result
  25415. var vertexData = new VertexData();
  25416. vertexData.indices = indices;
  25417. vertexData.positions = positions;
  25418. return vertexData;
  25419. };
  25420. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  25421. dashSize = dashSize || 3;
  25422. gapSize = gapSize || 1;
  25423. dashNb = dashNb || 200;
  25424. var positions = new Array();
  25425. var indices = new Array();
  25426. var curvect = BABYLON.Vector3.Zero();
  25427. var lg = 0;
  25428. var nb = 0;
  25429. var shft = 0;
  25430. var dashshft = 0;
  25431. var curshft = 0;
  25432. var idx = 0;
  25433. var i = 0;
  25434. for (i = 0; i < points.length - 1; i++) {
  25435. points[i + 1].subtractToRef(points[i], curvect);
  25436. lg += curvect.length();
  25437. }
  25438. shft = lg / dashNb;
  25439. dashshft = dashSize * shft / (dashSize + gapSize);
  25440. for (i = 0; i < points.length - 1; i++) {
  25441. points[i + 1].subtractToRef(points[i], curvect);
  25442. nb = Math.floor(curvect.length() / shft);
  25443. curvect.normalize();
  25444. for (var j = 0; j < nb; j++) {
  25445. curshft = shft * j;
  25446. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25447. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25448. indices.push(idx, idx + 1);
  25449. idx += 2;
  25450. }
  25451. }
  25452. // Result
  25453. var vertexData = new VertexData();
  25454. vertexData.positions = positions;
  25455. vertexData.indices = indices;
  25456. return vertexData;
  25457. };
  25458. VertexData.CreateGround = function (width, height, subdivisions) {
  25459. var indices = [];
  25460. var positions = [];
  25461. var normals = [];
  25462. var uvs = [];
  25463. var row, col;
  25464. width = width || 1;
  25465. height = height || 1;
  25466. subdivisions = subdivisions || 1;
  25467. for (row = 0; row <= subdivisions; row++) {
  25468. for (col = 0; col <= subdivisions; col++) {
  25469. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25470. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25471. positions.push(position.x, position.y, position.z);
  25472. normals.push(normal.x, normal.y, normal.z);
  25473. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25474. }
  25475. }
  25476. for (row = 0; row < subdivisions; row++) {
  25477. for (col = 0; col < subdivisions; col++) {
  25478. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25479. indices.push(col + 1 + row * (subdivisions + 1));
  25480. indices.push(col + row * (subdivisions + 1));
  25481. indices.push(col + (row + 1) * (subdivisions + 1));
  25482. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25483. indices.push(col + row * (subdivisions + 1));
  25484. }
  25485. }
  25486. // Result
  25487. var vertexData = new VertexData();
  25488. vertexData.indices = indices;
  25489. vertexData.positions = positions;
  25490. vertexData.normals = normals;
  25491. vertexData.uvs = uvs;
  25492. return vertexData;
  25493. };
  25494. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  25495. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  25496. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  25497. var indices = [];
  25498. var positions = [];
  25499. var normals = [];
  25500. var uvs = [];
  25501. var row, col, tileRow, tileCol;
  25502. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25503. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25504. precision.w = (precision.w < 1) ? 1 : precision.w;
  25505. precision.h = (precision.h < 1) ? 1 : precision.h;
  25506. var tileSize = {
  25507. 'w': (xmax - xmin) / subdivisions.w,
  25508. 'h': (zmax - zmin) / subdivisions.h
  25509. };
  25510. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25511. // Indices
  25512. var base = positions.length / 3;
  25513. var rowLength = precision.w + 1;
  25514. for (row = 0; row < precision.h; row++) {
  25515. for (col = 0; col < precision.w; col++) {
  25516. var square = [
  25517. base + col + row * rowLength,
  25518. base + (col + 1) + row * rowLength,
  25519. base + (col + 1) + (row + 1) * rowLength,
  25520. base + col + (row + 1) * rowLength
  25521. ];
  25522. indices.push(square[1]);
  25523. indices.push(square[2]);
  25524. indices.push(square[3]);
  25525. indices.push(square[0]);
  25526. indices.push(square[1]);
  25527. indices.push(square[3]);
  25528. }
  25529. }
  25530. // Position, normals and uvs
  25531. var position = BABYLON.Vector3.Zero();
  25532. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25533. for (row = 0; row <= precision.h; row++) {
  25534. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25535. for (col = 0; col <= precision.w; col++) {
  25536. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25537. position.y = 0;
  25538. positions.push(position.x, position.y, position.z);
  25539. normals.push(normal.x, normal.y, normal.z);
  25540. uvs.push(col / precision.w, row / precision.h);
  25541. }
  25542. }
  25543. }
  25544. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25545. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25546. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25547. }
  25548. }
  25549. // Result
  25550. var vertexData = new VertexData();
  25551. vertexData.indices = indices;
  25552. vertexData.positions = positions;
  25553. vertexData.normals = normals;
  25554. vertexData.uvs = uvs;
  25555. return vertexData;
  25556. };
  25557. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  25558. var indices = [];
  25559. var positions = [];
  25560. var normals = [];
  25561. var uvs = [];
  25562. var row, col;
  25563. // Vertices
  25564. for (row = 0; row <= subdivisions; row++) {
  25565. for (col = 0; col <= subdivisions; col++) {
  25566. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25567. // Compute height
  25568. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  25569. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  25570. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  25571. var r = buffer[pos] / 255.0;
  25572. var g = buffer[pos + 1] / 255.0;
  25573. var b = buffer[pos + 2] / 255.0;
  25574. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25575. position.y = minHeight + (maxHeight - minHeight) * gradient;
  25576. // Add vertex
  25577. positions.push(position.x, position.y, position.z);
  25578. normals.push(0, 0, 0);
  25579. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25580. }
  25581. }
  25582. // Indices
  25583. for (row = 0; row < subdivisions; row++) {
  25584. for (col = 0; col < subdivisions; col++) {
  25585. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25586. indices.push(col + 1 + row * (subdivisions + 1));
  25587. indices.push(col + row * (subdivisions + 1));
  25588. indices.push(col + (row + 1) * (subdivisions + 1));
  25589. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25590. indices.push(col + row * (subdivisions + 1));
  25591. }
  25592. }
  25593. // Normals
  25594. VertexData.ComputeNormals(positions, indices, normals);
  25595. // Result
  25596. var vertexData = new VertexData();
  25597. vertexData.indices = indices;
  25598. vertexData.positions = positions;
  25599. vertexData.normals = normals;
  25600. vertexData.uvs = uvs;
  25601. return vertexData;
  25602. };
  25603. VertexData.CreatePlane = function (size, sideOrientation) {
  25604. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25605. var indices = [];
  25606. var positions = [];
  25607. var normals = [];
  25608. var uvs = [];
  25609. size = size || 1;
  25610. // Vertices
  25611. var halfSize = size / 2.0;
  25612. positions.push(-halfSize, -halfSize, 0);
  25613. normals.push(0, 0, -1.0);
  25614. uvs.push(0.0, 0.0);
  25615. positions.push(halfSize, -halfSize, 0);
  25616. normals.push(0, 0, -1.0);
  25617. uvs.push(1.0, 0.0);
  25618. positions.push(halfSize, halfSize, 0);
  25619. normals.push(0, 0, -1.0);
  25620. uvs.push(1.0, 1.0);
  25621. positions.push(-halfSize, halfSize, 0);
  25622. normals.push(0, 0, -1.0);
  25623. uvs.push(0.0, 1.0);
  25624. // Indices
  25625. indices.push(0);
  25626. indices.push(1);
  25627. indices.push(2);
  25628. indices.push(0);
  25629. indices.push(2);
  25630. indices.push(3);
  25631. // Sides
  25632. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25633. // Result
  25634. var vertexData = new VertexData();
  25635. vertexData.indices = indices;
  25636. vertexData.positions = positions;
  25637. vertexData.normals = normals;
  25638. vertexData.uvs = uvs;
  25639. return vertexData;
  25640. };
  25641. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  25642. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25643. var positions = [];
  25644. var indices = [];
  25645. var normals = [];
  25646. var uvs = [];
  25647. // positions and uvs
  25648. positions.push(0, 0, 0); // disc center first
  25649. uvs.push(0.5, 0.5);
  25650. var step = Math.PI * 2 / tessellation;
  25651. for (var a = 0; a < Math.PI * 2; a += step) {
  25652. var x = Math.cos(a);
  25653. var y = Math.sin(a);
  25654. var u = (x + 1) / 2;
  25655. var v = (1 - y) / 2;
  25656. positions.push(radius * x, radius * y, 0);
  25657. uvs.push(u, v);
  25658. }
  25659. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25660. uvs.push(uvs[2], uvs[3]);
  25661. //indices
  25662. var vertexNb = positions.length / 3;
  25663. for (var i = 1; i < vertexNb - 1; i++) {
  25664. indices.push(i + 1, 0, i);
  25665. }
  25666. // result
  25667. VertexData.ComputeNormals(positions, indices, normals);
  25668. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25669. var vertexData = new VertexData();
  25670. vertexData.indices = indices;
  25671. vertexData.positions = positions;
  25672. vertexData.normals = normals;
  25673. vertexData.uvs = uvs;
  25674. return vertexData;
  25675. };
  25676. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25677. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  25678. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25679. var indices = [];
  25680. var positions = [];
  25681. var normals = [];
  25682. var uvs = [];
  25683. radius = radius || 2;
  25684. tube = tube || 0.5;
  25685. radialSegments = radialSegments || 32;
  25686. tubularSegments = tubularSegments || 32;
  25687. p = p || 2;
  25688. q = q || 3;
  25689. // Helper
  25690. var getPos = function (angle) {
  25691. var cu = Math.cos(angle);
  25692. var su = Math.sin(angle);
  25693. var quOverP = q / p * angle;
  25694. var cs = Math.cos(quOverP);
  25695. var tx = radius * (2 + cs) * 0.5 * cu;
  25696. var ty = radius * (2 + cs) * su * 0.5;
  25697. var tz = radius * Math.sin(quOverP) * 0.5;
  25698. return new BABYLON.Vector3(tx, ty, tz);
  25699. };
  25700. // Vertices
  25701. for (var i = 0; i <= radialSegments; i++) {
  25702. var modI = i % radialSegments;
  25703. var u = modI / radialSegments * 2 * p * Math.PI;
  25704. var p1 = getPos(u);
  25705. var p2 = getPos(u + 0.01);
  25706. var tang = p2.subtract(p1);
  25707. var n = p2.add(p1);
  25708. var bitan = BABYLON.Vector3.Cross(tang, n);
  25709. n = BABYLON.Vector3.Cross(bitan, tang);
  25710. bitan.normalize();
  25711. n.normalize();
  25712. for (var j = 0; j < tubularSegments; j++) {
  25713. var modJ = j % tubularSegments;
  25714. var v = modJ / tubularSegments * 2 * Math.PI;
  25715. var cx = -tube * Math.cos(v);
  25716. var cy = tube * Math.sin(v);
  25717. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25718. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25719. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25720. uvs.push(i / radialSegments);
  25721. uvs.push(j / tubularSegments);
  25722. }
  25723. }
  25724. for (i = 0; i < radialSegments; i++) {
  25725. for (j = 0; j < tubularSegments; j++) {
  25726. var jNext = (j + 1) % tubularSegments;
  25727. var a = i * tubularSegments + j;
  25728. var b = (i + 1) * tubularSegments + j;
  25729. var c = (i + 1) * tubularSegments + jNext;
  25730. var d = i * tubularSegments + jNext;
  25731. indices.push(d);
  25732. indices.push(b);
  25733. indices.push(a);
  25734. indices.push(d);
  25735. indices.push(c);
  25736. indices.push(b);
  25737. }
  25738. }
  25739. // Normals
  25740. VertexData.ComputeNormals(positions, indices, normals);
  25741. // Sides
  25742. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25743. // Result
  25744. var vertexData = new VertexData();
  25745. vertexData.indices = indices;
  25746. vertexData.positions = positions;
  25747. vertexData.normals = normals;
  25748. vertexData.uvs = uvs;
  25749. return vertexData;
  25750. };
  25751. // Tools
  25752. /**
  25753. * @param {any} - positions (number[] or Float32Array)
  25754. * @param {any} - indices (number[] or Uint16Array)
  25755. * @param {any} - normals (number[] or Float32Array)
  25756. */
  25757. VertexData.ComputeNormals = function (positions, indices, normals) {
  25758. var index = 0;
  25759. // temp Vector3
  25760. var p1 = BABYLON.Vector3.Zero();
  25761. var p2 = BABYLON.Vector3.Zero();
  25762. var p3 = BABYLON.Vector3.Zero();
  25763. var p1p2 = BABYLON.Vector3.Zero();
  25764. var p3p2 = BABYLON.Vector3.Zero();
  25765. var faceNormal = BABYLON.Vector3.Zero();
  25766. var vertexNormali1 = BABYLON.Vector3.Zero();
  25767. var vertexNormali2 = BABYLON.Vector3.Zero();
  25768. var vertexNormali3 = BABYLON.Vector3.Zero();
  25769. // indice triplet = 1 face
  25770. var nbFaces = indices.length / 3;
  25771. for (index = 0; index < nbFaces; index++) {
  25772. var i1 = indices[index * 3];
  25773. var i2 = indices[index * 3 + 1];
  25774. var i3 = indices[index * 3 + 2];
  25775. // setting the temp V3
  25776. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  25777. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  25778. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  25779. p1.subtractToRef(p2, p1p2);
  25780. p3.subtractToRef(p2, p3p2);
  25781. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  25782. faceNormal.normalize();
  25783. // All intermediate results are stored in the normals array :
  25784. // get the normals at i1, i2 and i3 indexes
  25785. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  25786. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  25787. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  25788. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  25789. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  25790. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  25791. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  25792. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  25793. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  25794. // make intermediate vectors3 from normals values
  25795. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  25796. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  25797. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  25798. // add the current face normals to these intermediate vectors3
  25799. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  25800. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  25801. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  25802. // store back intermediate vectors3 into the normals array
  25803. normals[i1 * 3] = vertexNormali1.x;
  25804. normals[i1 * 3 + 1] = vertexNormali1.y;
  25805. normals[i1 * 3 + 2] = vertexNormali1.z;
  25806. normals[i2 * 3] = vertexNormali2.x;
  25807. normals[i2 * 3 + 1] = vertexNormali2.y;
  25808. normals[i2 * 3 + 2] = vertexNormali2.z;
  25809. normals[i3 * 3] = vertexNormali3.x;
  25810. normals[i3 * 3 + 1] = vertexNormali3.y;
  25811. normals[i3 * 3 + 2] = vertexNormali3.z;
  25812. }
  25813. // last normalization
  25814. for (index = 0; index < normals.length / 3; index++) {
  25815. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  25816. vertexNormali1.normalize();
  25817. normals[index * 3] = vertexNormali1.x;
  25818. normals[index * 3 + 1] = vertexNormali1.y;
  25819. normals[index * 3 + 2] = vertexNormali1.z;
  25820. }
  25821. };
  25822. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25823. var li = indices.length;
  25824. var ln = normals.length;
  25825. var i;
  25826. var n;
  25827. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25828. switch (sideOrientation) {
  25829. case BABYLON.Mesh.FRONTSIDE:
  25830. // nothing changed
  25831. break;
  25832. case BABYLON.Mesh.BACKSIDE:
  25833. var tmp;
  25834. // indices
  25835. for (i = 0; i < li; i += 3) {
  25836. tmp = indices[i];
  25837. indices[i] = indices[i + 2];
  25838. indices[i + 2] = tmp;
  25839. }
  25840. // normals
  25841. for (n = 0; n < ln; n++) {
  25842. normals[n] = -normals[n];
  25843. }
  25844. break;
  25845. case BABYLON.Mesh.DOUBLESIDE:
  25846. // positions
  25847. var lp = positions.length;
  25848. var l = lp / 3;
  25849. for (var p = 0; p < lp; p++) {
  25850. positions[lp + p] = positions[p];
  25851. }
  25852. // indices
  25853. for (i = 0; i < li; i += 3) {
  25854. indices[i + li] = indices[i + 2] + l;
  25855. indices[i + 1 + li] = indices[i + 1] + l;
  25856. indices[i + 2 + li] = indices[i] + l;
  25857. }
  25858. // normals
  25859. for (n = 0; n < ln; n++) {
  25860. normals[ln + n] = -normals[n];
  25861. }
  25862. // uvs
  25863. var lu = uvs.length;
  25864. for (var u = 0; u < lu; u++) {
  25865. uvs[u + lu] = uvs[u];
  25866. }
  25867. break;
  25868. }
  25869. };
  25870. return VertexData;
  25871. })();
  25872. BABYLON.VertexData = VertexData;
  25873. })(BABYLON || (BABYLON = {}));
  25874. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25875. var BABYLON;
  25876. (function (BABYLON) {
  25877. var AnaglyphPostProcess = (function (_super) {
  25878. __extends(AnaglyphPostProcess, _super);
  25879. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25880. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  25881. }
  25882. return AnaglyphPostProcess;
  25883. })(BABYLON.PostProcess);
  25884. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  25885. })(BABYLON || (BABYLON = {}));
  25886. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  25887. var BABYLON;
  25888. (function (BABYLON) {
  25889. var Tags = (function () {
  25890. function Tags() {
  25891. }
  25892. Tags.EnableFor = function (obj) {
  25893. obj._tags = obj._tags || {};
  25894. obj.hasTags = function () {
  25895. return Tags.HasTags(obj);
  25896. };
  25897. obj.addTags = function (tagsString) {
  25898. return Tags.AddTagsTo(obj, tagsString);
  25899. };
  25900. obj.removeTags = function (tagsString) {
  25901. return Tags.RemoveTagsFrom(obj, tagsString);
  25902. };
  25903. obj.matchesTagsQuery = function (tagsQuery) {
  25904. return Tags.MatchesQuery(obj, tagsQuery);
  25905. };
  25906. };
  25907. Tags.DisableFor = function (obj) {
  25908. delete obj._tags;
  25909. delete obj.hasTags;
  25910. delete obj.addTags;
  25911. delete obj.removeTags;
  25912. delete obj.matchesTagsQuery;
  25913. };
  25914. Tags.HasTags = function (obj) {
  25915. if (!obj._tags) {
  25916. return false;
  25917. }
  25918. return !BABYLON.Tools.IsEmpty(obj._tags);
  25919. };
  25920. Tags.GetTags = function (obj) {
  25921. if (!obj._tags) {
  25922. return null;
  25923. }
  25924. return obj._tags;
  25925. };
  25926. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25927. // a tag cannot start with '||', '&&', and '!'
  25928. // it cannot contain whitespaces
  25929. Tags.AddTagsTo = function (obj, tagsString) {
  25930. if (!tagsString) {
  25931. return;
  25932. }
  25933. var tags = tagsString.split(" ");
  25934. for (var t in tags) {
  25935. Tags._AddTagTo(obj, tags[t]);
  25936. }
  25937. };
  25938. Tags._AddTagTo = function (obj, tag) {
  25939. tag = tag.trim();
  25940. if (tag === "" || tag === "true" || tag === "false") {
  25941. return;
  25942. }
  25943. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25944. return;
  25945. }
  25946. Tags.EnableFor(obj);
  25947. obj._tags[tag] = true;
  25948. };
  25949. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25950. if (!Tags.HasTags(obj)) {
  25951. return;
  25952. }
  25953. var tags = tagsString.split(" ");
  25954. for (var t in tags) {
  25955. Tags._RemoveTagFrom(obj, tags[t]);
  25956. }
  25957. };
  25958. Tags._RemoveTagFrom = function (obj, tag) {
  25959. delete obj._tags[tag];
  25960. };
  25961. Tags.MatchesQuery = function (obj, tagsQuery) {
  25962. if (tagsQuery === undefined) {
  25963. return true;
  25964. }
  25965. if (tagsQuery === "") {
  25966. return Tags.HasTags(obj);
  25967. }
  25968. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25969. };
  25970. return Tags;
  25971. })();
  25972. BABYLON.Tags = Tags;
  25973. })(BABYLON || (BABYLON = {}));
  25974. //# sourceMappingURL=babylon.tags.js.map
  25975. var BABYLON;
  25976. (function (BABYLON) {
  25977. var Internals;
  25978. (function (Internals) {
  25979. var AndOrNotEvaluator = (function () {
  25980. function AndOrNotEvaluator() {
  25981. }
  25982. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25983. if (!query.match(/\([^\(\)]*\)/g)) {
  25984. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25985. }
  25986. else {
  25987. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25988. // remove parenthesis
  25989. r = r.slice(1, r.length - 1);
  25990. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25991. });
  25992. }
  25993. if (query === "true") {
  25994. return true;
  25995. }
  25996. if (query === "false") {
  25997. return false;
  25998. }
  25999. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  26000. };
  26001. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  26002. evaluateCallback = evaluateCallback || (function (r) {
  26003. return r === "true" ? true : false;
  26004. });
  26005. var result;
  26006. var or = parenthesisContent.split("||");
  26007. for (var i in or) {
  26008. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  26009. var and = ori.split("&&");
  26010. if (and.length > 1) {
  26011. for (var j = 0; j < and.length; ++j) {
  26012. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  26013. if (andj !== "true" && andj !== "false") {
  26014. if (andj[0] === "!") {
  26015. result = !evaluateCallback(andj.substring(1));
  26016. }
  26017. else {
  26018. result = evaluateCallback(andj);
  26019. }
  26020. }
  26021. else {
  26022. result = andj === "true" ? true : false;
  26023. }
  26024. if (!result) {
  26025. ori = "false";
  26026. break;
  26027. }
  26028. }
  26029. }
  26030. if (result || ori === "true") {
  26031. result = true;
  26032. break;
  26033. }
  26034. // result equals false (or undefined)
  26035. if (ori !== "true" && ori !== "false") {
  26036. if (ori[0] === "!") {
  26037. result = !evaluateCallback(ori.substring(1));
  26038. }
  26039. else {
  26040. result = evaluateCallback(ori);
  26041. }
  26042. }
  26043. else {
  26044. result = ori === "true" ? true : false;
  26045. }
  26046. }
  26047. // the whole parenthesis scope is replaced by 'true' or 'false'
  26048. return result ? "true" : "false";
  26049. };
  26050. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26051. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26052. // remove whitespaces
  26053. r = r.replace(/[\s]/g, function () { return ""; });
  26054. return r.length % 2 ? "!" : "";
  26055. });
  26056. booleanString = booleanString.trim();
  26057. if (booleanString === "!true") {
  26058. booleanString = "false";
  26059. }
  26060. else if (booleanString === "!false") {
  26061. booleanString = "true";
  26062. }
  26063. return booleanString;
  26064. };
  26065. return AndOrNotEvaluator;
  26066. })();
  26067. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26068. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26069. })(BABYLON || (BABYLON = {}));
  26070. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  26071. var BABYLON;
  26072. (function (BABYLON) {
  26073. var PostProcessRenderPass = (function () {
  26074. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26075. this._enabled = true;
  26076. this._refCount = 0;
  26077. this._name = name;
  26078. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26079. this.setRenderList(renderList);
  26080. this._renderTexture.onBeforeRender = beforeRender;
  26081. this._renderTexture.onAfterRender = afterRender;
  26082. this._scene = scene;
  26083. this._renderList = renderList;
  26084. }
  26085. // private
  26086. PostProcessRenderPass.prototype._incRefCount = function () {
  26087. if (this._refCount === 0) {
  26088. this._scene.customRenderTargets.push(this._renderTexture);
  26089. }
  26090. return ++this._refCount;
  26091. };
  26092. PostProcessRenderPass.prototype._decRefCount = function () {
  26093. this._refCount--;
  26094. if (this._refCount <= 0) {
  26095. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26096. }
  26097. return this._refCount;
  26098. };
  26099. PostProcessRenderPass.prototype._update = function () {
  26100. this.setRenderList(this._renderList);
  26101. };
  26102. // public
  26103. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26104. this._renderTexture.renderList = renderList;
  26105. };
  26106. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26107. return this._renderTexture;
  26108. };
  26109. return PostProcessRenderPass;
  26110. })();
  26111. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26112. })(BABYLON || (BABYLON = {}));
  26113. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  26114. var BABYLON;
  26115. (function (BABYLON) {
  26116. var PostProcessRenderEffect = (function () {
  26117. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26118. this._engine = engine;
  26119. this._name = name;
  26120. this._singleInstance = singleInstance || true;
  26121. this._getPostProcess = getPostProcess;
  26122. this._cameras = [];
  26123. this._indicesForCamera = [];
  26124. this._postProcesses = {};
  26125. this._renderPasses = {};
  26126. this._renderEffectAsPasses = {};
  26127. }
  26128. PostProcessRenderEffect.prototype._update = function () {
  26129. for (var renderPassName in this._renderPasses) {
  26130. this._renderPasses[renderPassName]._update();
  26131. }
  26132. };
  26133. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26134. this._renderPasses[renderPass._name] = renderPass;
  26135. this._linkParameters();
  26136. };
  26137. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26138. delete this._renderPasses[renderPass._name];
  26139. this._linkParameters();
  26140. };
  26141. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26142. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26143. this._linkParameters();
  26144. };
  26145. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26146. for (var renderPassName in this._renderPasses) {
  26147. if (renderPassName === passName) {
  26148. return this._renderPasses[passName];
  26149. }
  26150. }
  26151. };
  26152. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26153. this._renderPasses = {};
  26154. this._linkParameters();
  26155. };
  26156. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26157. var cameraKey;
  26158. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26159. for (var i = 0; i < _cam.length; i++) {
  26160. var camera = _cam[i];
  26161. var cameraName = camera.name;
  26162. if (this._singleInstance) {
  26163. cameraKey = 0;
  26164. }
  26165. else {
  26166. cameraKey = cameraName;
  26167. }
  26168. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26169. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26170. if (!this._indicesForCamera[cameraName]) {
  26171. this._indicesForCamera[cameraName] = [];
  26172. }
  26173. this._indicesForCamera[cameraName].push(index);
  26174. if (this._cameras.indexOf(camera) === -1) {
  26175. this._cameras[cameraName] = camera;
  26176. }
  26177. for (var passName in this._renderPasses) {
  26178. this._renderPasses[passName]._incRefCount();
  26179. }
  26180. }
  26181. this._linkParameters();
  26182. };
  26183. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26184. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26185. for (var i = 0; i < _cam.length; i++) {
  26186. var camera = _cam[i];
  26187. var cameraName = camera.name;
  26188. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26189. var index = this._cameras.indexOf(cameraName);
  26190. this._indicesForCamera.splice(index, 1);
  26191. this._cameras.splice(index, 1);
  26192. for (var passName in this._renderPasses) {
  26193. this._renderPasses[passName]._decRefCount();
  26194. }
  26195. }
  26196. };
  26197. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26198. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26199. for (var i = 0; i < _cam.length; i++) {
  26200. var camera = _cam[i];
  26201. var cameraName = camera.name;
  26202. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26203. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26204. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26205. }
  26206. }
  26207. for (var passName in this._renderPasses) {
  26208. this._renderPasses[passName]._incRefCount();
  26209. }
  26210. }
  26211. };
  26212. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26213. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26214. for (var i = 0; i < _cam.length; i++) {
  26215. var camera = _cam[i];
  26216. var cameraName = camera.Name;
  26217. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26218. for (var passName in this._renderPasses) {
  26219. this._renderPasses[passName]._decRefCount();
  26220. }
  26221. }
  26222. };
  26223. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26224. if (this._singleInstance) {
  26225. return this._postProcesses[0];
  26226. }
  26227. else {
  26228. return this._postProcesses[camera.name];
  26229. }
  26230. };
  26231. PostProcessRenderEffect.prototype._linkParameters = function () {
  26232. var _this = this;
  26233. for (var index in this._postProcesses) {
  26234. if (this.applyParameters) {
  26235. this.applyParameters(this._postProcesses[index]);
  26236. }
  26237. this._postProcesses[index].onBeforeRender = function (effect) {
  26238. _this._linkTextures(effect);
  26239. };
  26240. }
  26241. };
  26242. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26243. for (var renderPassName in this._renderPasses) {
  26244. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26245. }
  26246. for (var renderEffectName in this._renderEffectAsPasses) {
  26247. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26248. }
  26249. };
  26250. return PostProcessRenderEffect;
  26251. })();
  26252. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26253. })(BABYLON || (BABYLON = {}));
  26254. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  26255. var BABYLON;
  26256. (function (BABYLON) {
  26257. var PostProcessRenderPipeline = (function () {
  26258. function PostProcessRenderPipeline(engine, name) {
  26259. this._engine = engine;
  26260. this._name = name;
  26261. this._renderEffects = {};
  26262. this._renderEffectsForIsolatedPass = {};
  26263. this._cameras = [];
  26264. }
  26265. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26266. this._renderEffects[renderEffect._name] = renderEffect;
  26267. };
  26268. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26269. var renderEffects = this._renderEffects[renderEffectName];
  26270. if (!renderEffects) {
  26271. return;
  26272. }
  26273. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26274. };
  26275. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26276. var renderEffects = this._renderEffects[renderEffectName];
  26277. if (!renderEffects) {
  26278. return;
  26279. }
  26280. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26281. };
  26282. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26283. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26284. var indicesToDelete = [];
  26285. for (var i = 0; i < _cam.length; i++) {
  26286. var camera = _cam[i];
  26287. var cameraName = camera.name;
  26288. if (this._cameras.indexOf(camera) === -1) {
  26289. this._cameras[cameraName] = camera;
  26290. }
  26291. else if (unique) {
  26292. indicesToDelete.push(i);
  26293. }
  26294. }
  26295. for (var i = 0; i < indicesToDelete.length; i++) {
  26296. cameras.splice(indicesToDelete[i], 1);
  26297. }
  26298. for (var renderEffectName in this._renderEffects) {
  26299. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26300. }
  26301. };
  26302. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26303. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26304. for (var renderEffectName in this._renderEffects) {
  26305. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26306. }
  26307. for (var i = 0; i < _cam.length; i++) {
  26308. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26309. }
  26310. };
  26311. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26312. var _this = this;
  26313. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26314. var pass = null;
  26315. for (var renderEffectName in this._renderEffects) {
  26316. pass = this._renderEffects[renderEffectName].getPass(passName);
  26317. if (pass != null) {
  26318. break;
  26319. }
  26320. }
  26321. if (pass === null) {
  26322. return;
  26323. }
  26324. for (var renderEffectName in this._renderEffects) {
  26325. this._renderEffects[renderEffectName]._disable(_cam);
  26326. }
  26327. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26328. for (var i = 0; i < _cam.length; i++) {
  26329. var camera = _cam[i];
  26330. var cameraName = camera.name;
  26331. 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); });
  26332. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26333. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26334. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26335. }
  26336. };
  26337. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26338. var _this = this;
  26339. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26340. for (var i = 0; i < _cam.length; i++) {
  26341. var camera = _cam[i];
  26342. var cameraName = camera.name;
  26343. 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); });
  26344. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26345. }
  26346. for (var renderEffectName in this._renderEffects) {
  26347. this._renderEffects[renderEffectName]._enable(_cam);
  26348. }
  26349. };
  26350. PostProcessRenderPipeline.prototype._update = function () {
  26351. for (var renderEffectName in this._renderEffects) {
  26352. this._renderEffects[renderEffectName]._update();
  26353. }
  26354. for (var i = 0; i < this._cameras.length; i++) {
  26355. var cameraName = this._cameras[i].name;
  26356. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26357. this._renderEffectsForIsolatedPass[cameraName]._update();
  26358. }
  26359. }
  26360. };
  26361. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26362. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26363. return PostProcessRenderPipeline;
  26364. })();
  26365. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26366. })(BABYLON || (BABYLON = {}));
  26367. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  26368. var BABYLON;
  26369. (function (BABYLON) {
  26370. var PostProcessRenderPipelineManager = (function () {
  26371. function PostProcessRenderPipelineManager() {
  26372. this._renderPipelines = {};
  26373. }
  26374. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26375. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26376. };
  26377. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26378. var renderPipeline = this._renderPipelines[renderPipelineName];
  26379. if (!renderPipeline) {
  26380. return;
  26381. }
  26382. renderPipeline._attachCameras(cameras, unique);
  26383. };
  26384. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26385. var renderPipeline = this._renderPipelines[renderPipelineName];
  26386. if (!renderPipeline) {
  26387. return;
  26388. }
  26389. renderPipeline._detachCameras(cameras);
  26390. };
  26391. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26392. var renderPipeline = this._renderPipelines[renderPipelineName];
  26393. if (!renderPipeline) {
  26394. return;
  26395. }
  26396. renderPipeline._enableEffect(renderEffectName, cameras);
  26397. };
  26398. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26399. var renderPipeline = this._renderPipelines[renderPipelineName];
  26400. if (!renderPipeline) {
  26401. return;
  26402. }
  26403. renderPipeline._disableEffect(renderEffectName, cameras);
  26404. };
  26405. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26406. var renderPipeline = this._renderPipelines[renderPipelineName];
  26407. if (!renderPipeline) {
  26408. return;
  26409. }
  26410. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26411. };
  26412. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26413. var renderPipeline = this._renderPipelines[renderPipelineName];
  26414. if (!renderPipeline) {
  26415. return;
  26416. }
  26417. renderPipeline._disableDisplayOnlyPass(cameras);
  26418. };
  26419. PostProcessRenderPipelineManager.prototype.update = function () {
  26420. for (var renderPipelineName in this._renderPipelines) {
  26421. this._renderPipelines[renderPipelineName]._update();
  26422. }
  26423. };
  26424. return PostProcessRenderPipelineManager;
  26425. })();
  26426. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26427. })(BABYLON || (BABYLON = {}));
  26428. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  26429. var BABYLON;
  26430. (function (BABYLON) {
  26431. var DisplayPassPostProcess = (function (_super) {
  26432. __extends(DisplayPassPostProcess, _super);
  26433. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26434. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  26435. }
  26436. return DisplayPassPostProcess;
  26437. })(BABYLON.PostProcess);
  26438. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  26439. })(BABYLON || (BABYLON = {}));
  26440. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  26441. var BABYLON;
  26442. (function (BABYLON) {
  26443. var BoundingBoxRenderer = (function () {
  26444. function BoundingBoxRenderer(scene) {
  26445. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26446. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26447. this.showBackLines = true;
  26448. this.renderList = new BABYLON.SmartArray(32);
  26449. this._scene = scene;
  26450. }
  26451. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26452. if (this._colorShader) {
  26453. return;
  26454. }
  26455. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26456. attributes: ["position"],
  26457. uniforms: ["worldViewProjection", "color"]
  26458. });
  26459. var engine = this._scene.getEngine();
  26460. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26461. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26462. 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]);
  26463. };
  26464. BoundingBoxRenderer.prototype.reset = function () {
  26465. this.renderList.reset();
  26466. };
  26467. BoundingBoxRenderer.prototype.render = function () {
  26468. if (this.renderList.length === 0) {
  26469. return;
  26470. }
  26471. this._prepareRessources();
  26472. if (!this._colorShader.isReady()) {
  26473. return;
  26474. }
  26475. var engine = this._scene.getEngine();
  26476. engine.setDepthWrite(false);
  26477. this._colorShader._preBind();
  26478. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26479. var boundingBox = this.renderList.data[boundingBoxIndex];
  26480. var min = boundingBox.minimum;
  26481. var max = boundingBox.maximum;
  26482. var diff = max.subtract(min);
  26483. var median = min.add(diff.scale(0.5));
  26484. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26485. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26486. .multiply(boundingBox.getWorldMatrix());
  26487. // VBOs
  26488. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26489. if (this.showBackLines) {
  26490. // Back
  26491. engine.setDepthFunctionToGreaterOrEqual();
  26492. this._scene.resetCachedMaterial();
  26493. this._colorShader.setColor4("color", this.backColor.toColor4());
  26494. this._colorShader.bind(worldMatrix);
  26495. // Draw order
  26496. engine.draw(false, 0, 24);
  26497. }
  26498. // Front
  26499. engine.setDepthFunctionToLess();
  26500. this._scene.resetCachedMaterial();
  26501. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26502. this._colorShader.bind(worldMatrix);
  26503. // Draw order
  26504. engine.draw(false, 0, 24);
  26505. }
  26506. this._colorShader.unbind();
  26507. engine.setDepthFunctionToLessOrEqual();
  26508. engine.setDepthWrite(true);
  26509. };
  26510. BoundingBoxRenderer.prototype.dispose = function () {
  26511. if (!this._colorShader) {
  26512. return;
  26513. }
  26514. this._colorShader.dispose();
  26515. this._vb.dispose();
  26516. this._scene.getEngine()._releaseBuffer(this._ib);
  26517. };
  26518. return BoundingBoxRenderer;
  26519. })();
  26520. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26521. })(BABYLON || (BABYLON = {}));
  26522. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  26523. var BABYLON;
  26524. (function (BABYLON) {
  26525. var Condition = (function () {
  26526. function Condition(actionManager) {
  26527. this._actionManager = actionManager;
  26528. }
  26529. Condition.prototype.isValid = function () {
  26530. return true;
  26531. };
  26532. Condition.prototype._getProperty = function (propertyPath) {
  26533. return this._actionManager._getProperty(propertyPath);
  26534. };
  26535. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26536. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26537. };
  26538. return Condition;
  26539. })();
  26540. BABYLON.Condition = Condition;
  26541. var ValueCondition = (function (_super) {
  26542. __extends(ValueCondition, _super);
  26543. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26544. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26545. _super.call(this, actionManager);
  26546. this.propertyPath = propertyPath;
  26547. this.value = value;
  26548. this.operator = operator;
  26549. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26550. this._property = this._getProperty(this.propertyPath);
  26551. }
  26552. Object.defineProperty(ValueCondition, "IsEqual", {
  26553. get: function () {
  26554. return ValueCondition._IsEqual;
  26555. },
  26556. enumerable: true,
  26557. configurable: true
  26558. });
  26559. Object.defineProperty(ValueCondition, "IsDifferent", {
  26560. get: function () {
  26561. return ValueCondition._IsDifferent;
  26562. },
  26563. enumerable: true,
  26564. configurable: true
  26565. });
  26566. Object.defineProperty(ValueCondition, "IsGreater", {
  26567. get: function () {
  26568. return ValueCondition._IsGreater;
  26569. },
  26570. enumerable: true,
  26571. configurable: true
  26572. });
  26573. Object.defineProperty(ValueCondition, "IsLesser", {
  26574. get: function () {
  26575. return ValueCondition._IsLesser;
  26576. },
  26577. enumerable: true,
  26578. configurable: true
  26579. });
  26580. // Methods
  26581. ValueCondition.prototype.isValid = function () {
  26582. switch (this.operator) {
  26583. case ValueCondition.IsGreater:
  26584. return this._target[this._property] > this.value;
  26585. case ValueCondition.IsLesser:
  26586. return this._target[this._property] < this.value;
  26587. case ValueCondition.IsEqual:
  26588. case ValueCondition.IsDifferent:
  26589. var check;
  26590. if (this.value.equals) {
  26591. check = this.value.equals(this._target[this._property]);
  26592. }
  26593. else {
  26594. check = this.value === this._target[this._property];
  26595. }
  26596. return this.operator === ValueCondition.IsEqual ? check : !check;
  26597. }
  26598. return false;
  26599. };
  26600. // Statics
  26601. ValueCondition._IsEqual = 0;
  26602. ValueCondition._IsDifferent = 1;
  26603. ValueCondition._IsGreater = 2;
  26604. ValueCondition._IsLesser = 3;
  26605. return ValueCondition;
  26606. })(Condition);
  26607. BABYLON.ValueCondition = ValueCondition;
  26608. var PredicateCondition = (function (_super) {
  26609. __extends(PredicateCondition, _super);
  26610. function PredicateCondition(actionManager, predicate) {
  26611. _super.call(this, actionManager);
  26612. this.predicate = predicate;
  26613. }
  26614. PredicateCondition.prototype.isValid = function () {
  26615. return this.predicate();
  26616. };
  26617. return PredicateCondition;
  26618. })(Condition);
  26619. BABYLON.PredicateCondition = PredicateCondition;
  26620. var StateCondition = (function (_super) {
  26621. __extends(StateCondition, _super);
  26622. function StateCondition(actionManager, target, value) {
  26623. _super.call(this, actionManager);
  26624. this.value = value;
  26625. this._target = target;
  26626. }
  26627. // Methods
  26628. StateCondition.prototype.isValid = function () {
  26629. return this._target.state === this.value;
  26630. };
  26631. return StateCondition;
  26632. })(Condition);
  26633. BABYLON.StateCondition = StateCondition;
  26634. })(BABYLON || (BABYLON = {}));
  26635. //# sourceMappingURL=babylon.condition.js.map
  26636. var BABYLON;
  26637. (function (BABYLON) {
  26638. var Action = (function () {
  26639. function Action(triggerOptions, condition) {
  26640. this.triggerOptions = triggerOptions;
  26641. if (triggerOptions.parameter) {
  26642. this.trigger = triggerOptions.trigger;
  26643. this._triggerParameter = triggerOptions.parameter;
  26644. }
  26645. else {
  26646. this.trigger = triggerOptions;
  26647. }
  26648. this._nextActiveAction = this;
  26649. this._condition = condition;
  26650. }
  26651. // Methods
  26652. Action.prototype._prepare = function () {
  26653. };
  26654. Action.prototype.getTriggerParameter = function () {
  26655. return this._triggerParameter;
  26656. };
  26657. Action.prototype._executeCurrent = function (evt) {
  26658. if (this._nextActiveAction._condition) {
  26659. var condition = this._nextActiveAction._condition;
  26660. var currentRenderId = this._actionManager.getScene().getRenderId();
  26661. // We cache the current evaluation for the current frame
  26662. if (condition._evaluationId === currentRenderId) {
  26663. if (!condition._currentResult) {
  26664. return;
  26665. }
  26666. }
  26667. else {
  26668. condition._evaluationId = currentRenderId;
  26669. if (!condition.isValid()) {
  26670. condition._currentResult = false;
  26671. return;
  26672. }
  26673. condition._currentResult = true;
  26674. }
  26675. }
  26676. this._nextActiveAction.execute(evt);
  26677. if (this._nextActiveAction._child) {
  26678. if (!this._nextActiveAction._child._actionManager) {
  26679. this._nextActiveAction._child._actionManager = this._actionManager;
  26680. }
  26681. this._nextActiveAction = this._nextActiveAction._child;
  26682. }
  26683. else {
  26684. this._nextActiveAction = this;
  26685. }
  26686. };
  26687. Action.prototype.execute = function (evt) {
  26688. };
  26689. Action.prototype.then = function (action) {
  26690. this._child = action;
  26691. action._actionManager = this._actionManager;
  26692. action._prepare();
  26693. return action;
  26694. };
  26695. Action.prototype._getProperty = function (propertyPath) {
  26696. return this._actionManager._getProperty(propertyPath);
  26697. };
  26698. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26699. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26700. };
  26701. return Action;
  26702. })();
  26703. BABYLON.Action = Action;
  26704. })(BABYLON || (BABYLON = {}));
  26705. //# sourceMappingURL=babylon.action.js.map
  26706. var BABYLON;
  26707. (function (BABYLON) {
  26708. /**
  26709. * ActionEvent is the event beint sent when an action is triggered.
  26710. */
  26711. var ActionEvent = (function () {
  26712. /**
  26713. * @constructor
  26714. * @param source The mesh that triggered the action.
  26715. * @param pointerX the X mouse cursor position at the time of the event
  26716. * @param pointerY the Y mouse cursor position at the time of the event
  26717. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26718. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26719. */
  26720. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  26721. this.source = source;
  26722. this.pointerX = pointerX;
  26723. this.pointerY = pointerY;
  26724. this.meshUnderPointer = meshUnderPointer;
  26725. this.sourceEvent = sourceEvent;
  26726. }
  26727. /**
  26728. * Helper function to auto-create an ActionEvent from a source mesh.
  26729. * @param source the source mesh that triggered the event
  26730. * @param evt {Event} The original (browser) event
  26731. */
  26732. ActionEvent.CreateNew = function (source, evt) {
  26733. var scene = source.getScene();
  26734. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26735. };
  26736. /**
  26737. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26738. * @param scene the scene where the event occurred
  26739. * @param evt {Event} The original (browser) event
  26740. */
  26741. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26742. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26743. };
  26744. return ActionEvent;
  26745. })();
  26746. BABYLON.ActionEvent = ActionEvent;
  26747. /**
  26748. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26749. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26750. */
  26751. var ActionManager = (function () {
  26752. function ActionManager(scene) {
  26753. // Members
  26754. this.actions = new Array();
  26755. this._scene = scene;
  26756. scene._actionManagers.push(this);
  26757. }
  26758. Object.defineProperty(ActionManager, "NothingTrigger", {
  26759. get: function () {
  26760. return ActionManager._NothingTrigger;
  26761. },
  26762. enumerable: true,
  26763. configurable: true
  26764. });
  26765. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26766. get: function () {
  26767. return ActionManager._OnPickTrigger;
  26768. },
  26769. enumerable: true,
  26770. configurable: true
  26771. });
  26772. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26773. get: function () {
  26774. return ActionManager._OnLeftPickTrigger;
  26775. },
  26776. enumerable: true,
  26777. configurable: true
  26778. });
  26779. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26780. get: function () {
  26781. return ActionManager._OnRightPickTrigger;
  26782. },
  26783. enumerable: true,
  26784. configurable: true
  26785. });
  26786. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26787. get: function () {
  26788. return ActionManager._OnCenterPickTrigger;
  26789. },
  26790. enumerable: true,
  26791. configurable: true
  26792. });
  26793. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26794. get: function () {
  26795. return ActionManager._OnPointerOverTrigger;
  26796. },
  26797. enumerable: true,
  26798. configurable: true
  26799. });
  26800. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26801. get: function () {
  26802. return ActionManager._OnPointerOutTrigger;
  26803. },
  26804. enumerable: true,
  26805. configurable: true
  26806. });
  26807. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26808. get: function () {
  26809. return ActionManager._OnEveryFrameTrigger;
  26810. },
  26811. enumerable: true,
  26812. configurable: true
  26813. });
  26814. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26815. get: function () {
  26816. return ActionManager._OnIntersectionEnterTrigger;
  26817. },
  26818. enumerable: true,
  26819. configurable: true
  26820. });
  26821. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26822. get: function () {
  26823. return ActionManager._OnIntersectionExitTrigger;
  26824. },
  26825. enumerable: true,
  26826. configurable: true
  26827. });
  26828. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26829. get: function () {
  26830. return ActionManager._OnKeyDownTrigger;
  26831. },
  26832. enumerable: true,
  26833. configurable: true
  26834. });
  26835. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26836. get: function () {
  26837. return ActionManager._OnKeyUpTrigger;
  26838. },
  26839. enumerable: true,
  26840. configurable: true
  26841. });
  26842. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26843. get: function () {
  26844. return ActionManager._OnPickUpTrigger;
  26845. },
  26846. enumerable: true,
  26847. configurable: true
  26848. });
  26849. // Methods
  26850. ActionManager.prototype.dispose = function () {
  26851. var index = this._scene._actionManagers.indexOf(this);
  26852. if (index > -1) {
  26853. this._scene._actionManagers.splice(index, 1);
  26854. }
  26855. };
  26856. ActionManager.prototype.getScene = function () {
  26857. return this._scene;
  26858. };
  26859. /**
  26860. * Does this action manager handles actions of any of the given triggers
  26861. * @param {number[]} triggers - the triggers to be tested
  26862. * @return {boolean} whether one (or more) of the triggers is handeled
  26863. */
  26864. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26865. for (var index = 0; index < this.actions.length; index++) {
  26866. var action = this.actions[index];
  26867. if (triggers.indexOf(action.trigger) > -1) {
  26868. return true;
  26869. }
  26870. }
  26871. return false;
  26872. };
  26873. /**
  26874. * Does this action manager handles actions of a given trigger
  26875. * @param {number} trigger - the trigger to be tested
  26876. * @return {boolean} whether the trigger is handeled
  26877. */
  26878. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26879. for (var index = 0; index < this.actions.length; index++) {
  26880. var action = this.actions[index];
  26881. if (action.trigger === trigger) {
  26882. return true;
  26883. }
  26884. }
  26885. return false;
  26886. };
  26887. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26888. /**
  26889. * Does this action manager has pointer triggers
  26890. * @return {boolean} whether or not it has pointer triggers
  26891. */
  26892. get: function () {
  26893. for (var index = 0; index < this.actions.length; index++) {
  26894. var action = this.actions[index];
  26895. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26896. return true;
  26897. }
  26898. if (action.trigger == ActionManager._OnPickUpTrigger) {
  26899. return true;
  26900. }
  26901. }
  26902. return false;
  26903. },
  26904. enumerable: true,
  26905. configurable: true
  26906. });
  26907. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26908. /**
  26909. * Does this action manager has pick triggers
  26910. * @return {boolean} whether or not it has pick triggers
  26911. */
  26912. get: function () {
  26913. for (var index = 0; index < this.actions.length; index++) {
  26914. var action = this.actions[index];
  26915. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  26916. return true;
  26917. }
  26918. }
  26919. return false;
  26920. },
  26921. enumerable: true,
  26922. configurable: true
  26923. });
  26924. /**
  26925. * Registers an action to this action manager
  26926. * @param {BABYLON.Action} action - the action to be registered
  26927. * @return {BABYLON.Action} the action amended (prepared) after registration
  26928. */
  26929. ActionManager.prototype.registerAction = function (action) {
  26930. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26931. if (this.getScene().actionManager !== this) {
  26932. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26933. return null;
  26934. }
  26935. }
  26936. this.actions.push(action);
  26937. action._actionManager = this;
  26938. action._prepare();
  26939. return action;
  26940. };
  26941. /**
  26942. * Process a specific trigger
  26943. * @param {number} trigger - the trigger to process
  26944. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26945. */
  26946. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26947. for (var index = 0; index < this.actions.length; index++) {
  26948. var action = this.actions[index];
  26949. if (action.trigger === trigger) {
  26950. if (trigger === ActionManager.OnKeyUpTrigger
  26951. || trigger === ActionManager.OnKeyDownTrigger) {
  26952. var parameter = action.getTriggerParameter();
  26953. if (parameter) {
  26954. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26955. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26956. if (actualkey !== parameter.toLowerCase()) {
  26957. continue;
  26958. }
  26959. }
  26960. }
  26961. action._executeCurrent(evt);
  26962. }
  26963. }
  26964. };
  26965. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26966. var properties = propertyPath.split(".");
  26967. for (var index = 0; index < properties.length - 1; index++) {
  26968. target = target[properties[index]];
  26969. }
  26970. return target;
  26971. };
  26972. ActionManager.prototype._getProperty = function (propertyPath) {
  26973. var properties = propertyPath.split(".");
  26974. return properties[properties.length - 1];
  26975. };
  26976. // Statics
  26977. ActionManager._NothingTrigger = 0;
  26978. ActionManager._OnPickTrigger = 1;
  26979. ActionManager._OnLeftPickTrigger = 2;
  26980. ActionManager._OnRightPickTrigger = 3;
  26981. ActionManager._OnCenterPickTrigger = 4;
  26982. ActionManager._OnPointerOverTrigger = 5;
  26983. ActionManager._OnPointerOutTrigger = 6;
  26984. ActionManager._OnEveryFrameTrigger = 7;
  26985. ActionManager._OnIntersectionEnterTrigger = 8;
  26986. ActionManager._OnIntersectionExitTrigger = 9;
  26987. ActionManager._OnKeyDownTrigger = 10;
  26988. ActionManager._OnKeyUpTrigger = 11;
  26989. ActionManager._OnPickUpTrigger = 12;
  26990. return ActionManager;
  26991. })();
  26992. BABYLON.ActionManager = ActionManager;
  26993. })(BABYLON || (BABYLON = {}));
  26994. //# sourceMappingURL=babylon.actionManager.js.map
  26995. var BABYLON;
  26996. (function (BABYLON) {
  26997. var InterpolateValueAction = (function (_super) {
  26998. __extends(InterpolateValueAction, _super);
  26999. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  27000. if (duration === void 0) { duration = 1000; }
  27001. _super.call(this, triggerOptions, condition);
  27002. this.propertyPath = propertyPath;
  27003. this.value = value;
  27004. this.duration = duration;
  27005. this.stopOtherAnimations = stopOtherAnimations;
  27006. this._target = target;
  27007. }
  27008. InterpolateValueAction.prototype._prepare = function () {
  27009. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27010. this._property = this._getProperty(this.propertyPath);
  27011. };
  27012. InterpolateValueAction.prototype.execute = function () {
  27013. var scene = this._actionManager.getScene();
  27014. var keys = [
  27015. {
  27016. frame: 0,
  27017. value: this._target[this._property]
  27018. }, {
  27019. frame: 100,
  27020. value: this.value
  27021. }
  27022. ];
  27023. var dataType;
  27024. if (typeof this.value === "number") {
  27025. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27026. }
  27027. else if (this.value instanceof BABYLON.Color3) {
  27028. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27029. }
  27030. else if (this.value instanceof BABYLON.Vector3) {
  27031. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27032. }
  27033. else if (this.value instanceof BABYLON.Matrix) {
  27034. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27035. }
  27036. else if (this.value instanceof BABYLON.Quaternion) {
  27037. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27038. }
  27039. else {
  27040. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27041. return;
  27042. }
  27043. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27044. animation.setKeys(keys);
  27045. if (this.stopOtherAnimations) {
  27046. scene.stopAnimation(this._target);
  27047. }
  27048. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  27049. };
  27050. return InterpolateValueAction;
  27051. })(BABYLON.Action);
  27052. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27053. })(BABYLON || (BABYLON = {}));
  27054. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  27055. var BABYLON;
  27056. (function (BABYLON) {
  27057. var SwitchBooleanAction = (function (_super) {
  27058. __extends(SwitchBooleanAction, _super);
  27059. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27060. _super.call(this, triggerOptions, condition);
  27061. this.propertyPath = propertyPath;
  27062. this._target = target;
  27063. }
  27064. SwitchBooleanAction.prototype._prepare = function () {
  27065. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27066. this._property = this._getProperty(this.propertyPath);
  27067. };
  27068. SwitchBooleanAction.prototype.execute = function () {
  27069. this._target[this._property] = !this._target[this._property];
  27070. };
  27071. return SwitchBooleanAction;
  27072. })(BABYLON.Action);
  27073. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27074. var SetStateAction = (function (_super) {
  27075. __extends(SetStateAction, _super);
  27076. function SetStateAction(triggerOptions, target, value, condition) {
  27077. _super.call(this, triggerOptions, condition);
  27078. this.value = value;
  27079. this._target = target;
  27080. }
  27081. SetStateAction.prototype.execute = function () {
  27082. this._target.state = this.value;
  27083. };
  27084. return SetStateAction;
  27085. })(BABYLON.Action);
  27086. BABYLON.SetStateAction = SetStateAction;
  27087. var SetValueAction = (function (_super) {
  27088. __extends(SetValueAction, _super);
  27089. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27090. _super.call(this, triggerOptions, condition);
  27091. this.propertyPath = propertyPath;
  27092. this.value = value;
  27093. this._target = target;
  27094. }
  27095. SetValueAction.prototype._prepare = function () {
  27096. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27097. this._property = this._getProperty(this.propertyPath);
  27098. };
  27099. SetValueAction.prototype.execute = function () {
  27100. this._target[this._property] = this.value;
  27101. };
  27102. return SetValueAction;
  27103. })(BABYLON.Action);
  27104. BABYLON.SetValueAction = SetValueAction;
  27105. var IncrementValueAction = (function (_super) {
  27106. __extends(IncrementValueAction, _super);
  27107. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27108. _super.call(this, triggerOptions, condition);
  27109. this.propertyPath = propertyPath;
  27110. this.value = value;
  27111. this._target = target;
  27112. }
  27113. IncrementValueAction.prototype._prepare = function () {
  27114. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27115. this._property = this._getProperty(this.propertyPath);
  27116. if (typeof this._target[this._property] !== "number") {
  27117. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27118. }
  27119. };
  27120. IncrementValueAction.prototype.execute = function () {
  27121. this._target[this._property] += this.value;
  27122. };
  27123. return IncrementValueAction;
  27124. })(BABYLON.Action);
  27125. BABYLON.IncrementValueAction = IncrementValueAction;
  27126. var PlayAnimationAction = (function (_super) {
  27127. __extends(PlayAnimationAction, _super);
  27128. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27129. _super.call(this, triggerOptions, condition);
  27130. this.from = from;
  27131. this.to = to;
  27132. this.loop = loop;
  27133. this._target = target;
  27134. }
  27135. PlayAnimationAction.prototype._prepare = function () {
  27136. };
  27137. PlayAnimationAction.prototype.execute = function () {
  27138. var scene = this._actionManager.getScene();
  27139. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27140. };
  27141. return PlayAnimationAction;
  27142. })(BABYLON.Action);
  27143. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27144. var StopAnimationAction = (function (_super) {
  27145. __extends(StopAnimationAction, _super);
  27146. function StopAnimationAction(triggerOptions, target, condition) {
  27147. _super.call(this, triggerOptions, condition);
  27148. this._target = target;
  27149. }
  27150. StopAnimationAction.prototype._prepare = function () {
  27151. };
  27152. StopAnimationAction.prototype.execute = function () {
  27153. var scene = this._actionManager.getScene();
  27154. scene.stopAnimation(this._target);
  27155. };
  27156. return StopAnimationAction;
  27157. })(BABYLON.Action);
  27158. BABYLON.StopAnimationAction = StopAnimationAction;
  27159. var DoNothingAction = (function (_super) {
  27160. __extends(DoNothingAction, _super);
  27161. function DoNothingAction(triggerOptions, condition) {
  27162. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27163. _super.call(this, triggerOptions, condition);
  27164. }
  27165. DoNothingAction.prototype.execute = function () {
  27166. };
  27167. return DoNothingAction;
  27168. })(BABYLON.Action);
  27169. BABYLON.DoNothingAction = DoNothingAction;
  27170. var CombineAction = (function (_super) {
  27171. __extends(CombineAction, _super);
  27172. function CombineAction(triggerOptions, children, condition) {
  27173. _super.call(this, triggerOptions, condition);
  27174. this.children = children;
  27175. }
  27176. CombineAction.prototype._prepare = function () {
  27177. for (var index = 0; index < this.children.length; index++) {
  27178. this.children[index]._actionManager = this._actionManager;
  27179. this.children[index]._prepare();
  27180. }
  27181. };
  27182. CombineAction.prototype.execute = function (evt) {
  27183. for (var index = 0; index < this.children.length; index++) {
  27184. this.children[index].execute(evt);
  27185. }
  27186. };
  27187. return CombineAction;
  27188. })(BABYLON.Action);
  27189. BABYLON.CombineAction = CombineAction;
  27190. var ExecuteCodeAction = (function (_super) {
  27191. __extends(ExecuteCodeAction, _super);
  27192. function ExecuteCodeAction(triggerOptions, func, condition) {
  27193. _super.call(this, triggerOptions, condition);
  27194. this.func = func;
  27195. }
  27196. ExecuteCodeAction.prototype.execute = function (evt) {
  27197. this.func(evt);
  27198. };
  27199. return ExecuteCodeAction;
  27200. })(BABYLON.Action);
  27201. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27202. var SetParentAction = (function (_super) {
  27203. __extends(SetParentAction, _super);
  27204. function SetParentAction(triggerOptions, target, parent, condition) {
  27205. _super.call(this, triggerOptions, condition);
  27206. this._target = target;
  27207. this._parent = parent;
  27208. }
  27209. SetParentAction.prototype._prepare = function () {
  27210. };
  27211. SetParentAction.prototype.execute = function () {
  27212. if (this._target.parent === this._parent) {
  27213. return;
  27214. }
  27215. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27216. invertParentWorldMatrix.invert();
  27217. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27218. this._target.parent = this._parent;
  27219. };
  27220. return SetParentAction;
  27221. })(BABYLON.Action);
  27222. BABYLON.SetParentAction = SetParentAction;
  27223. var PlaySoundAction = (function (_super) {
  27224. __extends(PlaySoundAction, _super);
  27225. function PlaySoundAction(triggerOptions, sound, condition) {
  27226. _super.call(this, triggerOptions, condition);
  27227. this._sound = sound;
  27228. }
  27229. PlaySoundAction.prototype._prepare = function () {
  27230. };
  27231. PlaySoundAction.prototype.execute = function () {
  27232. if (this._sound !== undefined)
  27233. this._sound.play();
  27234. };
  27235. return PlaySoundAction;
  27236. })(BABYLON.Action);
  27237. BABYLON.PlaySoundAction = PlaySoundAction;
  27238. var StopSoundAction = (function (_super) {
  27239. __extends(StopSoundAction, _super);
  27240. function StopSoundAction(triggerOptions, sound, condition) {
  27241. _super.call(this, triggerOptions, condition);
  27242. this._sound = sound;
  27243. }
  27244. StopSoundAction.prototype._prepare = function () {
  27245. };
  27246. StopSoundAction.prototype.execute = function () {
  27247. if (this._sound !== undefined)
  27248. this._sound.stop();
  27249. };
  27250. return StopSoundAction;
  27251. })(BABYLON.Action);
  27252. BABYLON.StopSoundAction = StopSoundAction;
  27253. })(BABYLON || (BABYLON = {}));
  27254. //# sourceMappingURL=babylon.directActions.js.map
  27255. var BABYLON;
  27256. (function (BABYLON) {
  27257. var Geometry = (function () {
  27258. function Geometry(id, scene, vertexData, updatable, mesh) {
  27259. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27260. this._totalVertices = 0;
  27261. this._indices = [];
  27262. this._isDisposed = false;
  27263. this.id = id;
  27264. this._engine = scene.getEngine();
  27265. this._meshes = [];
  27266. this._scene = scene;
  27267. // vertexData
  27268. if (vertexData) {
  27269. this.setAllVerticesData(vertexData, updatable);
  27270. }
  27271. else {
  27272. this._totalVertices = 0;
  27273. this._indices = [];
  27274. }
  27275. // applyToMesh
  27276. if (mesh) {
  27277. this.applyToMesh(mesh);
  27278. mesh.computeWorldMatrix(true);
  27279. }
  27280. }
  27281. Geometry.prototype.getScene = function () {
  27282. return this._scene;
  27283. };
  27284. Geometry.prototype.getEngine = function () {
  27285. return this._engine;
  27286. };
  27287. Geometry.prototype.isReady = function () {
  27288. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27289. };
  27290. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27291. vertexData.applyToGeometry(this, updatable);
  27292. this.notifyUpdate();
  27293. };
  27294. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27295. this._vertexBuffers = this._vertexBuffers || {};
  27296. if (this._vertexBuffers[kind]) {
  27297. this._vertexBuffers[kind].dispose();
  27298. }
  27299. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27300. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27301. stride = this._vertexBuffers[kind].getStrideSize();
  27302. this._totalVertices = data.length / stride;
  27303. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27304. var meshes = this._meshes;
  27305. var numOfMeshes = meshes.length;
  27306. for (var index = 0; index < numOfMeshes; index++) {
  27307. var mesh = meshes[index];
  27308. mesh._resetPointsArrayCache();
  27309. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27310. mesh._createGlobalSubMesh();
  27311. mesh.computeWorldMatrix(true);
  27312. }
  27313. }
  27314. this.notifyUpdate(kind);
  27315. };
  27316. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27317. var vertexBuffer = this.getVertexBuffer(kind);
  27318. if (!vertexBuffer) {
  27319. return;
  27320. }
  27321. vertexBuffer.updateDirectly(data, offset);
  27322. this.notifyUpdate(kind);
  27323. };
  27324. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27325. var vertexBuffer = this.getVertexBuffer(kind);
  27326. if (!vertexBuffer) {
  27327. return;
  27328. }
  27329. vertexBuffer.update(data);
  27330. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27331. var extend;
  27332. var stride = vertexBuffer.getStrideSize();
  27333. this._totalVertices = data.length / stride;
  27334. if (updateExtends) {
  27335. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27336. }
  27337. var meshes = this._meshes;
  27338. var numOfMeshes = meshes.length;
  27339. for (var index = 0; index < numOfMeshes; index++) {
  27340. var mesh = meshes[index];
  27341. mesh._resetPointsArrayCache();
  27342. if (updateExtends) {
  27343. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27344. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27345. var subMesh = mesh.subMeshes[subIndex];
  27346. subMesh.refreshBoundingInfo();
  27347. }
  27348. }
  27349. }
  27350. }
  27351. this.notifyUpdate(kind);
  27352. };
  27353. Geometry.prototype.getTotalVertices = function () {
  27354. if (!this.isReady()) {
  27355. return 0;
  27356. }
  27357. return this._totalVertices;
  27358. };
  27359. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27360. var vertexBuffer = this.getVertexBuffer(kind);
  27361. if (!vertexBuffer) {
  27362. return null;
  27363. }
  27364. var orig = vertexBuffer.getData();
  27365. if (!copyWhenShared || this._meshes.length === 1) {
  27366. return orig;
  27367. }
  27368. else {
  27369. var len = orig.length;
  27370. var copy = [];
  27371. for (var i = 0; i < len; i++) {
  27372. copy.push(orig[i]);
  27373. }
  27374. return copy;
  27375. }
  27376. };
  27377. Geometry.prototype.getVertexBuffer = function (kind) {
  27378. if (!this.isReady()) {
  27379. return null;
  27380. }
  27381. return this._vertexBuffers[kind];
  27382. };
  27383. Geometry.prototype.getVertexBuffers = function () {
  27384. if (!this.isReady()) {
  27385. return null;
  27386. }
  27387. return this._vertexBuffers;
  27388. };
  27389. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27390. if (!this._vertexBuffers) {
  27391. if (this._delayInfo) {
  27392. return this._delayInfo.indexOf(kind) !== -1;
  27393. }
  27394. return false;
  27395. }
  27396. return this._vertexBuffers[kind] !== undefined;
  27397. };
  27398. Geometry.prototype.getVerticesDataKinds = function () {
  27399. var result = [];
  27400. if (!this._vertexBuffers && this._delayInfo) {
  27401. for (var kind in this._delayInfo) {
  27402. result.push(kind);
  27403. }
  27404. }
  27405. else {
  27406. for (kind in this._vertexBuffers) {
  27407. result.push(kind);
  27408. }
  27409. }
  27410. return result;
  27411. };
  27412. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27413. if (this._indexBuffer) {
  27414. this._engine._releaseBuffer(this._indexBuffer);
  27415. }
  27416. this._indices = indices;
  27417. if (this._meshes.length !== 0 && this._indices) {
  27418. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27419. }
  27420. if (totalVertices !== undefined) {
  27421. this._totalVertices = totalVertices;
  27422. }
  27423. var meshes = this._meshes;
  27424. var numOfMeshes = meshes.length;
  27425. for (var index = 0; index < numOfMeshes; index++) {
  27426. meshes[index]._createGlobalSubMesh();
  27427. }
  27428. this.notifyUpdate();
  27429. };
  27430. Geometry.prototype.getTotalIndices = function () {
  27431. if (!this.isReady()) {
  27432. return 0;
  27433. }
  27434. return this._indices.length;
  27435. };
  27436. Geometry.prototype.getIndices = function (copyWhenShared) {
  27437. if (!this.isReady()) {
  27438. return null;
  27439. }
  27440. var orig = this._indices;
  27441. if (!copyWhenShared || this._meshes.length === 1) {
  27442. return orig;
  27443. }
  27444. else {
  27445. var len = orig.length;
  27446. var copy = [];
  27447. for (var i = 0; i < len; i++) {
  27448. copy.push(orig[i]);
  27449. }
  27450. return copy;
  27451. }
  27452. };
  27453. Geometry.prototype.getIndexBuffer = function () {
  27454. if (!this.isReady()) {
  27455. return null;
  27456. }
  27457. return this._indexBuffer;
  27458. };
  27459. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27460. var meshes = this._meshes;
  27461. var index = meshes.indexOf(mesh);
  27462. if (index === -1) {
  27463. return;
  27464. }
  27465. for (var kind in this._vertexBuffers) {
  27466. this._vertexBuffers[kind].dispose();
  27467. }
  27468. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27469. this._indexBuffer = null;
  27470. }
  27471. meshes.splice(index, 1);
  27472. mesh._geometry = null;
  27473. if (meshes.length === 0 && shouldDispose) {
  27474. this.dispose();
  27475. }
  27476. };
  27477. Geometry.prototype.applyToMesh = function (mesh) {
  27478. if (mesh._geometry === this) {
  27479. return;
  27480. }
  27481. var previousGeometry = mesh._geometry;
  27482. if (previousGeometry) {
  27483. previousGeometry.releaseForMesh(mesh);
  27484. }
  27485. var meshes = this._meshes;
  27486. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27487. mesh._geometry = this;
  27488. this._scene.pushGeometry(this);
  27489. meshes.push(mesh);
  27490. if (this.isReady()) {
  27491. this._applyToMesh(mesh);
  27492. }
  27493. else {
  27494. mesh._boundingInfo = this._boundingInfo;
  27495. }
  27496. };
  27497. Geometry.prototype._applyToMesh = function (mesh) {
  27498. var numOfMeshes = this._meshes.length;
  27499. // vertexBuffers
  27500. for (var kind in this._vertexBuffers) {
  27501. if (numOfMeshes === 1) {
  27502. this._vertexBuffers[kind].create();
  27503. }
  27504. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27505. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27506. mesh._resetPointsArrayCache();
  27507. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27508. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27509. mesh._createGlobalSubMesh();
  27510. //bounding info was just created again, world matrix should be applied again.
  27511. mesh._updateBoundingInfo();
  27512. }
  27513. }
  27514. // indexBuffer
  27515. if (numOfMeshes === 1 && this._indices) {
  27516. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27517. }
  27518. if (this._indexBuffer) {
  27519. this._indexBuffer.references = numOfMeshes;
  27520. }
  27521. };
  27522. Geometry.prototype.notifyUpdate = function (kind) {
  27523. if (this.onGeometryUpdated) {
  27524. this.onGeometryUpdated(this, kind);
  27525. }
  27526. };
  27527. Geometry.prototype.load = function (scene, onLoaded) {
  27528. var _this = this;
  27529. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27530. return;
  27531. }
  27532. if (this.isReady()) {
  27533. if (onLoaded) {
  27534. onLoaded();
  27535. }
  27536. return;
  27537. }
  27538. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27539. scene._addPendingData(this);
  27540. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27541. _this._delayLoadingFunction(JSON.parse(data), _this);
  27542. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27543. _this._delayInfo = [];
  27544. scene._removePendingData(_this);
  27545. var meshes = _this._meshes;
  27546. var numOfMeshes = meshes.length;
  27547. for (var index = 0; index < numOfMeshes; index++) {
  27548. _this._applyToMesh(meshes[index]);
  27549. }
  27550. if (onLoaded) {
  27551. onLoaded();
  27552. }
  27553. }, function () { }, scene.database);
  27554. };
  27555. Geometry.prototype.isDisposed = function () {
  27556. return this._isDisposed;
  27557. };
  27558. Geometry.prototype.dispose = function () {
  27559. var meshes = this._meshes;
  27560. var numOfMeshes = meshes.length;
  27561. var index;
  27562. for (index = 0; index < numOfMeshes; index++) {
  27563. this.releaseForMesh(meshes[index]);
  27564. }
  27565. this._meshes = [];
  27566. for (var kind in this._vertexBuffers) {
  27567. this._vertexBuffers[kind].dispose();
  27568. }
  27569. this._vertexBuffers = [];
  27570. this._totalVertices = 0;
  27571. if (this._indexBuffer) {
  27572. this._engine._releaseBuffer(this._indexBuffer);
  27573. }
  27574. this._indexBuffer = null;
  27575. this._indices = [];
  27576. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27577. this.delayLoadingFile = null;
  27578. this._delayLoadingFunction = null;
  27579. this._delayInfo = [];
  27580. this._boundingInfo = null; // todo: .dispose()
  27581. this._scene.removeGeometry(this);
  27582. this._isDisposed = true;
  27583. };
  27584. Geometry.prototype.copy = function (id) {
  27585. var vertexData = new BABYLON.VertexData();
  27586. vertexData.indices = [];
  27587. var indices = this.getIndices();
  27588. for (var index = 0; index < indices.length; index++) {
  27589. vertexData.indices.push(indices[index]);
  27590. }
  27591. var updatable = false;
  27592. var stopChecking = false;
  27593. for (var kind in this._vertexBuffers) {
  27594. // using slice() to make a copy of the array and not just reference it
  27595. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  27596. if (!stopChecking) {
  27597. updatable = this.getVertexBuffer(kind).isUpdatable();
  27598. stopChecking = !updatable;
  27599. }
  27600. }
  27601. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27602. geometry.delayLoadState = this.delayLoadState;
  27603. geometry.delayLoadingFile = this.delayLoadingFile;
  27604. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27605. for (kind in this._delayInfo) {
  27606. geometry._delayInfo = geometry._delayInfo || [];
  27607. geometry._delayInfo.push(kind);
  27608. }
  27609. // Bounding info
  27610. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  27611. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27612. return geometry;
  27613. };
  27614. // Statics
  27615. Geometry.ExtractFromMesh = function (mesh, id) {
  27616. var geometry = mesh._geometry;
  27617. if (!geometry) {
  27618. return null;
  27619. }
  27620. return geometry.copy(id);
  27621. };
  27622. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27623. // be aware Math.random() could cause collisions
  27624. Geometry.RandomId = function () {
  27625. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27626. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27627. return v.toString(16);
  27628. });
  27629. };
  27630. return Geometry;
  27631. })();
  27632. BABYLON.Geometry = Geometry;
  27633. /////// Primitives //////////////////////////////////////////////
  27634. var Geometry;
  27635. (function (Geometry) {
  27636. var Primitives;
  27637. (function (Primitives) {
  27638. /// Abstract class
  27639. var _Primitive = (function (_super) {
  27640. __extends(_Primitive, _super);
  27641. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27642. this._beingRegenerated = true;
  27643. this._canBeRegenerated = canBeRegenerated;
  27644. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27645. this._beingRegenerated = false;
  27646. }
  27647. _Primitive.prototype.canBeRegenerated = function () {
  27648. return this._canBeRegenerated;
  27649. };
  27650. _Primitive.prototype.regenerate = function () {
  27651. if (!this._canBeRegenerated) {
  27652. return;
  27653. }
  27654. this._beingRegenerated = true;
  27655. this.setAllVerticesData(this._regenerateVertexData(), false);
  27656. this._beingRegenerated = false;
  27657. };
  27658. _Primitive.prototype.asNewGeometry = function (id) {
  27659. return _super.prototype.copy.call(this, id);
  27660. };
  27661. // overrides
  27662. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27663. if (!this._beingRegenerated) {
  27664. return;
  27665. }
  27666. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27667. };
  27668. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27669. if (!this._beingRegenerated) {
  27670. return;
  27671. }
  27672. _super.prototype.setVerticesData.call(this, kind, data, false);
  27673. };
  27674. // to override
  27675. // protected
  27676. _Primitive.prototype._regenerateVertexData = function () {
  27677. throw new Error("Abstract method");
  27678. };
  27679. _Primitive.prototype.copy = function (id) {
  27680. throw new Error("Must be overriden in sub-classes.");
  27681. };
  27682. return _Primitive;
  27683. })(Geometry);
  27684. Primitives._Primitive = _Primitive;
  27685. var Ribbon = (function (_super) {
  27686. __extends(Ribbon, _super);
  27687. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27688. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27689. this.pathArray = pathArray;
  27690. this.closeArray = closeArray;
  27691. this.closePath = closePath;
  27692. this.offset = offset;
  27693. this.side = side;
  27694. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27695. }
  27696. Ribbon.prototype._regenerateVertexData = function () {
  27697. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  27698. };
  27699. Ribbon.prototype.copy = function (id) {
  27700. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27701. };
  27702. return Ribbon;
  27703. })(_Primitive);
  27704. Primitives.Ribbon = Ribbon;
  27705. var Box = (function (_super) {
  27706. __extends(Box, _super);
  27707. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27708. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27709. this.size = size;
  27710. this.side = side;
  27711. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27712. }
  27713. Box.prototype._regenerateVertexData = function () {
  27714. return BABYLON.VertexData.CreateBox(this.size, this.side);
  27715. };
  27716. Box.prototype.copy = function (id) {
  27717. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27718. };
  27719. return Box;
  27720. })(_Primitive);
  27721. Primitives.Box = Box;
  27722. var Sphere = (function (_super) {
  27723. __extends(Sphere, _super);
  27724. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27725. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27726. this.segments = segments;
  27727. this.diameter = diameter;
  27728. this.side = side;
  27729. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27730. }
  27731. Sphere.prototype._regenerateVertexData = function () {
  27732. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  27733. };
  27734. Sphere.prototype.copy = function (id) {
  27735. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27736. };
  27737. return Sphere;
  27738. })(_Primitive);
  27739. Primitives.Sphere = Sphere;
  27740. var Cylinder = (function (_super) {
  27741. __extends(Cylinder, _super);
  27742. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27743. if (subdivisions === void 0) { subdivisions = 1; }
  27744. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27745. this.height = height;
  27746. this.diameterTop = diameterTop;
  27747. this.diameterBottom = diameterBottom;
  27748. this.tessellation = tessellation;
  27749. this.subdivisions = subdivisions;
  27750. this.side = side;
  27751. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27752. }
  27753. Cylinder.prototype._regenerateVertexData = function () {
  27754. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  27755. };
  27756. Cylinder.prototype.copy = function (id) {
  27757. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27758. };
  27759. return Cylinder;
  27760. })(_Primitive);
  27761. Primitives.Cylinder = Cylinder;
  27762. var Torus = (function (_super) {
  27763. __extends(Torus, _super);
  27764. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27765. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27766. this.diameter = diameter;
  27767. this.thickness = thickness;
  27768. this.tessellation = tessellation;
  27769. this.side = side;
  27770. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27771. }
  27772. Torus.prototype._regenerateVertexData = function () {
  27773. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  27774. };
  27775. Torus.prototype.copy = function (id) {
  27776. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27777. };
  27778. return Torus;
  27779. })(_Primitive);
  27780. Primitives.Torus = Torus;
  27781. var Ground = (function (_super) {
  27782. __extends(Ground, _super);
  27783. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27784. this.width = width;
  27785. this.height = height;
  27786. this.subdivisions = subdivisions;
  27787. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27788. }
  27789. Ground.prototype._regenerateVertexData = function () {
  27790. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  27791. };
  27792. Ground.prototype.copy = function (id) {
  27793. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27794. };
  27795. return Ground;
  27796. })(_Primitive);
  27797. Primitives.Ground = Ground;
  27798. var TiledGround = (function (_super) {
  27799. __extends(TiledGround, _super);
  27800. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27801. this.xmin = xmin;
  27802. this.zmin = zmin;
  27803. this.xmax = xmax;
  27804. this.zmax = zmax;
  27805. this.subdivisions = subdivisions;
  27806. this.precision = precision;
  27807. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27808. }
  27809. TiledGround.prototype._regenerateVertexData = function () {
  27810. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  27811. };
  27812. TiledGround.prototype.copy = function (id) {
  27813. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27814. };
  27815. return TiledGround;
  27816. })(_Primitive);
  27817. Primitives.TiledGround = TiledGround;
  27818. var Plane = (function (_super) {
  27819. __extends(Plane, _super);
  27820. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27821. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27822. this.size = size;
  27823. this.side = side;
  27824. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27825. }
  27826. Plane.prototype._regenerateVertexData = function () {
  27827. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  27828. };
  27829. Plane.prototype.copy = function (id) {
  27830. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27831. };
  27832. return Plane;
  27833. })(_Primitive);
  27834. Primitives.Plane = Plane;
  27835. var TorusKnot = (function (_super) {
  27836. __extends(TorusKnot, _super);
  27837. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27838. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27839. this.radius = radius;
  27840. this.tube = tube;
  27841. this.radialSegments = radialSegments;
  27842. this.tubularSegments = tubularSegments;
  27843. this.p = p;
  27844. this.q = q;
  27845. this.side = side;
  27846. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27847. }
  27848. TorusKnot.prototype._regenerateVertexData = function () {
  27849. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  27850. };
  27851. TorusKnot.prototype.copy = function (id) {
  27852. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27853. };
  27854. return TorusKnot;
  27855. })(_Primitive);
  27856. Primitives.TorusKnot = TorusKnot;
  27857. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27858. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27859. })(BABYLON || (BABYLON = {}));
  27860. //# sourceMappingURL=babylon.geometry.js.map
  27861. var BABYLON;
  27862. (function (BABYLON) {
  27863. var GroundMesh = (function (_super) {
  27864. __extends(GroundMesh, _super);
  27865. function GroundMesh(name, scene) {
  27866. _super.call(this, name, scene);
  27867. this.generateOctree = false;
  27868. this._worldInverse = new BABYLON.Matrix();
  27869. }
  27870. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27871. get: function () {
  27872. return this._subdivisions;
  27873. },
  27874. enumerable: true,
  27875. configurable: true
  27876. });
  27877. GroundMesh.prototype.optimize = function (chunksCount) {
  27878. this.subdivide(this._subdivisions);
  27879. this.createOrUpdateSubmeshesOctree(32);
  27880. };
  27881. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27882. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27883. this.getWorldMatrix().invertToRef(this._worldInverse);
  27884. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27885. var pickInfo = this.intersects(ray);
  27886. if (pickInfo.hit) {
  27887. return pickInfo.pickedPoint.y;
  27888. }
  27889. return 0;
  27890. };
  27891. return GroundMesh;
  27892. })(BABYLON.Mesh);
  27893. BABYLON.GroundMesh = GroundMesh;
  27894. })(BABYLON || (BABYLON = {}));
  27895. //# sourceMappingURL=babylon.groundMesh.js.map
  27896. var BABYLON;
  27897. (function (BABYLON) {
  27898. var LinesMesh = (function (_super) {
  27899. __extends(LinesMesh, _super);
  27900. function LinesMesh(name, scene, updatable) {
  27901. if (updatable === void 0) { updatable = false; }
  27902. _super.call(this, name, scene);
  27903. this.color = new BABYLON.Color3(1, 1, 1);
  27904. this.alpha = 1;
  27905. this._indices = new Array();
  27906. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27907. attributes: ["position"],
  27908. uniforms: ["worldViewProjection", "color"],
  27909. needAlphaBlending: true
  27910. });
  27911. }
  27912. Object.defineProperty(LinesMesh.prototype, "material", {
  27913. get: function () {
  27914. return this._colorShader;
  27915. },
  27916. enumerable: true,
  27917. configurable: true
  27918. });
  27919. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27920. get: function () {
  27921. return false;
  27922. },
  27923. enumerable: true,
  27924. configurable: true
  27925. });
  27926. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27927. get: function () {
  27928. return false;
  27929. },
  27930. enumerable: true,
  27931. configurable: true
  27932. });
  27933. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27934. var engine = this.getScene().getEngine();
  27935. var indexToBind = this._geometry.getIndexBuffer();
  27936. // VBOs
  27937. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27938. // Color
  27939. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27940. };
  27941. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27942. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27943. return;
  27944. }
  27945. var engine = this.getScene().getEngine();
  27946. // Draw order
  27947. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27948. };
  27949. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27950. return null;
  27951. };
  27952. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27953. this._colorShader.dispose();
  27954. _super.prototype.dispose.call(this, doNotRecurse);
  27955. };
  27956. return LinesMesh;
  27957. })(BABYLON.Mesh);
  27958. BABYLON.LinesMesh = LinesMesh;
  27959. })(BABYLON || (BABYLON = {}));
  27960. //# sourceMappingURL=babylon.linesMesh.js.map
  27961. var BABYLON;
  27962. (function (BABYLON) {
  27963. var OutlineRenderer = (function () {
  27964. function OutlineRenderer(scene) {
  27965. this._scene = scene;
  27966. }
  27967. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27968. var _this = this;
  27969. if (useOverlay === void 0) { useOverlay = false; }
  27970. var scene = this._scene;
  27971. var engine = this._scene.getEngine();
  27972. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27973. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27974. return;
  27975. }
  27976. var mesh = subMesh.getRenderingMesh();
  27977. var material = subMesh.getMaterial();
  27978. engine.enableEffect(this._effect);
  27979. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27980. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27981. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27982. // Bones
  27983. if (mesh.useBones) {
  27984. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27985. }
  27986. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27987. // Alpha test
  27988. if (material && material.needAlphaTesting()) {
  27989. var alphaTexture = material.getAlphaTestTexture();
  27990. this._effect.setTexture("diffuseSampler", alphaTexture);
  27991. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27992. }
  27993. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  27994. };
  27995. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  27996. var defines = [];
  27997. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  27998. var mesh = subMesh.getMesh();
  27999. var material = subMesh.getMaterial();
  28000. // Alpha test
  28001. if (material && material.needAlphaTesting()) {
  28002. defines.push("#define ALPHATEST");
  28003. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28004. attribs.push(BABYLON.VertexBuffer.UVKind);
  28005. defines.push("#define UV1");
  28006. }
  28007. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28008. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28009. defines.push("#define UV2");
  28010. }
  28011. }
  28012. // Bones
  28013. if (mesh.useBones) {
  28014. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28015. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28016. defines.push("#define BONES");
  28017. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28018. }
  28019. // Instances
  28020. if (useInstances) {
  28021. defines.push("#define INSTANCES");
  28022. attribs.push("world0");
  28023. attribs.push("world1");
  28024. attribs.push("world2");
  28025. attribs.push("world3");
  28026. }
  28027. // Get correct effect
  28028. var join = defines.join("\n");
  28029. if (this._cachedDefines !== join) {
  28030. this._cachedDefines = join;
  28031. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  28032. }
  28033. return this._effect.isReady();
  28034. };
  28035. return OutlineRenderer;
  28036. })();
  28037. BABYLON.OutlineRenderer = OutlineRenderer;
  28038. })(BABYLON || (BABYLON = {}));
  28039. //# sourceMappingURL=babylon.outlineRenderer.js.map
  28040. var BABYLON;
  28041. (function (BABYLON) {
  28042. var MeshAssetTask = (function () {
  28043. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  28044. this.name = name;
  28045. this.meshesNames = meshesNames;
  28046. this.rootUrl = rootUrl;
  28047. this.sceneFilename = sceneFilename;
  28048. this.isCompleted = false;
  28049. }
  28050. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28051. var _this = this;
  28052. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  28053. _this.loadedMeshes = meshes;
  28054. _this.loadedParticleSystems = particleSystems;
  28055. _this.loadedSkeletons = skeletons;
  28056. _this.isCompleted = true;
  28057. if (_this.onSuccess) {
  28058. _this.onSuccess(_this);
  28059. }
  28060. onSuccess();
  28061. }, null, function () {
  28062. if (_this.onError) {
  28063. _this.onError(_this);
  28064. }
  28065. onError();
  28066. });
  28067. };
  28068. return MeshAssetTask;
  28069. })();
  28070. BABYLON.MeshAssetTask = MeshAssetTask;
  28071. var TextFileAssetTask = (function () {
  28072. function TextFileAssetTask(name, url) {
  28073. this.name = name;
  28074. this.url = url;
  28075. this.isCompleted = false;
  28076. }
  28077. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28078. var _this = this;
  28079. BABYLON.Tools.LoadFile(this.url, function (data) {
  28080. _this.text = data;
  28081. _this.isCompleted = true;
  28082. if (_this.onSuccess) {
  28083. _this.onSuccess(_this);
  28084. }
  28085. onSuccess();
  28086. }, null, scene.database, false, function () {
  28087. if (_this.onError) {
  28088. _this.onError(_this);
  28089. }
  28090. onError();
  28091. });
  28092. };
  28093. return TextFileAssetTask;
  28094. })();
  28095. BABYLON.TextFileAssetTask = TextFileAssetTask;
  28096. var BinaryFileAssetTask = (function () {
  28097. function BinaryFileAssetTask(name, url) {
  28098. this.name = name;
  28099. this.url = url;
  28100. this.isCompleted = false;
  28101. }
  28102. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28103. var _this = this;
  28104. BABYLON.Tools.LoadFile(this.url, function (data) {
  28105. _this.data = data;
  28106. _this.isCompleted = true;
  28107. if (_this.onSuccess) {
  28108. _this.onSuccess(_this);
  28109. }
  28110. onSuccess();
  28111. }, null, scene.database, true, function () {
  28112. if (_this.onError) {
  28113. _this.onError(_this);
  28114. }
  28115. onError();
  28116. });
  28117. };
  28118. return BinaryFileAssetTask;
  28119. })();
  28120. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  28121. var ImageAssetTask = (function () {
  28122. function ImageAssetTask(name, url) {
  28123. this.name = name;
  28124. this.url = url;
  28125. this.isCompleted = false;
  28126. }
  28127. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28128. var _this = this;
  28129. var img = new Image();
  28130. img.onload = function () {
  28131. _this.image = img;
  28132. _this.isCompleted = true;
  28133. if (_this.onSuccess) {
  28134. _this.onSuccess(_this);
  28135. }
  28136. onSuccess();
  28137. };
  28138. img.onerror = function () {
  28139. if (_this.onError) {
  28140. _this.onError(_this);
  28141. }
  28142. onError();
  28143. };
  28144. img.src = this.url;
  28145. };
  28146. return ImageAssetTask;
  28147. })();
  28148. BABYLON.ImageAssetTask = ImageAssetTask;
  28149. var TextureAssetTask = (function () {
  28150. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  28151. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28152. this.name = name;
  28153. this.url = url;
  28154. this.noMipmap = noMipmap;
  28155. this.invertY = invertY;
  28156. this.samplingMode = samplingMode;
  28157. this.isCompleted = false;
  28158. }
  28159. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28160. var _this = this;
  28161. var onload = function () {
  28162. _this.isCompleted = true;
  28163. if (_this.onSuccess) {
  28164. _this.onSuccess(_this);
  28165. }
  28166. onSuccess();
  28167. };
  28168. var onerror = function () {
  28169. if (_this.onError) {
  28170. _this.onError(_this);
  28171. }
  28172. onError();
  28173. };
  28174. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  28175. };
  28176. return TextureAssetTask;
  28177. })();
  28178. BABYLON.TextureAssetTask = TextureAssetTask;
  28179. var AssetsManager = (function () {
  28180. function AssetsManager(scene) {
  28181. this._tasks = new Array();
  28182. this._waitingTasksCount = 0;
  28183. this.useDefaultLoadingScreen = true;
  28184. this._scene = scene;
  28185. }
  28186. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  28187. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  28188. this._tasks.push(task);
  28189. return task;
  28190. };
  28191. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  28192. var task = new TextFileAssetTask(taskName, url);
  28193. this._tasks.push(task);
  28194. return task;
  28195. };
  28196. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  28197. var task = new BinaryFileAssetTask(taskName, url);
  28198. this._tasks.push(task);
  28199. return task;
  28200. };
  28201. AssetsManager.prototype.addImageTask = function (taskName, url) {
  28202. var task = new ImageAssetTask(taskName, url);
  28203. this._tasks.push(task);
  28204. return task;
  28205. };
  28206. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  28207. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28208. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  28209. this._tasks.push(task);
  28210. return task;
  28211. };
  28212. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  28213. this._waitingTasksCount--;
  28214. if (this._waitingTasksCount === 0) {
  28215. if (this.onFinish) {
  28216. this.onFinish(this._tasks);
  28217. }
  28218. this._scene.getEngine().hideLoadingUI();
  28219. }
  28220. };
  28221. AssetsManager.prototype._runTask = function (task) {
  28222. var _this = this;
  28223. task.run(this._scene, function () {
  28224. if (_this.onTaskSuccess) {
  28225. _this.onTaskSuccess(task);
  28226. }
  28227. _this._decreaseWaitingTasksCount();
  28228. }, function () {
  28229. if (_this.onTaskError) {
  28230. _this.onTaskError(task);
  28231. }
  28232. _this._decreaseWaitingTasksCount();
  28233. });
  28234. };
  28235. AssetsManager.prototype.reset = function () {
  28236. this._tasks = new Array();
  28237. return this;
  28238. };
  28239. AssetsManager.prototype.load = function () {
  28240. this._waitingTasksCount = this._tasks.length;
  28241. if (this._waitingTasksCount === 0) {
  28242. if (this.onFinish) {
  28243. this.onFinish(this._tasks);
  28244. }
  28245. return this;
  28246. }
  28247. if (this.useDefaultLoadingScreen) {
  28248. this._scene.getEngine().displayLoadingUI();
  28249. }
  28250. for (var index = 0; index < this._tasks.length; index++) {
  28251. var task = this._tasks[index];
  28252. this._runTask(task);
  28253. }
  28254. return this;
  28255. };
  28256. return AssetsManager;
  28257. })();
  28258. BABYLON.AssetsManager = AssetsManager;
  28259. })(BABYLON || (BABYLON = {}));
  28260. //# sourceMappingURL=babylon.assetsManager.js.map
  28261. var BABYLON;
  28262. (function (BABYLON) {
  28263. var VRDeviceOrientationFreeCamera = (function (_super) {
  28264. __extends(VRDeviceOrientationFreeCamera, _super);
  28265. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  28266. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28267. _super.call(this, name, position, scene);
  28268. this._alpha = 0;
  28269. this._beta = 0;
  28270. this._gamma = 0;
  28271. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28272. metrics.compensateDistorsion = compensateDistorsion;
  28273. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  28274. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  28275. }
  28276. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  28277. this._alpha = +evt.alpha | 0;
  28278. this._beta = +evt.beta | 0;
  28279. this._gamma = +evt.gamma | 0;
  28280. if (this._gamma < 0) {
  28281. this._gamma = 90 + this._gamma;
  28282. }
  28283. else {
  28284. // Incline it in the correct angle.
  28285. this._gamma = 270 - this._gamma;
  28286. }
  28287. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28288. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28289. this.rotation.z = this._beta / 180.0 * Math.PI;
  28290. };
  28291. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28292. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28293. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  28294. };
  28295. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  28296. _super.prototype.detachControl.call(this, element);
  28297. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  28298. };
  28299. return VRDeviceOrientationFreeCamera;
  28300. })(BABYLON.FreeCamera);
  28301. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  28302. })(BABYLON || (BABYLON = {}));
  28303. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28304. var BABYLON;
  28305. (function (BABYLON) {
  28306. var WebVRFreeCamera = (function (_super) {
  28307. __extends(WebVRFreeCamera, _super);
  28308. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  28309. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28310. _super.call(this, name, position, scene);
  28311. this._hmdDevice = null;
  28312. this._sensorDevice = null;
  28313. this._cacheState = null;
  28314. this._cacheQuaternion = new BABYLON.Quaternion();
  28315. this._cacheRotation = BABYLON.Vector3.Zero();
  28316. this._vrEnabled = false;
  28317. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28318. metrics.compensateDistorsion = compensateDistorsion;
  28319. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  28320. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28321. }
  28322. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  28323. var size = devices.length;
  28324. var i = 0;
  28325. // Reset devices.
  28326. this._sensorDevice = null;
  28327. this._hmdDevice = null;
  28328. // Search for a HmdDevice.
  28329. while (i < size && this._hmdDevice === null) {
  28330. if (devices[i] instanceof HMDVRDevice) {
  28331. this._hmdDevice = devices[i];
  28332. }
  28333. i++;
  28334. }
  28335. i = 0;
  28336. while (i < size && this._sensorDevice === null) {
  28337. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28338. this._sensorDevice = devices[i];
  28339. }
  28340. i++;
  28341. }
  28342. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28343. };
  28344. WebVRFreeCamera.prototype._checkInputs = function () {
  28345. if (this._vrEnabled) {
  28346. this._cacheState = this._sensorDevice.getState();
  28347. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28348. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28349. this.rotation.x = -this._cacheRotation.z;
  28350. this.rotation.y = -this._cacheRotation.y;
  28351. this.rotation.z = this._cacheRotation.x;
  28352. }
  28353. _super.prototype._checkInputs.call(this);
  28354. };
  28355. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28356. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28357. if (navigator.getVRDevices) {
  28358. navigator.getVRDevices().then(this._getWebVRDevices);
  28359. }
  28360. else if (navigator.mozGetVRDevices) {
  28361. navigator.mozGetVRDevices(this._getWebVRDevices);
  28362. }
  28363. };
  28364. WebVRFreeCamera.prototype.detachControl = function (element) {
  28365. _super.prototype.detachControl.call(this, element);
  28366. this._vrEnabled = false;
  28367. };
  28368. return WebVRFreeCamera;
  28369. })(BABYLON.FreeCamera);
  28370. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  28371. })(BABYLON || (BABYLON = {}));
  28372. //# sourceMappingURL=babylon.webVRCamera.js.map
  28373. var BABYLON;
  28374. (function (BABYLON) {
  28375. // Standard optimizations
  28376. var SceneOptimization = (function () {
  28377. function SceneOptimization(priority) {
  28378. if (priority === void 0) { priority = 0; }
  28379. this.priority = priority;
  28380. this.apply = function (scene) {
  28381. return true; // Return true if everything that can be done was applied
  28382. };
  28383. }
  28384. return SceneOptimization;
  28385. })();
  28386. BABYLON.SceneOptimization = SceneOptimization;
  28387. var TextureOptimization = (function (_super) {
  28388. __extends(TextureOptimization, _super);
  28389. function TextureOptimization(priority, maximumSize) {
  28390. var _this = this;
  28391. if (priority === void 0) { priority = 0; }
  28392. if (maximumSize === void 0) { maximumSize = 1024; }
  28393. _super.call(this, priority);
  28394. this.priority = priority;
  28395. this.maximumSize = maximumSize;
  28396. this.apply = function (scene) {
  28397. var allDone = true;
  28398. for (var index = 0; index < scene.textures.length; index++) {
  28399. var texture = scene.textures[index];
  28400. if (!texture.canRescale) {
  28401. continue;
  28402. }
  28403. var currentSize = texture.getSize();
  28404. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28405. if (maxDimension > _this.maximumSize) {
  28406. texture.scale(0.5);
  28407. allDone = false;
  28408. }
  28409. }
  28410. return allDone;
  28411. };
  28412. }
  28413. return TextureOptimization;
  28414. })(SceneOptimization);
  28415. BABYLON.TextureOptimization = TextureOptimization;
  28416. var HardwareScalingOptimization = (function (_super) {
  28417. __extends(HardwareScalingOptimization, _super);
  28418. function HardwareScalingOptimization(priority, maximumScale) {
  28419. var _this = this;
  28420. if (priority === void 0) { priority = 0; }
  28421. if (maximumScale === void 0) { maximumScale = 2; }
  28422. _super.call(this, priority);
  28423. this.priority = priority;
  28424. this.maximumScale = maximumScale;
  28425. this._currentScale = 1;
  28426. this.apply = function (scene) {
  28427. _this._currentScale++;
  28428. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28429. return _this._currentScale >= _this.maximumScale;
  28430. };
  28431. }
  28432. return HardwareScalingOptimization;
  28433. })(SceneOptimization);
  28434. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28435. var ShadowsOptimization = (function (_super) {
  28436. __extends(ShadowsOptimization, _super);
  28437. function ShadowsOptimization() {
  28438. _super.apply(this, arguments);
  28439. this.apply = function (scene) {
  28440. scene.shadowsEnabled = false;
  28441. return true;
  28442. };
  28443. }
  28444. return ShadowsOptimization;
  28445. })(SceneOptimization);
  28446. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28447. var PostProcessesOptimization = (function (_super) {
  28448. __extends(PostProcessesOptimization, _super);
  28449. function PostProcessesOptimization() {
  28450. _super.apply(this, arguments);
  28451. this.apply = function (scene) {
  28452. scene.postProcessesEnabled = false;
  28453. return true;
  28454. };
  28455. }
  28456. return PostProcessesOptimization;
  28457. })(SceneOptimization);
  28458. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28459. var LensFlaresOptimization = (function (_super) {
  28460. __extends(LensFlaresOptimization, _super);
  28461. function LensFlaresOptimization() {
  28462. _super.apply(this, arguments);
  28463. this.apply = function (scene) {
  28464. scene.lensFlaresEnabled = false;
  28465. return true;
  28466. };
  28467. }
  28468. return LensFlaresOptimization;
  28469. })(SceneOptimization);
  28470. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28471. var ParticlesOptimization = (function (_super) {
  28472. __extends(ParticlesOptimization, _super);
  28473. function ParticlesOptimization() {
  28474. _super.apply(this, arguments);
  28475. this.apply = function (scene) {
  28476. scene.particlesEnabled = false;
  28477. return true;
  28478. };
  28479. }
  28480. return ParticlesOptimization;
  28481. })(SceneOptimization);
  28482. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28483. var RenderTargetsOptimization = (function (_super) {
  28484. __extends(RenderTargetsOptimization, _super);
  28485. function RenderTargetsOptimization() {
  28486. _super.apply(this, arguments);
  28487. this.apply = function (scene) {
  28488. scene.renderTargetsEnabled = false;
  28489. return true;
  28490. };
  28491. }
  28492. return RenderTargetsOptimization;
  28493. })(SceneOptimization);
  28494. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28495. var MergeMeshesOptimization = (function (_super) {
  28496. __extends(MergeMeshesOptimization, _super);
  28497. function MergeMeshesOptimization() {
  28498. var _this = this;
  28499. _super.apply(this, arguments);
  28500. this._canBeMerged = function (abstractMesh) {
  28501. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28502. return false;
  28503. }
  28504. var mesh = abstractMesh;
  28505. if (!mesh.isVisible || !mesh.isEnabled()) {
  28506. return false;
  28507. }
  28508. if (mesh.instances.length > 0) {
  28509. return false;
  28510. }
  28511. if (mesh.skeleton || mesh.hasLODLevels) {
  28512. return false;
  28513. }
  28514. return true;
  28515. };
  28516. this.apply = function (scene) {
  28517. var globalPool = scene.meshes.slice(0);
  28518. var globalLength = globalPool.length;
  28519. for (var index = 0; index < globalLength; index++) {
  28520. var currentPool = new Array();
  28521. var current = globalPool[index];
  28522. // Checks
  28523. if (!_this._canBeMerged(current)) {
  28524. continue;
  28525. }
  28526. currentPool.push(current);
  28527. // Find compatible meshes
  28528. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28529. var otherMesh = globalPool[subIndex];
  28530. if (!_this._canBeMerged(otherMesh)) {
  28531. continue;
  28532. }
  28533. if (otherMesh.material !== current.material) {
  28534. continue;
  28535. }
  28536. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28537. continue;
  28538. }
  28539. currentPool.push(otherMesh);
  28540. globalLength--;
  28541. globalPool.splice(subIndex, 1);
  28542. subIndex--;
  28543. }
  28544. if (currentPool.length < 2) {
  28545. continue;
  28546. }
  28547. // Merge meshes
  28548. BABYLON.Mesh.MergeMeshes(currentPool);
  28549. }
  28550. return true;
  28551. };
  28552. }
  28553. return MergeMeshesOptimization;
  28554. })(SceneOptimization);
  28555. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28556. // Options
  28557. var SceneOptimizerOptions = (function () {
  28558. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28559. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28560. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28561. this.targetFrameRate = targetFrameRate;
  28562. this.trackerDuration = trackerDuration;
  28563. this.optimizations = new Array();
  28564. }
  28565. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28566. var result = new SceneOptimizerOptions(targetFrameRate);
  28567. var priority = 0;
  28568. result.optimizations.push(new MergeMeshesOptimization(priority));
  28569. result.optimizations.push(new ShadowsOptimization(priority));
  28570. result.optimizations.push(new LensFlaresOptimization(priority));
  28571. // Next priority
  28572. priority++;
  28573. result.optimizations.push(new PostProcessesOptimization(priority));
  28574. result.optimizations.push(new ParticlesOptimization(priority));
  28575. // Next priority
  28576. priority++;
  28577. result.optimizations.push(new TextureOptimization(priority, 1024));
  28578. return result;
  28579. };
  28580. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28581. var result = new SceneOptimizerOptions(targetFrameRate);
  28582. var priority = 0;
  28583. result.optimizations.push(new MergeMeshesOptimization(priority));
  28584. result.optimizations.push(new ShadowsOptimization(priority));
  28585. result.optimizations.push(new LensFlaresOptimization(priority));
  28586. // Next priority
  28587. priority++;
  28588. result.optimizations.push(new PostProcessesOptimization(priority));
  28589. result.optimizations.push(new ParticlesOptimization(priority));
  28590. // Next priority
  28591. priority++;
  28592. result.optimizations.push(new TextureOptimization(priority, 512));
  28593. // Next priority
  28594. priority++;
  28595. result.optimizations.push(new RenderTargetsOptimization(priority));
  28596. // Next priority
  28597. priority++;
  28598. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28599. return result;
  28600. };
  28601. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28602. var result = new SceneOptimizerOptions(targetFrameRate);
  28603. var priority = 0;
  28604. result.optimizations.push(new MergeMeshesOptimization(priority));
  28605. result.optimizations.push(new ShadowsOptimization(priority));
  28606. result.optimizations.push(new LensFlaresOptimization(priority));
  28607. // Next priority
  28608. priority++;
  28609. result.optimizations.push(new PostProcessesOptimization(priority));
  28610. result.optimizations.push(new ParticlesOptimization(priority));
  28611. // Next priority
  28612. priority++;
  28613. result.optimizations.push(new TextureOptimization(priority, 256));
  28614. // Next priority
  28615. priority++;
  28616. result.optimizations.push(new RenderTargetsOptimization(priority));
  28617. // Next priority
  28618. priority++;
  28619. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28620. return result;
  28621. };
  28622. return SceneOptimizerOptions;
  28623. })();
  28624. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28625. // Scene optimizer tool
  28626. var SceneOptimizer = (function () {
  28627. function SceneOptimizer() {
  28628. }
  28629. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28630. // TODO: add an epsilon
  28631. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28632. if (onSuccess) {
  28633. onSuccess();
  28634. }
  28635. return;
  28636. }
  28637. // Apply current level of optimizations
  28638. var allDone = true;
  28639. var noOptimizationApplied = true;
  28640. for (var index = 0; index < options.optimizations.length; index++) {
  28641. var optimization = options.optimizations[index];
  28642. if (optimization.priority === currentPriorityLevel) {
  28643. noOptimizationApplied = false;
  28644. allDone = allDone && optimization.apply(scene);
  28645. }
  28646. }
  28647. // If no optimization was applied, this is a failure :(
  28648. if (noOptimizationApplied) {
  28649. if (onFailure) {
  28650. onFailure();
  28651. }
  28652. return;
  28653. }
  28654. // If all optimizations were done, move to next level
  28655. if (allDone) {
  28656. currentPriorityLevel++;
  28657. }
  28658. // Let's the system running for a specific amount of time before checking FPS
  28659. scene.executeWhenReady(function () {
  28660. setTimeout(function () {
  28661. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28662. }, options.trackerDuration);
  28663. });
  28664. };
  28665. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28666. if (!options) {
  28667. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28668. }
  28669. // Let's the system running for a specific amount of time before checking FPS
  28670. scene.executeWhenReady(function () {
  28671. setTimeout(function () {
  28672. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28673. }, options.trackerDuration);
  28674. });
  28675. };
  28676. return SceneOptimizer;
  28677. })();
  28678. BABYLON.SceneOptimizer = SceneOptimizer;
  28679. })(BABYLON || (BABYLON = {}));
  28680. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28681. var BABYLON;
  28682. (function (BABYLON) {
  28683. var Internals;
  28684. (function (Internals) {
  28685. var MeshLODLevel = (function () {
  28686. function MeshLODLevel(distance, mesh) {
  28687. this.distance = distance;
  28688. this.mesh = mesh;
  28689. }
  28690. return MeshLODLevel;
  28691. })();
  28692. Internals.MeshLODLevel = MeshLODLevel;
  28693. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28694. })(BABYLON || (BABYLON = {}));
  28695. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28696. var BABYLON;
  28697. (function (BABYLON) {
  28698. var AudioEngine = (function () {
  28699. function AudioEngine() {
  28700. this._audioContext = null;
  28701. this._audioContextInitialized = false;
  28702. this.canUseWebAudio = false;
  28703. this.WarnedWebAudioUnsupported = false;
  28704. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28705. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28706. this.canUseWebAudio = true;
  28707. }
  28708. }
  28709. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28710. get: function () {
  28711. if (!this._audioContextInitialized) {
  28712. this._initializeAudioContext();
  28713. }
  28714. return this._audioContext;
  28715. },
  28716. enumerable: true,
  28717. configurable: true
  28718. });
  28719. AudioEngine.prototype._initializeAudioContext = function () {
  28720. try {
  28721. if (this.canUseWebAudio) {
  28722. this._audioContext = new AudioContext();
  28723. // create a global volume gain node
  28724. this.masterGain = this._audioContext.createGain();
  28725. this.masterGain.gain.value = 1;
  28726. this.masterGain.connect(this._audioContext.destination);
  28727. this._audioContextInitialized = true;
  28728. }
  28729. }
  28730. catch (e) {
  28731. this.canUseWebAudio = false;
  28732. BABYLON.Tools.Error("Web Audio: " + e.message);
  28733. }
  28734. };
  28735. AudioEngine.prototype.dispose = function () {
  28736. if (this.canUseWebAudio && this._audioContextInitialized) {
  28737. if (this._connectedAnalyser) {
  28738. this._connectedAnalyser.stopDebugCanvas();
  28739. this._connectedAnalyser.dispose();
  28740. this.masterGain.disconnect();
  28741. this.masterGain.connect(this._audioContext.destination);
  28742. this._connectedAnalyser = null;
  28743. }
  28744. this.masterGain.gain.value = 1;
  28745. }
  28746. this.WarnedWebAudioUnsupported = false;
  28747. };
  28748. AudioEngine.prototype.getGlobalVolume = function () {
  28749. if (this.canUseWebAudio && this._audioContextInitialized) {
  28750. return this.masterGain.gain.value;
  28751. }
  28752. else {
  28753. return -1;
  28754. }
  28755. };
  28756. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28757. if (this.canUseWebAudio && this._audioContextInitialized) {
  28758. this.masterGain.gain.value = newVolume;
  28759. }
  28760. };
  28761. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28762. if (this._connectedAnalyser) {
  28763. this._connectedAnalyser.stopDebugCanvas();
  28764. }
  28765. if (this.canUseWebAudio && this._audioContextInitialized) {
  28766. this._connectedAnalyser = analyser;
  28767. this.masterGain.disconnect();
  28768. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28769. }
  28770. };
  28771. return AudioEngine;
  28772. })();
  28773. BABYLON.AudioEngine = AudioEngine;
  28774. })(BABYLON || (BABYLON = {}));
  28775. //# sourceMappingURL=babylon.audioEngine.js.map
  28776. var BABYLON;
  28777. (function (BABYLON) {
  28778. var Sound = (function () {
  28779. /**
  28780. * Create a sound and attach it to a scene
  28781. * @param name Name of your sound
  28782. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28783. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28784. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28785. */
  28786. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28787. var _this = this;
  28788. this.autoplay = false;
  28789. this.loop = false;
  28790. this.useCustomAttenuation = false;
  28791. this.spatialSound = false;
  28792. this.refDistance = 1;
  28793. this.rolloffFactor = 1;
  28794. this.maxDistance = 100;
  28795. this.distanceModel = "linear";
  28796. this._panningModel = "equalpower";
  28797. this._playbackRate = 1;
  28798. this._startTime = 0;
  28799. this._startOffset = 0;
  28800. this._position = BABYLON.Vector3.Zero();
  28801. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28802. this._volume = 1;
  28803. this._isLoaded = false;
  28804. this._isReadyToPlay = false;
  28805. this.isPlaying = false;
  28806. this.isPaused = false;
  28807. this._isDirectional = false;
  28808. // Used if you'd like to create a directional sound.
  28809. // If not set, the sound will be omnidirectional
  28810. this._coneInnerAngle = 360;
  28811. this._coneOuterAngle = 360;
  28812. this._coneOuterGain = 0;
  28813. this.name = name;
  28814. this._scene = scene;
  28815. this._readyToPlayCallback = readyToPlayCallback;
  28816. // Default custom attenuation function is a linear attenuation
  28817. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28818. if (currentDistance < maxDistance) {
  28819. return currentVolume * (1 - currentDistance / maxDistance);
  28820. }
  28821. else {
  28822. return 0;
  28823. }
  28824. };
  28825. if (options) {
  28826. this.autoplay = options.autoplay || false;
  28827. this.loop = options.loop || false;
  28828. // if volume === 0, we need another way to check this option
  28829. if (options.volume !== undefined) {
  28830. this._volume = options.volume;
  28831. }
  28832. this.spatialSound = options.spatialSound || false;
  28833. this.maxDistance = options.maxDistance || 100;
  28834. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28835. this.rolloffFactor = options.rolloffFactor || 1;
  28836. this.refDistance = options.refDistance || 1;
  28837. this.distanceModel = options.distanceModel || "linear";
  28838. this._playbackRate = options.playbackRate || 1;
  28839. }
  28840. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28841. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28842. this._soundGain.gain.value = this._volume;
  28843. this._inputAudioNode = this._soundGain;
  28844. this._ouputAudioNode = this._soundGain;
  28845. if (this.spatialSound) {
  28846. this._createSpatialParameters();
  28847. }
  28848. this._scene.mainSoundTrack.AddSound(this);
  28849. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28850. if (urlOrArrayBuffer) {
  28851. // If it's an URL
  28852. if (typeof (urlOrArrayBuffer) === "string") {
  28853. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  28854. }
  28855. else {
  28856. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28857. this._soundLoaded(urlOrArrayBuffer);
  28858. }
  28859. else {
  28860. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28861. }
  28862. }
  28863. }
  28864. }
  28865. else {
  28866. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28867. this._scene.mainSoundTrack.AddSound(this);
  28868. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28869. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28870. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28871. }
  28872. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28873. if (this._readyToPlayCallback) {
  28874. window.setTimeout(function () {
  28875. _this._readyToPlayCallback();
  28876. }, 1000);
  28877. }
  28878. }
  28879. }
  28880. Sound.prototype.dispose = function () {
  28881. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28882. if (this.isPlaying) {
  28883. this.stop();
  28884. }
  28885. this._isReadyToPlay = false;
  28886. if (this.soundTrackId === -1) {
  28887. this._scene.mainSoundTrack.RemoveSound(this);
  28888. }
  28889. else {
  28890. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28891. }
  28892. if (this._soundGain) {
  28893. this._soundGain.disconnect();
  28894. this._soundGain = null;
  28895. }
  28896. if (this._soundPanner) {
  28897. this._soundPanner.disconnect();
  28898. this._soundPanner = null;
  28899. }
  28900. if (this._soundSource) {
  28901. this._soundSource.disconnect();
  28902. this._soundSource = null;
  28903. }
  28904. this._audioBuffer = null;
  28905. if (this._connectedMesh) {
  28906. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28907. this._connectedMesh = null;
  28908. }
  28909. }
  28910. };
  28911. Sound.prototype._soundLoaded = function (audioData) {
  28912. var _this = this;
  28913. this._isLoaded = true;
  28914. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28915. _this._audioBuffer = buffer;
  28916. _this._isReadyToPlay = true;
  28917. if (_this.autoplay) {
  28918. _this.play();
  28919. }
  28920. if (_this._readyToPlayCallback) {
  28921. _this._readyToPlayCallback();
  28922. }
  28923. }, function (error) { BABYLON.Tools.Error("Error while decoding audio data: " + error.err); });
  28924. };
  28925. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28926. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28927. this._audioBuffer = audioBuffer;
  28928. this._isReadyToPlay = true;
  28929. }
  28930. };
  28931. Sound.prototype.updateOptions = function (options) {
  28932. if (options) {
  28933. this.loop = options.loop || this.loop;
  28934. this.maxDistance = options.maxDistance || this.maxDistance;
  28935. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28936. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28937. this.refDistance = options.refDistance || this.refDistance;
  28938. this.distanceModel = options.distanceModel || this.distanceModel;
  28939. this._playbackRate = options.playbackRate || this._playbackRate;
  28940. this._updateSpatialParameters();
  28941. if (this.isPlaying) {
  28942. this._soundSource.playbackRate.value = this._playbackRate;
  28943. }
  28944. }
  28945. };
  28946. Sound.prototype._createSpatialParameters = function () {
  28947. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28948. if (this._scene.headphone) {
  28949. this._panningModel = "HRTF";
  28950. }
  28951. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28952. this._updateSpatialParameters();
  28953. this._soundPanner.connect(this._ouputAudioNode);
  28954. this._inputAudioNode = this._soundPanner;
  28955. }
  28956. };
  28957. Sound.prototype._updateSpatialParameters = function () {
  28958. if (this.spatialSound) {
  28959. if (this.useCustomAttenuation) {
  28960. // Tricks to disable in a way embedded Web Audio attenuation
  28961. this._soundPanner.distanceModel = "linear";
  28962. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28963. this._soundPanner.refDistance = 1;
  28964. this._soundPanner.rolloffFactor = 1;
  28965. this._soundPanner.panningModel = this._panningModel;
  28966. }
  28967. else {
  28968. this._soundPanner.distanceModel = this.distanceModel;
  28969. this._soundPanner.maxDistance = this.maxDistance;
  28970. this._soundPanner.refDistance = this.refDistance;
  28971. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28972. this._soundPanner.panningModel = this._panningModel;
  28973. }
  28974. }
  28975. };
  28976. Sound.prototype.switchPanningModelToHRTF = function () {
  28977. this._panningModel = "HRTF";
  28978. this._switchPanningModel();
  28979. };
  28980. Sound.prototype.switchPanningModelToEqualPower = function () {
  28981. this._panningModel = "equalpower";
  28982. this._switchPanningModel();
  28983. };
  28984. Sound.prototype._switchPanningModel = function () {
  28985. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28986. this._soundPanner.panningModel = this._panningModel;
  28987. }
  28988. };
  28989. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  28990. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28991. this._ouputAudioNode.disconnect();
  28992. this._ouputAudioNode.connect(soundTrackAudioNode);
  28993. }
  28994. };
  28995. /**
  28996. * Transform this sound into a directional source
  28997. * @param coneInnerAngle Size of the inner cone in degree
  28998. * @param coneOuterAngle Size of the outer cone in degree
  28999. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  29000. */
  29001. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  29002. if (coneOuterAngle < coneInnerAngle) {
  29003. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  29004. return;
  29005. }
  29006. this._coneInnerAngle = coneInnerAngle;
  29007. this._coneOuterAngle = coneOuterAngle;
  29008. this._coneOuterGain = coneOuterGain;
  29009. this._isDirectional = true;
  29010. if (this.isPlaying && this.loop) {
  29011. this.stop();
  29012. this.play();
  29013. }
  29014. };
  29015. Sound.prototype.setPosition = function (newPosition) {
  29016. this._position = newPosition;
  29017. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29018. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29019. }
  29020. };
  29021. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  29022. this._localDirection = newLocalDirection;
  29023. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  29024. this._updateDirection();
  29025. }
  29026. };
  29027. Sound.prototype._updateDirection = function () {
  29028. var mat = this._connectedMesh.getWorldMatrix();
  29029. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  29030. direction.normalize();
  29031. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  29032. };
  29033. Sound.prototype.updateDistanceFromListener = function () {
  29034. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  29035. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  29036. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  29037. }
  29038. };
  29039. Sound.prototype.setAttenuationFunction = function (callback) {
  29040. this._customAttenuationFunction = callback;
  29041. };
  29042. /**
  29043. * Play the sound
  29044. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  29045. */
  29046. Sound.prototype.play = function (time) {
  29047. var _this = this;
  29048. if (this._isReadyToPlay && this._scene.audioEnabled) {
  29049. try {
  29050. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29051. if (!this._soundSource) {
  29052. if (this.spatialSound) {
  29053. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29054. if (this._isDirectional) {
  29055. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  29056. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  29057. this._soundPanner.coneOuterGain = this._coneOuterGain;
  29058. if (this._connectedMesh) {
  29059. this._updateDirection();
  29060. }
  29061. else {
  29062. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  29063. }
  29064. }
  29065. }
  29066. }
  29067. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  29068. this._soundSource.buffer = this._audioBuffer;
  29069. this._soundSource.connect(this._inputAudioNode);
  29070. this._soundSource.loop = this.loop;
  29071. this._soundSource.playbackRate.value = this._playbackRate;
  29072. this._startTime = startTime;
  29073. this._soundSource.onended = function () { _this._onended(); };
  29074. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29075. this.isPlaying = true;
  29076. this.isPaused = false;
  29077. }
  29078. catch (ex) {
  29079. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29080. }
  29081. }
  29082. };
  29083. Sound.prototype._onended = function () {
  29084. this.isPlaying = false;
  29085. if (this.onended) {
  29086. this.onended();
  29087. }
  29088. };
  29089. /**
  29090. * Stop the sound
  29091. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29092. */
  29093. Sound.prototype.stop = function (time) {
  29094. if (this.isPlaying) {
  29095. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29096. this._soundSource.stop(stopTime);
  29097. this.isPlaying = false;
  29098. }
  29099. };
  29100. Sound.prototype.pause = function () {
  29101. if (this.isPlaying) {
  29102. this.stop(0);
  29103. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29104. this.isPaused = true;
  29105. }
  29106. };
  29107. Sound.prototype.setVolume = function (newVolume, time) {
  29108. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29109. if (time) {
  29110. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29111. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  29112. }
  29113. else {
  29114. this._soundGain.gain.value = newVolume;
  29115. }
  29116. }
  29117. this._volume = newVolume;
  29118. };
  29119. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29120. this._playbackRate = newPlaybackRate;
  29121. if (this.isPlaying) {
  29122. this._soundSource.playbackRate.value = this._playbackRate;
  29123. }
  29124. };
  29125. Sound.prototype.getVolume = function () {
  29126. return this._volume;
  29127. };
  29128. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29129. var _this = this;
  29130. this._connectedMesh = meshToConnectTo;
  29131. if (!this.spatialSound) {
  29132. this.spatialSound = true;
  29133. this._createSpatialParameters();
  29134. if (this.isPlaying && this.loop) {
  29135. this.stop();
  29136. this.play();
  29137. }
  29138. }
  29139. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29140. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29141. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29142. };
  29143. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29144. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29145. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29146. this._updateDirection();
  29147. }
  29148. };
  29149. return Sound;
  29150. })();
  29151. BABYLON.Sound = Sound;
  29152. })(BABYLON || (BABYLON = {}));
  29153. //# sourceMappingURL=babylon.sound.js.map
  29154. var BABYLON;
  29155. (function (BABYLON) {
  29156. var SoundTrack = (function () {
  29157. function SoundTrack(scene, options) {
  29158. this.id = -1;
  29159. this._isMainTrack = false;
  29160. this._scene = scene;
  29161. this._audioEngine = BABYLON.Engine.audioEngine;
  29162. this.soundCollection = new Array();
  29163. if (this._audioEngine.canUseWebAudio) {
  29164. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  29165. this._outputAudioNode.connect(this._audioEngine.masterGain);
  29166. if (options) {
  29167. if (options.volume) {
  29168. this._outputAudioNode.gain.value = options.volume;
  29169. }
  29170. if (options.mainTrack) {
  29171. this._isMainTrack = options.mainTrack;
  29172. }
  29173. }
  29174. }
  29175. if (!this._isMainTrack) {
  29176. this._scene.soundTracks.push(this);
  29177. this.id = this._scene.soundTracks.length - 1;
  29178. }
  29179. }
  29180. SoundTrack.prototype.dispose = function () {
  29181. if (this._audioEngine.canUseWebAudio) {
  29182. if (this._connectedAnalyser) {
  29183. this._connectedAnalyser.stopDebugCanvas();
  29184. }
  29185. while (this.soundCollection.length) {
  29186. this.soundCollection[0].dispose();
  29187. }
  29188. this._outputAudioNode.disconnect();
  29189. this._outputAudioNode = null;
  29190. }
  29191. };
  29192. SoundTrack.prototype.AddSound = function (sound) {
  29193. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29194. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  29195. }
  29196. if (sound.soundTrackId) {
  29197. if (sound.soundTrackId === -1) {
  29198. this._scene.mainSoundTrack.RemoveSound(sound);
  29199. }
  29200. else {
  29201. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29202. }
  29203. }
  29204. this.soundCollection.push(sound);
  29205. sound.soundTrackId = this.id;
  29206. };
  29207. SoundTrack.prototype.RemoveSound = function (sound) {
  29208. var index = this.soundCollection.indexOf(sound);
  29209. if (index !== -1) {
  29210. this.soundCollection.splice(index, 1);
  29211. }
  29212. };
  29213. SoundTrack.prototype.setVolume = function (newVolume) {
  29214. if (this._audioEngine.canUseWebAudio) {
  29215. this._outputAudioNode.gain.value = newVolume;
  29216. }
  29217. };
  29218. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29219. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29220. for (var i = 0; i < this.soundCollection.length; i++) {
  29221. this.soundCollection[i].switchPanningModelToHRTF();
  29222. }
  29223. }
  29224. };
  29225. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29226. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29227. for (var i = 0; i < this.soundCollection.length; i++) {
  29228. this.soundCollection[i].switchPanningModelToEqualPower();
  29229. }
  29230. }
  29231. };
  29232. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29233. if (this._connectedAnalyser) {
  29234. this._connectedAnalyser.stopDebugCanvas();
  29235. }
  29236. this._connectedAnalyser = analyser;
  29237. if (this._audioEngine.canUseWebAudio) {
  29238. this._outputAudioNode.disconnect();
  29239. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  29240. }
  29241. };
  29242. return SoundTrack;
  29243. })();
  29244. BABYLON.SoundTrack = SoundTrack;
  29245. })(BABYLON || (BABYLON = {}));
  29246. //# sourceMappingURL=babylon.soundtrack.js.map
  29247. var BABYLON;
  29248. (function (BABYLON) {
  29249. var DebugLayer = (function () {
  29250. function DebugLayer(scene) {
  29251. var _this = this;
  29252. this._transformationMatrix = BABYLON.Matrix.Identity();
  29253. this._enabled = false;
  29254. this._labelsEnabled = false;
  29255. this._displayStatistics = true;
  29256. this._displayTree = false;
  29257. this._displayLogs = false;
  29258. this._identityMatrix = BABYLON.Matrix.Identity();
  29259. this.axisRatio = 0.02;
  29260. this.accentColor = "orange";
  29261. this._scene = scene;
  29262. this._syncPositions = function () {
  29263. var engine = _this._scene.getEngine();
  29264. var canvasRect = engine.getRenderingCanvasClientRect();
  29265. if (_this._showUI) {
  29266. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29267. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29268. _this._statsDiv.style.width = "400px";
  29269. _this._statsDiv.style.height = "auto";
  29270. _this._statsSubsetDiv.style.maxHeight = "240px";
  29271. _this._optionsDiv.style.left = "0px";
  29272. _this._optionsDiv.style.top = "10px";
  29273. _this._optionsDiv.style.width = "200px";
  29274. _this._optionsDiv.style.height = "auto";
  29275. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29276. _this._logDiv.style.left = "0px";
  29277. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29278. _this._logDiv.style.width = "600px";
  29279. _this._logDiv.style.height = "160px";
  29280. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29281. _this._treeDiv.style.top = "10px";
  29282. _this._treeDiv.style.width = "300px";
  29283. _this._treeDiv.style.height = "auto";
  29284. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29285. }
  29286. _this._globalDiv.style.left = canvasRect.left + "px";
  29287. _this._globalDiv.style.top = canvasRect.top + "px";
  29288. _this._drawingCanvas.style.left = "0px";
  29289. _this._drawingCanvas.style.top = "0px";
  29290. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29291. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29292. var devicePixelRatio = window.devicePixelRatio || 1;
  29293. var context = _this._drawingContext;
  29294. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29295. context.mozBackingStorePixelRatio ||
  29296. context.msBackingStorePixelRatio ||
  29297. context.oBackingStorePixelRatio ||
  29298. context.backingStorePixelRatio || 1;
  29299. _this._ratio = devicePixelRatio / backingStoreRatio;
  29300. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29301. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29302. };
  29303. this._onCanvasClick = function (evt) {
  29304. _this._clickPosition = {
  29305. x: evt.clientX * _this._ratio,
  29306. y: evt.clientY * _this._ratio
  29307. };
  29308. };
  29309. this._syncUI = function () {
  29310. if (_this._showUI) {
  29311. if (_this._displayStatistics) {
  29312. _this._displayStats();
  29313. _this._statsDiv.style.display = "";
  29314. }
  29315. else {
  29316. _this._statsDiv.style.display = "none";
  29317. }
  29318. if (_this._displayLogs) {
  29319. _this._logDiv.style.display = "";
  29320. }
  29321. else {
  29322. _this._logDiv.style.display = "none";
  29323. }
  29324. if (_this._displayTree) {
  29325. _this._treeDiv.style.display = "";
  29326. if (_this._needToRefreshMeshesTree) {
  29327. _this._needToRefreshMeshesTree = false;
  29328. _this._refreshMeshesTreeContent();
  29329. }
  29330. }
  29331. else {
  29332. _this._treeDiv.style.display = "none";
  29333. }
  29334. }
  29335. };
  29336. this._syncData = function () {
  29337. if (_this._labelsEnabled || !_this._showUI) {
  29338. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29339. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29340. var engine = _this._scene.getEngine();
  29341. var viewport = _this._camera.viewport;
  29342. var globalViewport = viewport.toGlobal(engine);
  29343. // Meshes
  29344. var meshes = _this._camera.getActiveMeshes();
  29345. for (var index = 0; index < meshes.length; index++) {
  29346. var mesh = meshes.data[index];
  29347. var position = mesh.getBoundingInfo().boundingSphere.center;
  29348. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29349. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29350. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29351. }
  29352. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29353. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29354. }
  29355. }
  29356. // Cameras
  29357. var cameras = _this._scene.cameras;
  29358. for (index = 0; index < cameras.length; index++) {
  29359. var camera = cameras[index];
  29360. if (camera === _this._camera) {
  29361. continue;
  29362. }
  29363. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29364. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29365. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29366. _this._camera.detachControl(engine.getRenderingCanvas());
  29367. _this._camera = camera;
  29368. _this._camera.attachControl(engine.getRenderingCanvas());
  29369. }, function () { return "purple"; });
  29370. }
  29371. }
  29372. // Lights
  29373. var lights = _this._scene.lights;
  29374. for (index = 0; index < lights.length; index++) {
  29375. var light = lights[index];
  29376. if (light.position) {
  29377. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29378. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29379. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29380. light.setEnabled(!light.isEnabled());
  29381. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29382. }
  29383. }
  29384. }
  29385. }
  29386. _this._clickPosition = undefined;
  29387. };
  29388. }
  29389. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29390. while (this._treeSubsetDiv.hasChildNodes()) {
  29391. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29392. }
  29393. // Add meshes
  29394. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29395. sortedArray.sort(function (a, b) {
  29396. if (a.name === b.name) {
  29397. return 0;
  29398. }
  29399. return (a.name > b.name) ? 1 : -1;
  29400. });
  29401. for (var index = 0; index < sortedArray.length; index++) {
  29402. var mesh = sortedArray[index];
  29403. if (!mesh.isEnabled()) {
  29404. continue;
  29405. }
  29406. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29407. m.isVisible = element.checked;
  29408. }, mesh);
  29409. }
  29410. };
  29411. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29412. this._drawingContext.beginPath();
  29413. this._drawingContext.moveTo(zero.x, zero.y);
  29414. this._drawingContext.lineTo(unit.x, unit.y);
  29415. this._drawingContext.strokeStyle = color;
  29416. this._drawingContext.lineWidth = 4;
  29417. this._drawingContext.stroke();
  29418. this._drawingContext.font = "normal 14px Segoe UI";
  29419. this._drawingContext.fillStyle = color;
  29420. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29421. };
  29422. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29423. var position = mesh.getBoundingInfo().boundingSphere.center;
  29424. var worldMatrix = mesh.getWorldMatrix();
  29425. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29426. var unit = (unprojectedVector.subtract(position)).length();
  29427. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29428. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29429. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29430. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29431. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29432. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29433. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29434. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29435. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29436. };
  29437. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29438. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29439. this._drawingContext.font = "normal 12px Segoe UI";
  29440. var textMetrics = this._drawingContext.measureText(text);
  29441. var centerX = projectedPosition.x - textMetrics.width / 2;
  29442. var centerY = projectedPosition.y;
  29443. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29444. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29445. onClick();
  29446. }
  29447. this._drawingContext.beginPath();
  29448. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29449. this._drawingContext.fillStyle = getFillStyle();
  29450. this._drawingContext.globalAlpha = 0.5;
  29451. this._drawingContext.fill();
  29452. this._drawingContext.globalAlpha = 1.0;
  29453. this._drawingContext.strokeStyle = '#FFFFFF';
  29454. this._drawingContext.lineWidth = 1;
  29455. this._drawingContext.stroke();
  29456. this._drawingContext.fillStyle = "#FFFFFF";
  29457. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29458. this._drawingContext.beginPath();
  29459. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29460. this._drawingContext.fill();
  29461. }
  29462. };
  29463. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29464. if (!this._clickPosition) {
  29465. return false;
  29466. }
  29467. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29468. return false;
  29469. }
  29470. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29471. return false;
  29472. }
  29473. return true;
  29474. };
  29475. DebugLayer.prototype.isVisible = function () {
  29476. return this._enabled;
  29477. };
  29478. DebugLayer.prototype.hide = function () {
  29479. if (!this._enabled) {
  29480. return;
  29481. }
  29482. this._enabled = false;
  29483. var engine = this._scene.getEngine();
  29484. this._scene.unregisterBeforeRender(this._syncData);
  29485. this._scene.unregisterAfterRender(this._syncUI);
  29486. document.body.removeChild(this._globalDiv);
  29487. window.removeEventListener("resize", this._syncPositions);
  29488. this._scene.forceShowBoundingBoxes = false;
  29489. this._scene.forceWireframe = false;
  29490. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29491. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29492. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29493. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29494. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29495. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29496. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29497. this._scene.shadowsEnabled = true;
  29498. this._scene.particlesEnabled = true;
  29499. this._scene.postProcessesEnabled = true;
  29500. this._scene.collisionsEnabled = true;
  29501. this._scene.lightsEnabled = true;
  29502. this._scene.texturesEnabled = true;
  29503. this._scene.lensFlaresEnabled = true;
  29504. this._scene.proceduralTexturesEnabled = true;
  29505. this._scene.renderTargetsEnabled = true;
  29506. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29507. };
  29508. DebugLayer.prototype.show = function (showUI, camera) {
  29509. if (showUI === void 0) { showUI = true; }
  29510. if (camera === void 0) { camera = null; }
  29511. if (this._enabled) {
  29512. return;
  29513. }
  29514. this._enabled = true;
  29515. if (camera) {
  29516. this._camera = camera;
  29517. }
  29518. else {
  29519. this._camera = this._scene.activeCamera;
  29520. }
  29521. this._showUI = showUI;
  29522. var engine = this._scene.getEngine();
  29523. this._globalDiv = document.createElement("div");
  29524. document.body.appendChild(this._globalDiv);
  29525. this._generateDOMelements();
  29526. window.addEventListener("resize", this._syncPositions);
  29527. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29528. this._syncPositions();
  29529. this._scene.registerBeforeRender(this._syncData);
  29530. this._scene.registerAfterRender(this._syncUI);
  29531. };
  29532. DebugLayer.prototype._clearLabels = function () {
  29533. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29534. for (var index = 0; index < this._scene.meshes.length; index++) {
  29535. var mesh = this._scene.meshes[index];
  29536. mesh.renderOverlay = false;
  29537. }
  29538. };
  29539. DebugLayer.prototype._generateheader = function (root, text) {
  29540. var header = document.createElement("div");
  29541. header.innerHTML = text + "&nbsp;";
  29542. header.style.textAlign = "right";
  29543. header.style.width = "100%";
  29544. header.style.color = "white";
  29545. header.style.backgroundColor = "Black";
  29546. header.style.padding = "5px 5px 4px 0px";
  29547. header.style.marginLeft = "-5px";
  29548. header.style.fontWeight = "bold";
  29549. root.appendChild(header);
  29550. };
  29551. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29552. var label = document.createElement("label");
  29553. label.innerHTML = title;
  29554. label.style.color = color;
  29555. root.appendChild(label);
  29556. root.appendChild(document.createElement("br"));
  29557. };
  29558. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29559. if (tag === void 0) { tag = null; }
  29560. var label = document.createElement("label");
  29561. var boundingBoxesCheckbox = document.createElement("input");
  29562. boundingBoxesCheckbox.type = "checkbox";
  29563. boundingBoxesCheckbox.checked = initialState;
  29564. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29565. task(evt.target, tag);
  29566. });
  29567. label.appendChild(boundingBoxesCheckbox);
  29568. var container = document.createElement("span");
  29569. var leftPart = document.createElement("span");
  29570. var rightPart = document.createElement("span");
  29571. rightPart.style.cssFloat = "right";
  29572. leftPart.innerHTML = leftTitle;
  29573. rightPart.innerHTML = rightTitle;
  29574. rightPart.style.fontSize = "12px";
  29575. rightPart.style.maxWidth = "200px";
  29576. container.appendChild(leftPart);
  29577. container.appendChild(rightPart);
  29578. label.appendChild(container);
  29579. root.appendChild(label);
  29580. root.appendChild(document.createElement("br"));
  29581. };
  29582. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29583. if (tag === void 0) { tag = null; }
  29584. var label = document.createElement("label");
  29585. var checkBox = document.createElement("input");
  29586. checkBox.type = "checkbox";
  29587. checkBox.checked = initialState;
  29588. checkBox.addEventListener("change", function (evt) {
  29589. task(evt.target, tag);
  29590. });
  29591. label.appendChild(checkBox);
  29592. label.appendChild(document.createTextNode(title));
  29593. root.appendChild(label);
  29594. root.appendChild(document.createElement("br"));
  29595. };
  29596. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29597. if (tag === void 0) { tag = null; }
  29598. var button = document.createElement("button");
  29599. button.innerHTML = title;
  29600. button.style.height = "24px";
  29601. button.style.color = "#444444";
  29602. button.style.border = "1px solid white";
  29603. button.className = "debugLayerButton";
  29604. button.addEventListener("click", function (evt) {
  29605. task(evt.target, tag);
  29606. });
  29607. root.appendChild(button);
  29608. root.appendChild(document.createElement("br"));
  29609. };
  29610. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29611. if (tag === void 0) { tag = null; }
  29612. var label = document.createElement("label");
  29613. var boundingBoxesRadio = document.createElement("input");
  29614. boundingBoxesRadio.type = "radio";
  29615. boundingBoxesRadio.name = name;
  29616. boundingBoxesRadio.checked = initialState;
  29617. boundingBoxesRadio.addEventListener("change", function (evt) {
  29618. task(evt.target, tag);
  29619. });
  29620. label.appendChild(boundingBoxesRadio);
  29621. label.appendChild(document.createTextNode(title));
  29622. root.appendChild(label);
  29623. root.appendChild(document.createElement("br"));
  29624. };
  29625. DebugLayer.prototype._generateDOMelements = function () {
  29626. var _this = this;
  29627. this._globalDiv.id = "DebugLayer";
  29628. this._globalDiv.style.position = "absolute";
  29629. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29630. this._globalDiv.style.fontSize = "14px";
  29631. this._globalDiv.style.color = "white";
  29632. // Drawing canvas
  29633. this._drawingCanvas = document.createElement("canvas");
  29634. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29635. this._drawingCanvas.style.position = "absolute";
  29636. this._drawingCanvas.style.pointerEvents = "none";
  29637. this._drawingContext = this._drawingCanvas.getContext("2d");
  29638. this._globalDiv.appendChild(this._drawingCanvas);
  29639. if (this._showUI) {
  29640. var background = "rgba(128, 128, 128, 0.4)";
  29641. var border = "rgb(180, 180, 180) solid 1px";
  29642. // Stats
  29643. this._statsDiv = document.createElement("div");
  29644. this._statsDiv.id = "DebugLayerStats";
  29645. this._statsDiv.style.border = border;
  29646. this._statsDiv.style.position = "absolute";
  29647. this._statsDiv.style.background = background;
  29648. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29649. this._generateheader(this._statsDiv, "STATISTICS");
  29650. this._statsSubsetDiv = document.createElement("div");
  29651. this._statsSubsetDiv.style.paddingTop = "5px";
  29652. this._statsSubsetDiv.style.paddingBottom = "5px";
  29653. this._statsSubsetDiv.style.overflowY = "auto";
  29654. this._statsDiv.appendChild(this._statsSubsetDiv);
  29655. // Tree
  29656. this._treeDiv = document.createElement("div");
  29657. this._treeDiv.id = "DebugLayerTree";
  29658. this._treeDiv.style.border = border;
  29659. this._treeDiv.style.position = "absolute";
  29660. this._treeDiv.style.background = background;
  29661. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29662. this._treeDiv.style.display = "none";
  29663. this._generateheader(this._treeDiv, "MESHES TREE");
  29664. this._treeSubsetDiv = document.createElement("div");
  29665. this._treeSubsetDiv.style.paddingTop = "5px";
  29666. this._treeSubsetDiv.style.paddingRight = "5px";
  29667. this._treeSubsetDiv.style.overflowY = "auto";
  29668. this._treeSubsetDiv.style.maxHeight = "300px";
  29669. this._treeDiv.appendChild(this._treeSubsetDiv);
  29670. this._needToRefreshMeshesTree = true;
  29671. // Logs
  29672. this._logDiv = document.createElement("div");
  29673. this._logDiv.style.border = border;
  29674. this._logDiv.id = "DebugLayerLogs";
  29675. this._logDiv.style.position = "absolute";
  29676. this._logDiv.style.background = background;
  29677. this._logDiv.style.padding = "0px 0px 0px 5px";
  29678. this._logDiv.style.display = "none";
  29679. this._generateheader(this._logDiv, "LOGS");
  29680. this._logSubsetDiv = document.createElement("div");
  29681. this._logSubsetDiv.style.height = "127px";
  29682. this._logSubsetDiv.style.paddingTop = "5px";
  29683. this._logSubsetDiv.style.overflowY = "auto";
  29684. this._logSubsetDiv.style.fontSize = "12px";
  29685. this._logSubsetDiv.style.fontFamily = "consolas";
  29686. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29687. this._logDiv.appendChild(this._logSubsetDiv);
  29688. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29689. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29690. };
  29691. // Options
  29692. this._optionsDiv = document.createElement("div");
  29693. this._optionsDiv.id = "DebugLayerOptions";
  29694. this._optionsDiv.style.border = border;
  29695. this._optionsDiv.style.position = "absolute";
  29696. this._optionsDiv.style.background = background;
  29697. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29698. this._optionsDiv.style.overflowY = "auto";
  29699. this._generateheader(this._optionsDiv, "OPTIONS");
  29700. this._optionsSubsetDiv = document.createElement("div");
  29701. this._optionsSubsetDiv.style.paddingTop = "5px";
  29702. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29703. this._optionsSubsetDiv.style.overflowY = "auto";
  29704. this._optionsSubsetDiv.style.maxHeight = "200px";
  29705. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29706. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29707. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29708. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29709. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29710. _this._displayTree = element.checked;
  29711. _this._needToRefreshMeshesTree = true;
  29712. });
  29713. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29714. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29715. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29716. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29717. _this._labelsEnabled = element.checked;
  29718. if (!_this._labelsEnabled) {
  29719. _this._clearLabels();
  29720. }
  29721. });
  29722. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29723. if (element.checked) {
  29724. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29725. }
  29726. else {
  29727. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29728. }
  29729. });
  29730. ;
  29731. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29732. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29733. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29734. if (element.checked) {
  29735. _this._scene.forceWireframe = false;
  29736. _this._scene.forcePointsCloud = false;
  29737. }
  29738. });
  29739. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29740. if (element.checked) {
  29741. _this._scene.forceWireframe = true;
  29742. _this._scene.forcePointsCloud = false;
  29743. }
  29744. });
  29745. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29746. if (element.checked) {
  29747. _this._scene.forceWireframe = false;
  29748. _this._scene.forcePointsCloud = true;
  29749. }
  29750. });
  29751. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29752. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29753. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29754. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29755. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29756. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29757. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29758. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29759. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29760. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29761. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29762. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29763. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29764. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29765. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29766. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29767. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29768. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29769. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29770. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29771. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29772. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29773. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29774. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29775. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29776. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29777. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29778. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29779. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29780. if (element.checked) {
  29781. _this._scene.headphone = true;
  29782. }
  29783. });
  29784. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29785. if (element.checked) {
  29786. _this._scene.headphone = false;
  29787. }
  29788. });
  29789. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29790. _this._scene.audioEnabled = !element.checked;
  29791. });
  29792. }
  29793. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29794. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29795. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29796. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29797. this._globalDiv.appendChild(this._statsDiv);
  29798. this._globalDiv.appendChild(this._logDiv);
  29799. this._globalDiv.appendChild(this._optionsDiv);
  29800. this._globalDiv.appendChild(this._treeDiv);
  29801. }
  29802. };
  29803. DebugLayer.prototype._displayStats = function () {
  29804. var scene = this._scene;
  29805. var engine = scene.getEngine();
  29806. var glInfo = engine.getGlInfo();
  29807. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29808. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29809. + "<b>Count</b><br>"
  29810. + "Total meshes: " + scene.meshes.length + "<br>"
  29811. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29812. + "Total materials: " + scene.materials.length + "<br>"
  29813. + "Total textures: " + scene.textures.length + "<br>"
  29814. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29815. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29816. + "Active bones: " + scene.getActiveBones() + "<br>"
  29817. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29818. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  29819. + "<b>Duration</b><br>"
  29820. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29821. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29822. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29823. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29824. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29825. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29826. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  29827. + "</div>"
  29828. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29829. + "<b>Extensions</b><br>"
  29830. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29831. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29832. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29833. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  29834. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29835. + "<b>Caps.</b><br>"
  29836. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29837. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29838. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  29839. + "</div><br>"
  29840. + "<b>Info</b><br>"
  29841. + glInfo.version + "<br>"
  29842. + glInfo.renderer + "<br>";
  29843. if (this.customStatsFunction) {
  29844. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29845. }
  29846. };
  29847. return DebugLayer;
  29848. })();
  29849. BABYLON.DebugLayer = DebugLayer;
  29850. })(BABYLON || (BABYLON = {}));
  29851. //# sourceMappingURL=babylon.debugLayer.js.map
  29852. var BABYLON;
  29853. (function (BABYLON) {
  29854. var RawTexture = (function (_super) {
  29855. __extends(RawTexture, _super);
  29856. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29857. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29858. if (invertY === void 0) { invertY = false; }
  29859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29860. _super.call(this, null, scene, !generateMipMaps, invertY);
  29861. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29862. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29863. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29864. }
  29865. // Statics
  29866. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29867. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29868. if (invertY === void 0) { invertY = false; }
  29869. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29870. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29871. };
  29872. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29873. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29874. if (invertY === void 0) { invertY = false; }
  29875. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29876. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29877. };
  29878. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29879. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29880. if (invertY === void 0) { invertY = false; }
  29881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29882. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29883. };
  29884. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29885. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29886. if (invertY === void 0) { invertY = false; }
  29887. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29888. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29889. };
  29890. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29891. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29892. if (invertY === void 0) { invertY = false; }
  29893. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29894. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29895. };
  29896. return RawTexture;
  29897. })(BABYLON.Texture);
  29898. BABYLON.RawTexture = RawTexture;
  29899. })(BABYLON || (BABYLON = {}));
  29900. //# sourceMappingURL=babylon.rawTexture.js.map
  29901. var BABYLON;
  29902. (function (BABYLON) {
  29903. var IndexedVector2 = (function (_super) {
  29904. __extends(IndexedVector2, _super);
  29905. function IndexedVector2(original, index) {
  29906. _super.call(this, original.x, original.y);
  29907. this.index = index;
  29908. }
  29909. return IndexedVector2;
  29910. })(BABYLON.Vector2);
  29911. var PolygonPoints = (function () {
  29912. function PolygonPoints() {
  29913. this.elements = new Array();
  29914. }
  29915. PolygonPoints.prototype.add = function (originalPoints) {
  29916. var _this = this;
  29917. var result = new Array();
  29918. originalPoints.forEach(function (point) {
  29919. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  29920. var newPoint = new IndexedVector2(point, _this.elements.length);
  29921. result.push(newPoint);
  29922. _this.elements.push(newPoint);
  29923. }
  29924. });
  29925. return result;
  29926. };
  29927. PolygonPoints.prototype.computeBounds = function () {
  29928. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29929. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29930. this.elements.forEach(function (point) {
  29931. // x
  29932. if (point.x < lmin.x) {
  29933. lmin.x = point.x;
  29934. }
  29935. else if (point.x > lmax.x) {
  29936. lmax.x = point.x;
  29937. }
  29938. // y
  29939. if (point.y < lmin.y) {
  29940. lmin.y = point.y;
  29941. }
  29942. else if (point.y > lmax.y) {
  29943. lmax.y = point.y;
  29944. }
  29945. });
  29946. return {
  29947. min: lmin,
  29948. max: lmax,
  29949. width: lmax.x - lmin.x,
  29950. height: lmax.y - lmin.y
  29951. };
  29952. };
  29953. return PolygonPoints;
  29954. })();
  29955. var Polygon = (function () {
  29956. function Polygon() {
  29957. }
  29958. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  29959. return [
  29960. new BABYLON.Vector2(xmin, ymin),
  29961. new BABYLON.Vector2(xmax, ymin),
  29962. new BABYLON.Vector2(xmax, ymax),
  29963. new BABYLON.Vector2(xmin, ymax)
  29964. ];
  29965. };
  29966. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  29967. if (cx === void 0) { cx = 0; }
  29968. if (cy === void 0) { cy = 0; }
  29969. if (numberOfSides === void 0) { numberOfSides = 32; }
  29970. var result = new Array();
  29971. var angle = 0;
  29972. var increment = (Math.PI * 2) / numberOfSides;
  29973. for (var i = 0; i < numberOfSides; i++) {
  29974. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  29975. angle -= increment;
  29976. }
  29977. return result;
  29978. };
  29979. Polygon.Parse = function (input) {
  29980. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  29981. var i, result = [];
  29982. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  29983. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  29984. }
  29985. return result;
  29986. };
  29987. Polygon.StartingAt = function (x, y) {
  29988. return BABYLON.Path2.StartingAt(x, y);
  29989. };
  29990. return Polygon;
  29991. })();
  29992. BABYLON.Polygon = Polygon;
  29993. var PolygonMeshBuilder = (function () {
  29994. function PolygonMeshBuilder(name, contours, scene) {
  29995. this._points = new PolygonPoints();
  29996. this._outlinepoints = new PolygonPoints();
  29997. this._holes = [];
  29998. if (!("poly2tri" in window)) {
  29999. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  30000. }
  30001. this._name = name;
  30002. this._scene = scene;
  30003. var points;
  30004. if (contours instanceof BABYLON.Path2) {
  30005. points = contours.getPoints();
  30006. }
  30007. else {
  30008. points = contours;
  30009. }
  30010. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  30011. this._outlinepoints.add(points);
  30012. }
  30013. PolygonMeshBuilder.prototype.addHole = function (hole) {
  30014. this._swctx.addHole(this._points.add(hole));
  30015. var holepoints = new PolygonPoints();
  30016. holepoints.add(hole);
  30017. this._holes.push(holepoints);
  30018. return this;
  30019. };
  30020. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  30021. var _this = this;
  30022. if (updatable === void 0) { updatable = false; }
  30023. var result = new BABYLON.Mesh(this._name, this._scene);
  30024. var normals = [];
  30025. var positions = [];
  30026. var uvs = [];
  30027. var bounds = this._points.computeBounds();
  30028. this._points.elements.forEach(function (p) {
  30029. normals.push(0, 1.0, 0);
  30030. positions.push(p.x, 0, p.y);
  30031. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  30032. });
  30033. var indices = [];
  30034. this._swctx.triangulate();
  30035. this._swctx.getTriangles().forEach(function (triangle) {
  30036. triangle.getPoints().forEach(function (point) {
  30037. indices.push(point.index);
  30038. });
  30039. });
  30040. if (depth > 0) {
  30041. var positionscount = (positions.length / 3); //get the current pointcount
  30042. this._points.elements.forEach(function (p) {
  30043. normals.push(0, -1.0, 0);
  30044. positions.push(p.x, -depth, p.y);
  30045. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  30046. });
  30047. var p1; //we need to change order of point so the triangles are made in the rigth way.
  30048. var p2;
  30049. var poscounter = 0;
  30050. this._swctx.getTriangles().forEach(function (triangle) {
  30051. triangle.getPoints().forEach(function (point) {
  30052. switch (poscounter) {
  30053. case 0:
  30054. p1 = point;
  30055. break;
  30056. case 1:
  30057. p2 = point;
  30058. break;
  30059. case 2:
  30060. indices.push(point.index + positionscount);
  30061. indices.push(p2.index + positionscount);
  30062. indices.push(p1.index + positionscount);
  30063. poscounter = -1;
  30064. break;
  30065. }
  30066. poscounter++;
  30067. //indices.push((<IndexedVector2>point).index + positionscount);
  30068. });
  30069. });
  30070. //Add the sides
  30071. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  30072. this._holes.forEach(function (hole) {
  30073. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  30074. });
  30075. }
  30076. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  30077. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  30078. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  30079. result.setIndices(indices);
  30080. return result;
  30081. };
  30082. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  30083. var StartIndex = positions.length / 3;
  30084. var ulength = 0;
  30085. for (var i = 0; i < points.elements.length; i++) {
  30086. var p = points.elements[i];
  30087. var p1;
  30088. if ((i + 1) > points.elements.length - 1) {
  30089. p1 = points.elements[0];
  30090. }
  30091. else {
  30092. p1 = points.elements[i + 1];
  30093. }
  30094. positions.push(p.x, 0, p.y);
  30095. positions.push(p.x, -depth, p.y);
  30096. positions.push(p1.x, 0, p1.y);
  30097. positions.push(p1.x, -depth, p1.y);
  30098. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  30099. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  30100. var v3 = v2.subtract(v1);
  30101. var v4 = new BABYLON.Vector3(0, 1, 0);
  30102. var vn = BABYLON.Vector3.Cross(v3, v4);
  30103. vn = vn.normalize();
  30104. uvs.push(ulength / bounds.width, 0);
  30105. uvs.push(ulength / bounds.width, 1);
  30106. ulength += v3.length();
  30107. uvs.push((ulength / bounds.width), 0);
  30108. uvs.push((ulength / bounds.width), 1);
  30109. if (!flip) {
  30110. normals.push(-vn.x, -vn.y, -vn.z);
  30111. normals.push(-vn.x, -vn.y, -vn.z);
  30112. normals.push(-vn.x, -vn.y, -vn.z);
  30113. normals.push(-vn.x, -vn.y, -vn.z);
  30114. indices.push(StartIndex);
  30115. indices.push(StartIndex + 1);
  30116. indices.push(StartIndex + 2);
  30117. indices.push(StartIndex + 1);
  30118. indices.push(StartIndex + 3);
  30119. indices.push(StartIndex + 2);
  30120. }
  30121. else {
  30122. normals.push(vn.x, vn.y, vn.z);
  30123. normals.push(vn.x, vn.y, vn.z);
  30124. normals.push(vn.x, vn.y, vn.z);
  30125. normals.push(vn.x, vn.y, vn.z);
  30126. indices.push(StartIndex);
  30127. indices.push(StartIndex + 2);
  30128. indices.push(StartIndex + 1);
  30129. indices.push(StartIndex + 1);
  30130. indices.push(StartIndex + 2);
  30131. indices.push(StartIndex + 3);
  30132. }
  30133. StartIndex += 4;
  30134. }
  30135. ;
  30136. };
  30137. return PolygonMeshBuilder;
  30138. })();
  30139. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  30140. })(BABYLON || (BABYLON = {}));
  30141. //# sourceMappingURL=babylon.polygonMesh.js.map
  30142. var BABYLON;
  30143. (function (BABYLON) {
  30144. var SimplificationSettings = (function () {
  30145. function SimplificationSettings(quality, distance, optimizeMesh) {
  30146. this.quality = quality;
  30147. this.distance = distance;
  30148. this.optimizeMesh = optimizeMesh;
  30149. }
  30150. return SimplificationSettings;
  30151. })();
  30152. BABYLON.SimplificationSettings = SimplificationSettings;
  30153. var SimplificationQueue = (function () {
  30154. function SimplificationQueue() {
  30155. this.running = false;
  30156. this._simplificationArray = [];
  30157. }
  30158. SimplificationQueue.prototype.addTask = function (task) {
  30159. this._simplificationArray.push(task);
  30160. };
  30161. SimplificationQueue.prototype.executeNext = function () {
  30162. var task = this._simplificationArray.pop();
  30163. if (task) {
  30164. this.running = true;
  30165. this.runSimplification(task);
  30166. }
  30167. else {
  30168. this.running = false;
  30169. }
  30170. };
  30171. SimplificationQueue.prototype.runSimplification = function (task) {
  30172. var _this = this;
  30173. if (task.parallelProcessing) {
  30174. //parallel simplifier
  30175. task.settings.forEach(function (setting) {
  30176. var simplifier = _this.getSimplifier(task);
  30177. simplifier.simplify(setting, function (newMesh) {
  30178. task.mesh.addLODLevel(setting.distance, newMesh);
  30179. newMesh.isVisible = true;
  30180. //check if it is the last
  30181. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30182. //all done, run the success callback.
  30183. task.successCallback();
  30184. }
  30185. _this.executeNext();
  30186. });
  30187. });
  30188. }
  30189. else {
  30190. //single simplifier.
  30191. var simplifier = this.getSimplifier(task);
  30192. var runDecimation = function (setting, callback) {
  30193. simplifier.simplify(setting, function (newMesh) {
  30194. task.mesh.addLODLevel(setting.distance, newMesh);
  30195. newMesh.isVisible = true;
  30196. //run the next quality level
  30197. callback();
  30198. });
  30199. };
  30200. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30201. runDecimation(task.settings[loop.index], function () {
  30202. loop.executeNext();
  30203. });
  30204. }, function () {
  30205. //execution ended, run the success callback.
  30206. if (task.successCallback) {
  30207. task.successCallback();
  30208. }
  30209. _this.executeNext();
  30210. });
  30211. }
  30212. };
  30213. SimplificationQueue.prototype.getSimplifier = function (task) {
  30214. switch (task.simplificationType) {
  30215. case SimplificationType.QUADRATIC:
  30216. default:
  30217. return new QuadraticErrorSimplification(task.mesh);
  30218. }
  30219. };
  30220. return SimplificationQueue;
  30221. })();
  30222. BABYLON.SimplificationQueue = SimplificationQueue;
  30223. /**
  30224. * The implemented types of simplification.
  30225. * At the moment only Quadratic Error Decimation is implemented.
  30226. */
  30227. (function (SimplificationType) {
  30228. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30229. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30230. var SimplificationType = BABYLON.SimplificationType;
  30231. var DecimationTriangle = (function () {
  30232. function DecimationTriangle(vertices) {
  30233. this.vertices = vertices;
  30234. this.error = new Array(4);
  30235. this.deleted = false;
  30236. this.isDirty = false;
  30237. this.deletePending = false;
  30238. this.borderFactor = 0;
  30239. }
  30240. return DecimationTriangle;
  30241. })();
  30242. BABYLON.DecimationTriangle = DecimationTriangle;
  30243. var DecimationVertex = (function () {
  30244. function DecimationVertex(position, id) {
  30245. this.position = position;
  30246. this.id = id;
  30247. this.isBorder = true;
  30248. this.q = new QuadraticMatrix();
  30249. this.triangleCount = 0;
  30250. this.triangleStart = 0;
  30251. this.originalOffsets = [];
  30252. }
  30253. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30254. this.position.copyFrom(newPosition);
  30255. };
  30256. return DecimationVertex;
  30257. })();
  30258. BABYLON.DecimationVertex = DecimationVertex;
  30259. var QuadraticMatrix = (function () {
  30260. function QuadraticMatrix(data) {
  30261. this.data = new Array(10);
  30262. for (var i = 0; i < 10; ++i) {
  30263. if (data && data[i]) {
  30264. this.data[i] = data[i];
  30265. }
  30266. else {
  30267. this.data[i] = 0;
  30268. }
  30269. }
  30270. }
  30271. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30272. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30273. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30274. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30275. return det;
  30276. };
  30277. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30278. for (var i = 0; i < 10; ++i) {
  30279. this.data[i] += matrix.data[i];
  30280. }
  30281. };
  30282. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30283. for (var i = 0; i < 10; ++i) {
  30284. this.data[i] += data[i];
  30285. }
  30286. };
  30287. QuadraticMatrix.prototype.add = function (matrix) {
  30288. var m = new QuadraticMatrix();
  30289. for (var i = 0; i < 10; ++i) {
  30290. m.data[i] = this.data[i] + matrix.data[i];
  30291. }
  30292. return m;
  30293. };
  30294. QuadraticMatrix.FromData = function (a, b, c, d) {
  30295. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30296. };
  30297. //returning an array to avoid garbage collection
  30298. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30299. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30300. };
  30301. return QuadraticMatrix;
  30302. })();
  30303. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30304. var Reference = (function () {
  30305. function Reference(vertexId, triangleId) {
  30306. this.vertexId = vertexId;
  30307. this.triangleId = triangleId;
  30308. }
  30309. return Reference;
  30310. })();
  30311. BABYLON.Reference = Reference;
  30312. /**
  30313. * An implementation of the Quadratic Error simplification algorithm.
  30314. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30315. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30316. * @author RaananW
  30317. */
  30318. var QuadraticErrorSimplification = (function () {
  30319. function QuadraticErrorSimplification(_mesh) {
  30320. this._mesh = _mesh;
  30321. this.initialized = false;
  30322. this.syncIterations = 5000;
  30323. this.aggressiveness = 7;
  30324. this.decimationIterations = 100;
  30325. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30326. }
  30327. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30328. var _this = this;
  30329. this.initDecimatedMesh();
  30330. //iterating through the submeshes array, one after the other.
  30331. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30332. _this.initWithMesh(loop.index, function () {
  30333. _this.runDecimation(settings, loop.index, function () {
  30334. loop.executeNext();
  30335. });
  30336. }, settings.optimizeMesh);
  30337. }, function () {
  30338. setTimeout(function () {
  30339. successCallback(_this._reconstructedMesh);
  30340. }, 0);
  30341. });
  30342. };
  30343. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30344. var _this = this;
  30345. var gCount = 0;
  30346. triangle.vertices.forEach(function (vertex) {
  30347. var count = 0;
  30348. var vPos = vertex.position;
  30349. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30350. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30351. ++count;
  30352. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30353. ++count;
  30354. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30355. ++count;
  30356. if (count > 1) {
  30357. ++gCount;
  30358. }
  30359. ;
  30360. });
  30361. if (gCount > 1) {
  30362. console.log(triangle, gCount);
  30363. }
  30364. return gCount > 1;
  30365. };
  30366. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30367. var _this = this;
  30368. var targetCount = ~~(this.triangles.length * settings.quality);
  30369. var deletedTriangles = 0;
  30370. var triangleCount = this.triangles.length;
  30371. var iterationFunction = function (iteration, callback) {
  30372. setTimeout(function () {
  30373. if (iteration % 5 === 0) {
  30374. _this.updateMesh(iteration === 0);
  30375. }
  30376. for (var i = 0; i < _this.triangles.length; ++i) {
  30377. _this.triangles[i].isDirty = false;
  30378. }
  30379. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30380. var trianglesIterator = function (i) {
  30381. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30382. var t = _this.triangles[tIdx];
  30383. if (!t)
  30384. return;
  30385. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30386. return;
  30387. }
  30388. for (var j = 0; j < 3; ++j) {
  30389. if (t.error[j] < threshold) {
  30390. var deleted0 = [];
  30391. var deleted1 = [];
  30392. var v0 = t.vertices[j];
  30393. var v1 = t.vertices[(j + 1) % 3];
  30394. if (v0.isBorder !== v1.isBorder)
  30395. continue;
  30396. var p = BABYLON.Vector3.Zero();
  30397. var n = BABYLON.Vector3.Zero();
  30398. var uv = BABYLON.Vector2.Zero();
  30399. var color = new BABYLON.Color4(0, 0, 0, 1);
  30400. _this.calculateError(v0, v1, p, n, uv, color);
  30401. var delTr = [];
  30402. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30403. continue;
  30404. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30405. continue;
  30406. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30407. continue;
  30408. var uniqueArray = [];
  30409. delTr.forEach(function (deletedT) {
  30410. if (uniqueArray.indexOf(deletedT) === -1) {
  30411. deletedT.deletePending = true;
  30412. uniqueArray.push(deletedT);
  30413. }
  30414. });
  30415. if (uniqueArray.length % 2 != 0) {
  30416. continue;
  30417. }
  30418. v0.q = v1.q.add(v0.q);
  30419. v0.updatePosition(p);
  30420. var tStart = _this.references.length;
  30421. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30422. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30423. var tCount = _this.references.length - tStart;
  30424. if (tCount <= v0.triangleCount) {
  30425. if (tCount) {
  30426. for (var c = 0; c < tCount; c++) {
  30427. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30428. }
  30429. }
  30430. }
  30431. else {
  30432. v0.triangleStart = tStart;
  30433. }
  30434. v0.triangleCount = tCount;
  30435. break;
  30436. }
  30437. }
  30438. };
  30439. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30440. }, 0);
  30441. };
  30442. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30443. if (triangleCount - deletedTriangles <= targetCount)
  30444. loop.breakLoop();
  30445. else {
  30446. iterationFunction(loop.index, function () {
  30447. loop.executeNext();
  30448. });
  30449. }
  30450. }, function () {
  30451. setTimeout(function () {
  30452. //reconstruct this part of the mesh
  30453. _this.reconstructMesh(submeshIndex);
  30454. successCallback();
  30455. }, 0);
  30456. });
  30457. };
  30458. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30459. var _this = this;
  30460. this.vertices = [];
  30461. this.triangles = [];
  30462. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30463. var indices = this._mesh.getIndices();
  30464. var submesh = this._mesh.subMeshes[submeshIndex];
  30465. var findInVertices = function (positionToSearch) {
  30466. if (optimizeMesh) {
  30467. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30468. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30469. return _this.vertices[ii];
  30470. }
  30471. }
  30472. }
  30473. return null;
  30474. };
  30475. var vertexReferences = [];
  30476. var vertexInit = function (i) {
  30477. var offset = i + submesh.verticesStart;
  30478. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30479. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30480. vertex.originalOffsets.push(offset);
  30481. if (vertex.id == _this.vertices.length) {
  30482. _this.vertices.push(vertex);
  30483. }
  30484. vertexReferences.push(vertex.id);
  30485. };
  30486. //var totalVertices = mesh.getTotalVertices();
  30487. var totalVertices = submesh.verticesCount;
  30488. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30489. var indicesInit = function (i) {
  30490. var offset = (submesh.indexStart / 3) + i;
  30491. var pos = (offset * 3);
  30492. var i0 = indices[pos + 0];
  30493. var i1 = indices[pos + 1];
  30494. var i2 = indices[pos + 2];
  30495. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30496. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30497. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30498. var triangle = new DecimationTriangle([v0, v1, v2]);
  30499. triangle.originalOffset = pos;
  30500. _this.triangles.push(triangle);
  30501. };
  30502. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30503. _this.init(callback);
  30504. });
  30505. });
  30506. };
  30507. QuadraticErrorSimplification.prototype.init = function (callback) {
  30508. var _this = this;
  30509. var triangleInit1 = function (i) {
  30510. var t = _this.triangles[i];
  30511. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30512. for (var j = 0; j < 3; j++) {
  30513. 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))));
  30514. }
  30515. };
  30516. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30517. var triangleInit2 = function (i) {
  30518. var t = _this.triangles[i];
  30519. for (var j = 0; j < 3; ++j) {
  30520. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30521. }
  30522. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30523. };
  30524. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30525. _this.initialized = true;
  30526. callback();
  30527. });
  30528. });
  30529. };
  30530. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30531. var newTriangles = [];
  30532. var i;
  30533. for (i = 0; i < this.vertices.length; ++i) {
  30534. this.vertices[i].triangleCount = 0;
  30535. }
  30536. var t;
  30537. var j;
  30538. for (i = 0; i < this.triangles.length; ++i) {
  30539. if (!this.triangles[i].deleted) {
  30540. t = this.triangles[i];
  30541. for (j = 0; j < 3; ++j) {
  30542. t.vertices[j].triangleCount = 1;
  30543. }
  30544. newTriangles.push(t);
  30545. }
  30546. }
  30547. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30548. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30549. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30550. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30551. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30552. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30553. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30554. var vertexCount = 0;
  30555. for (i = 0; i < this.vertices.length; ++i) {
  30556. var vertex = this.vertices[i];
  30557. vertex.id = vertexCount;
  30558. if (vertex.triangleCount) {
  30559. vertex.originalOffsets.forEach(function (originalOffset) {
  30560. newPositionData.push(vertex.position.x);
  30561. newPositionData.push(vertex.position.y);
  30562. newPositionData.push(vertex.position.z);
  30563. newNormalData.push(normalData[originalOffset * 3]);
  30564. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30565. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30566. if (uvs && uvs.length) {
  30567. newUVsData.push(uvs[(originalOffset * 2)]);
  30568. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30569. }
  30570. else if (colorsData && colorsData.length) {
  30571. newColorsData.push(colorsData[(originalOffset * 4)]);
  30572. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30573. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30574. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30575. }
  30576. ++vertexCount;
  30577. });
  30578. }
  30579. }
  30580. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30581. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30582. var submeshesArray = this._reconstructedMesh.subMeshes;
  30583. this._reconstructedMesh.subMeshes = [];
  30584. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30585. var originalIndices = this._mesh.getIndices();
  30586. for (i = 0; i < newTriangles.length; ++i) {
  30587. var t = newTriangles[i];
  30588. //now get the new referencing point for each vertex
  30589. [0, 1, 2].forEach(function (idx) {
  30590. var id = originalIndices[t.originalOffset + idx];
  30591. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30592. if (offset < 0)
  30593. offset = 0;
  30594. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30595. });
  30596. }
  30597. //overwriting the old vertex buffers and indices.
  30598. this._reconstructedMesh.setIndices(newIndicesArray);
  30599. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30600. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30601. if (newUVsData.length > 0)
  30602. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30603. if (newColorsData.length > 0)
  30604. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30605. //create submesh
  30606. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30607. if (submeshIndex > 0) {
  30608. this._reconstructedMesh.subMeshes = [];
  30609. submeshesArray.forEach(function (submesh) {
  30610. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30611. });
  30612. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30613. }
  30614. };
  30615. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30616. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30617. this._reconstructedMesh.material = this._mesh.material;
  30618. this._reconstructedMesh.parent = this._mesh.parent;
  30619. this._reconstructedMesh.isVisible = false;
  30620. };
  30621. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30622. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30623. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30624. if (t.deleted)
  30625. continue;
  30626. var s = this.references[vertex1.triangleStart + i].vertexId;
  30627. var v1 = t.vertices[(s + 1) % 3];
  30628. var v2 = t.vertices[(s + 2) % 3];
  30629. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30630. deletedArray[i] = true;
  30631. delTr.push(t);
  30632. continue;
  30633. }
  30634. var d1 = v1.position.subtract(point);
  30635. d1 = d1.normalize();
  30636. var d2 = v2.position.subtract(point);
  30637. d2 = d2.normalize();
  30638. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30639. return true;
  30640. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30641. deletedArray[i] = false;
  30642. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30643. return true;
  30644. }
  30645. return false;
  30646. };
  30647. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30648. var newDeleted = deletedTriangles;
  30649. for (var i = 0; i < vertex.triangleCount; ++i) {
  30650. var ref = this.references[vertex.triangleStart + i];
  30651. var t = this.triangles[ref.triangleId];
  30652. if (t.deleted)
  30653. continue;
  30654. if (deletedArray[i] && t.deletePending) {
  30655. t.deleted = true;
  30656. newDeleted++;
  30657. continue;
  30658. }
  30659. t.vertices[ref.vertexId] = origVertex;
  30660. t.isDirty = true;
  30661. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30662. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30663. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30664. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30665. this.references.push(ref);
  30666. }
  30667. return newDeleted;
  30668. };
  30669. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30670. for (var i = 0; i < this.vertices.length; ++i) {
  30671. var vCount = [];
  30672. var vId = [];
  30673. var v = this.vertices[i];
  30674. var j;
  30675. for (j = 0; j < v.triangleCount; ++j) {
  30676. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30677. for (var ii = 0; ii < 3; ii++) {
  30678. var ofs = 0;
  30679. var vv = triangle.vertices[ii];
  30680. while (ofs < vCount.length) {
  30681. if (vId[ofs] === vv.id)
  30682. break;
  30683. ++ofs;
  30684. }
  30685. if (ofs === vCount.length) {
  30686. vCount.push(1);
  30687. vId.push(vv.id);
  30688. }
  30689. else {
  30690. vCount[ofs]++;
  30691. }
  30692. }
  30693. }
  30694. for (j = 0; j < vCount.length; ++j) {
  30695. if (vCount[j] === 1) {
  30696. this.vertices[vId[j]].isBorder = true;
  30697. }
  30698. else {
  30699. this.vertices[vId[j]].isBorder = false;
  30700. }
  30701. }
  30702. }
  30703. };
  30704. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30705. if (identifyBorders === void 0) { identifyBorders = false; }
  30706. var i;
  30707. if (!identifyBorders) {
  30708. var newTrianglesVector = [];
  30709. for (i = 0; i < this.triangles.length; ++i) {
  30710. if (!this.triangles[i].deleted) {
  30711. newTrianglesVector.push(this.triangles[i]);
  30712. }
  30713. }
  30714. this.triangles = newTrianglesVector;
  30715. }
  30716. for (i = 0; i < this.vertices.length; ++i) {
  30717. this.vertices[i].triangleCount = 0;
  30718. this.vertices[i].triangleStart = 0;
  30719. }
  30720. var t;
  30721. var j;
  30722. var v;
  30723. for (i = 0; i < this.triangles.length; ++i) {
  30724. t = this.triangles[i];
  30725. for (j = 0; j < 3; ++j) {
  30726. v = t.vertices[j];
  30727. v.triangleCount++;
  30728. }
  30729. }
  30730. var tStart = 0;
  30731. for (i = 0; i < this.vertices.length; ++i) {
  30732. this.vertices[i].triangleStart = tStart;
  30733. tStart += this.vertices[i].triangleCount;
  30734. this.vertices[i].triangleCount = 0;
  30735. }
  30736. var newReferences = new Array(this.triangles.length * 3);
  30737. for (i = 0; i < this.triangles.length; ++i) {
  30738. t = this.triangles[i];
  30739. for (j = 0; j < 3; ++j) {
  30740. v = t.vertices[j];
  30741. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30742. v.triangleCount++;
  30743. }
  30744. }
  30745. this.references = newReferences;
  30746. if (identifyBorders) {
  30747. this.identifyBorder();
  30748. }
  30749. };
  30750. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30751. var x = point.x;
  30752. var y = point.y;
  30753. var z = point.z;
  30754. 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
  30755. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30756. };
  30757. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30758. var q = vertex1.q.add(vertex2.q);
  30759. var border = vertex1.isBorder && vertex2.isBorder;
  30760. var error = 0;
  30761. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30762. if (qDet !== 0 && !border) {
  30763. if (!pointResult) {
  30764. pointResult = BABYLON.Vector3.Zero();
  30765. }
  30766. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30767. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30768. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30769. error = this.vertexError(q, pointResult);
  30770. }
  30771. else {
  30772. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30773. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30774. var error1 = this.vertexError(q, vertex1.position);
  30775. var error2 = this.vertexError(q, vertex2.position);
  30776. var error3 = this.vertexError(q, p3);
  30777. error = Math.min(error1, error2, error3);
  30778. if (error === error1) {
  30779. if (pointResult) {
  30780. pointResult.copyFrom(vertex1.position);
  30781. }
  30782. }
  30783. else if (error === error2) {
  30784. if (pointResult) {
  30785. pointResult.copyFrom(vertex2.position);
  30786. }
  30787. }
  30788. else {
  30789. if (pointResult) {
  30790. pointResult.copyFrom(p3);
  30791. }
  30792. }
  30793. }
  30794. return error;
  30795. };
  30796. return QuadraticErrorSimplification;
  30797. })();
  30798. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30799. })(BABYLON || (BABYLON = {}));
  30800. //# sourceMappingURL=babylon.meshSimplification.js.map
  30801. var BABYLON;
  30802. (function (BABYLON) {
  30803. var Analyser = (function () {
  30804. function Analyser(scene) {
  30805. this.SMOOTHING = 0.75;
  30806. this.FFT_SIZE = 512;
  30807. this.BARGRAPHAMPLITUDE = 256;
  30808. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30809. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30810. this._scene = scene;
  30811. this._audioEngine = BABYLON.Engine.audioEngine;
  30812. if (this._audioEngine.canUseWebAudio) {
  30813. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30814. this._webAudioAnalyser.minDecibels = -140;
  30815. this._webAudioAnalyser.maxDecibels = 0;
  30816. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30817. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30818. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30819. }
  30820. }
  30821. Analyser.prototype.getFrequencyBinCount = function () {
  30822. if (this._audioEngine.canUseWebAudio) {
  30823. return this._webAudioAnalyser.frequencyBinCount;
  30824. }
  30825. else {
  30826. return 0;
  30827. }
  30828. };
  30829. Analyser.prototype.getByteFrequencyData = function () {
  30830. if (this._audioEngine.canUseWebAudio) {
  30831. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30832. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30833. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30834. }
  30835. return this._byteFreqs;
  30836. };
  30837. Analyser.prototype.getByteTimeDomainData = function () {
  30838. if (this._audioEngine.canUseWebAudio) {
  30839. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30840. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30841. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30842. }
  30843. return this._byteTime;
  30844. };
  30845. Analyser.prototype.getFloatFrequencyData = function () {
  30846. if (this._audioEngine.canUseWebAudio) {
  30847. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30848. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30849. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30850. }
  30851. return this._floatFreqs;
  30852. };
  30853. Analyser.prototype.drawDebugCanvas = function () {
  30854. var _this = this;
  30855. if (this._audioEngine.canUseWebAudio) {
  30856. if (!this._debugCanvas) {
  30857. this._debugCanvas = document.createElement("canvas");
  30858. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30859. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30860. this._debugCanvas.style.position = "absolute";
  30861. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30862. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30863. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30864. document.body.appendChild(this._debugCanvas);
  30865. this._registerFunc = function () {
  30866. _this.drawDebugCanvas();
  30867. };
  30868. this._scene.registerBeforeRender(this._registerFunc);
  30869. }
  30870. if (this._registerFunc) {
  30871. var workingArray = this.getByteFrequencyData();
  30872. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30873. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30874. // Draw the frequency domain chart.
  30875. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30876. var value = workingArray[i];
  30877. var percent = value / this.BARGRAPHAMPLITUDE;
  30878. var height = this.DEBUGCANVASSIZE.height * percent;
  30879. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30880. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30881. var hue = i / this.getFrequencyBinCount() * 360;
  30882. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30883. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30884. }
  30885. }
  30886. }
  30887. };
  30888. Analyser.prototype.stopDebugCanvas = function () {
  30889. if (this._debugCanvas) {
  30890. this._scene.unregisterBeforeRender(this._registerFunc);
  30891. this._registerFunc = null;
  30892. document.body.removeChild(this._debugCanvas);
  30893. this._debugCanvas = null;
  30894. this._debugCanvasContext = null;
  30895. }
  30896. };
  30897. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30898. if (this._audioEngine.canUseWebAudio) {
  30899. inputAudioNode.connect(this._webAudioAnalyser);
  30900. this._webAudioAnalyser.connect(outputAudioNode);
  30901. }
  30902. };
  30903. Analyser.prototype.dispose = function () {
  30904. if (this._audioEngine.canUseWebAudio) {
  30905. this._webAudioAnalyser.disconnect();
  30906. }
  30907. };
  30908. return Analyser;
  30909. })();
  30910. BABYLON.Analyser = Analyser;
  30911. })(BABYLON || (BABYLON = {}));
  30912. //# sourceMappingURL=babylon.analyser.js.map
  30913. var BABYLON;
  30914. (function (BABYLON) {
  30915. var DepthRenderer = (function () {
  30916. function DepthRenderer(scene, type) {
  30917. var _this = this;
  30918. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30919. this._viewMatrix = BABYLON.Matrix.Zero();
  30920. this._projectionMatrix = BABYLON.Matrix.Zero();
  30921. this._transformMatrix = BABYLON.Matrix.Zero();
  30922. this._worldViewProjection = BABYLON.Matrix.Zero();
  30923. this._scene = scene;
  30924. var engine = scene.getEngine();
  30925. // Render target
  30926. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30927. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30928. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30929. this._depthMap.refreshRate = 1;
  30930. this._depthMap.renderParticles = false;
  30931. this._depthMap.renderList = null;
  30932. // set default depth value to 1.0 (far away)
  30933. this._depthMap.onClear = function (engine) {
  30934. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30935. };
  30936. // Custom render function
  30937. var renderSubMesh = function (subMesh) {
  30938. var mesh = subMesh.getRenderingMesh();
  30939. var scene = _this._scene;
  30940. var engine = scene.getEngine();
  30941. // Culling
  30942. engine.setState(subMesh.getMaterial().backFaceCulling);
  30943. // Managing instances
  30944. var batch = mesh._getInstancesRenderList(subMesh._id);
  30945. if (batch.mustReturn) {
  30946. return;
  30947. }
  30948. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30949. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30950. engine.enableEffect(_this._effect);
  30951. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  30952. var material = subMesh.getMaterial();
  30953. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30954. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  30955. // Alpha test
  30956. if (material && material.needAlphaTesting()) {
  30957. var alphaTexture = material.getAlphaTestTexture();
  30958. _this._effect.setTexture("diffuseSampler", alphaTexture);
  30959. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30960. }
  30961. // Bones
  30962. if (mesh.useBones) {
  30963. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30964. }
  30965. // Draw
  30966. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  30967. }
  30968. };
  30969. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  30970. var index;
  30971. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30972. renderSubMesh(opaqueSubMeshes.data[index]);
  30973. }
  30974. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30975. renderSubMesh(alphaTestSubMeshes.data[index]);
  30976. }
  30977. };
  30978. }
  30979. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  30980. var defines = [];
  30981. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30982. var mesh = subMesh.getMesh();
  30983. var scene = mesh.getScene();
  30984. var material = subMesh.getMaterial();
  30985. // Alpha test
  30986. if (material && material.needAlphaTesting()) {
  30987. defines.push("#define ALPHATEST");
  30988. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30989. attribs.push(BABYLON.VertexBuffer.UVKind);
  30990. defines.push("#define UV1");
  30991. }
  30992. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30993. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30994. defines.push("#define UV2");
  30995. }
  30996. }
  30997. // Bones
  30998. if (mesh.useBones) {
  30999. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31000. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31001. defines.push("#define BONES");
  31002. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31003. }
  31004. // Instances
  31005. if (useInstances) {
  31006. defines.push("#define INSTANCES");
  31007. attribs.push("world0");
  31008. attribs.push("world1");
  31009. attribs.push("world2");
  31010. attribs.push("world3");
  31011. }
  31012. // Get correct effect
  31013. var join = defines.join("\n");
  31014. if (this._cachedDefines !== join) {
  31015. this._cachedDefines = join;
  31016. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  31017. }
  31018. return this._effect.isReady();
  31019. };
  31020. DepthRenderer.prototype.getDepthMap = function () {
  31021. return this._depthMap;
  31022. };
  31023. // Methods
  31024. DepthRenderer.prototype.dispose = function () {
  31025. this._depthMap.dispose();
  31026. };
  31027. return DepthRenderer;
  31028. })();
  31029. BABYLON.DepthRenderer = DepthRenderer;
  31030. })(BABYLON || (BABYLON = {}));
  31031. //# sourceMappingURL=babylon.depthRenderer.js.map
  31032. var BABYLON;
  31033. (function (BABYLON) {
  31034. var SSAORenderingPipeline = (function (_super) {
  31035. __extends(SSAORenderingPipeline, _super);
  31036. /**
  31037. * @constructor
  31038. * @param {string} name - The rendering pipeline name
  31039. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31040. * @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 }
  31041. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31042. */
  31043. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  31044. var _this = this;
  31045. _super.call(this, scene.getEngine(), name);
  31046. // Members
  31047. /**
  31048. * The PassPostProcess id in the pipeline that contains the original scene color
  31049. * @type {string}
  31050. */
  31051. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  31052. /**
  31053. * The SSAO PostProcess id in the pipeline
  31054. * @type {string}
  31055. */
  31056. this.SSAORenderEffect = "SSAORenderEffect";
  31057. /**
  31058. * The horizontal blur PostProcess id in the pipeline
  31059. * @type {string}
  31060. */
  31061. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  31062. /**
  31063. * The vertical blur PostProcess id in the pipeline
  31064. * @type {string}
  31065. */
  31066. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  31067. /**
  31068. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  31069. * @type {string}
  31070. */
  31071. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  31072. /**
  31073. * The output strength of the SSAO post-process. Default value is 1.0.
  31074. * @type {number}
  31075. */
  31076. this.totalStrength = 1.0;
  31077. /**
  31078. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  31079. * @type {number}
  31080. */
  31081. this.radius = 0.0002;
  31082. /**
  31083. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  31084. * Must not be equal to fallOff and superior to fallOff.
  31085. * Default value is 0.0075
  31086. * @type {number}
  31087. */
  31088. this.area = 0.0075;
  31089. /**
  31090. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  31091. * Must not be equal to area and inferior to area.
  31092. * Default value is 0.0002
  31093. * @type {number}
  31094. */
  31095. this.fallOff = 0.0002;
  31096. this._firstUpdate = true;
  31097. this._scene = scene;
  31098. // Set up assets
  31099. this._createRandomTexture();
  31100. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31101. var ssaoRatio = ratio.ssaoRatio || ratio;
  31102. var combineRatio = ratio.combineRatio || ratio;
  31103. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31104. this._createSSAOPostProcess(ssaoRatio);
  31105. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31106. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31107. this._createSSAOCombinePostProcess(combineRatio);
  31108. // Set up pipeline
  31109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  31110. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  31111. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  31112. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  31113. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  31114. // Finish
  31115. scene.postProcessRenderPipelineManager.addPipeline(this);
  31116. if (cameras)
  31117. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31118. }
  31119. // Public Methods
  31120. /**
  31121. * Returns the horizontal blur PostProcess
  31122. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  31123. */
  31124. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  31125. return this._blurHPostProcess;
  31126. };
  31127. /**
  31128. * Returns the vertical blur PostProcess
  31129. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  31130. */
  31131. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  31132. return this._blurVPostProcess;
  31133. };
  31134. /**
  31135. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  31136. */
  31137. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31138. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31139. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31140. this._originalColorPostProcess = undefined;
  31141. this._ssaoPostProcess = undefined;
  31142. this._blurHPostProcess = undefined;
  31143. this._blurVPostProcess = undefined;
  31144. this._ssaoCombinePostProcess = undefined;
  31145. this._randomTexture.dispose();
  31146. if (disableDepthRender)
  31147. this._scene.disableDepthRenderer();
  31148. };
  31149. // Private Methods
  31150. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  31151. var _this = this;
  31152. var sampleSphere = [
  31153. 0.5381, 0.1856, -0.4319,
  31154. 0.1379, 0.2486, 0.4430,
  31155. 0.3371, 0.5679, -0.0057,
  31156. -0.6999, -0.0451, -0.0019,
  31157. 0.0689, -0.1598, -0.8547,
  31158. 0.0560, 0.0069, -0.1843,
  31159. -0.0146, 0.1402, 0.0762,
  31160. 0.0100, -0.1924, -0.0344,
  31161. -0.3577, -0.5301, -0.4358,
  31162. -0.3169, 0.1063, 0.0158,
  31163. 0.0103, -0.5869, 0.0046,
  31164. -0.0897, -0.4940, 0.3287,
  31165. 0.7119, -0.0154, -0.0918,
  31166. -0.0533, 0.0596, -0.5411,
  31167. 0.0352, -0.0631, 0.5460,
  31168. -0.4776, 0.2847, -0.0271
  31169. ];
  31170. var samplesFactor = 1.0 / 16.0;
  31171. 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);
  31172. this._ssaoPostProcess.onApply = function (effect) {
  31173. if (_this._firstUpdate) {
  31174. effect.setArray3("sampleSphere", sampleSphere);
  31175. effect.setFloat("samplesFactor", samplesFactor);
  31176. effect.setFloat("randTextureTiles", 4.0 / ratio);
  31177. _this._firstUpdate = false;
  31178. }
  31179. effect.setFloat("totalStrength", _this.totalStrength);
  31180. effect.setFloat("radius", _this.radius);
  31181. effect.setFloat("area", _this.area);
  31182. effect.setFloat("fallOff", _this.fallOff);
  31183. effect.setTexture("textureSampler", _this._depthTexture);
  31184. effect.setTexture("randomSampler", _this._randomTexture);
  31185. };
  31186. };
  31187. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  31188. var _this = this;
  31189. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31190. this._ssaoCombinePostProcess.onApply = function (effect) {
  31191. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  31192. };
  31193. };
  31194. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  31195. var size = 512;
  31196. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31197. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31198. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31199. var context = this._randomTexture.getContext();
  31200. var rand = function (min, max) {
  31201. return Math.random() * (max - min) + min;
  31202. };
  31203. for (var x = 0; x < size; x++) {
  31204. for (var y = 0; y < size; y++) {
  31205. var randVector = BABYLON.Vector3.Zero();
  31206. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  31207. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  31208. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  31209. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  31210. context.fillRect(x, y, 1, 1);
  31211. }
  31212. }
  31213. this._randomTexture.update(false);
  31214. };
  31215. return SSAORenderingPipeline;
  31216. })(BABYLON.PostProcessRenderPipeline);
  31217. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  31218. })(BABYLON || (BABYLON = {}));
  31219. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  31220. var BABYLON;
  31221. (function (BABYLON) {
  31222. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  31223. var VolumetricLightScatteringPostProcess = (function (_super) {
  31224. __extends(VolumetricLightScatteringPostProcess, _super);
  31225. /**
  31226. * @constructor
  31227. * @param {string} name - The post-process name
  31228. * @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)
  31229. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  31230. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  31231. * @param {number} samples - The post-process quality, default 100
  31232. * @param {number} samplingMode - The post-process filtering mode
  31233. * @param {BABYLON.Engine} engine - The babylon engine
  31234. * @param {boolean} reusable - If the post-process is reusable
  31235. */
  31236. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  31237. var _this = this;
  31238. if (samples === void 0) { samples = 100; }
  31239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31240. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  31241. this._screenCoordinates = BABYLON.Vector2.Zero();
  31242. /**
  31243. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31244. * @type {boolean}
  31245. */
  31246. this.useCustomMeshPosition = false;
  31247. /**
  31248. * If the post-process should inverse the light scattering direction
  31249. * @type {boolean}
  31250. */
  31251. this.invert = true;
  31252. /**
  31253. * Set to true to use the diffuseColor instead of the diffuseTexture
  31254. * @type {boolean}
  31255. */
  31256. this.useDiffuseColor = false;
  31257. /**
  31258. * Array containing the excluded meshes not rendered in the internal pass
  31259. */
  31260. this.excludedMeshes = new Array();
  31261. /**
  31262. * Controls the overall intensity of the post-process
  31263. * @type {number}
  31264. */
  31265. this.exposure = 0.3;
  31266. /**
  31267. * Dissipates each sample's contribution in range [0, 1]
  31268. * @type {number}
  31269. */
  31270. this.decay = 0.96815;
  31271. /**
  31272. * Controls the overall intensity of each sample
  31273. * @type {number}
  31274. */
  31275. this.weight = 0.58767;
  31276. /**
  31277. * Controls the density of each sample
  31278. * @type {number}
  31279. */
  31280. this.density = 0.926;
  31281. var scene = camera.getScene();
  31282. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  31283. // Configure mesh
  31284. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  31285. // Configure
  31286. this._createPass(scene, ratio.passRatio || ratio);
  31287. this.onApply = function (effect) {
  31288. _this._updateMeshScreenCoordinates(scene);
  31289. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  31290. effect.setFloat("exposure", _this.exposure);
  31291. effect.setFloat("decay", _this.decay);
  31292. effect.setFloat("weight", _this.weight);
  31293. effect.setFloat("density", _this.density);
  31294. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  31295. };
  31296. }
  31297. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31298. var mesh = subMesh.getMesh();
  31299. var defines = [];
  31300. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31301. var material = subMesh.getMaterial();
  31302. var needUV = false;
  31303. // Render this.mesh as default
  31304. if (mesh === this.mesh) {
  31305. if (this.useDiffuseColor) {
  31306. defines.push("#define DIFFUSE_COLOR_RENDER");
  31307. }
  31308. else if (material) {
  31309. if (material.diffuseTexture !== undefined) {
  31310. defines.push("#define BASIC_RENDER");
  31311. }
  31312. else {
  31313. defines.push("#define DIFFUSE_COLOR_RENDER");
  31314. }
  31315. }
  31316. defines.push("#define NEED_UV");
  31317. needUV = true;
  31318. }
  31319. // Alpha test
  31320. if (material) {
  31321. if (material.needAlphaTesting()) {
  31322. defines.push("#define ALPHATEST");
  31323. }
  31324. if (material.opacityTexture !== undefined) {
  31325. defines.push("#define OPACITY");
  31326. if (material.opacityTexture.getAlphaFromRGB) {
  31327. defines.push("#define OPACITYRGB");
  31328. }
  31329. if (!needUV) {
  31330. defines.push("#define NEED_UV");
  31331. }
  31332. }
  31333. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31334. attribs.push(BABYLON.VertexBuffer.UVKind);
  31335. defines.push("#define UV1");
  31336. }
  31337. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31338. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31339. defines.push("#define UV2");
  31340. }
  31341. }
  31342. // Bones
  31343. if (mesh.useBones) {
  31344. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31345. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31346. defines.push("#define BONES");
  31347. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31348. }
  31349. // Instances
  31350. if (useInstances) {
  31351. defines.push("#define INSTANCES");
  31352. attribs.push("world0");
  31353. attribs.push("world1");
  31354. attribs.push("world2");
  31355. attribs.push("world3");
  31356. }
  31357. // Get correct effect
  31358. var join = defines.join("\n");
  31359. if (this._cachedDefines !== join) {
  31360. this._cachedDefines = join;
  31361. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  31362. }
  31363. return this._volumetricLightScatteringPass.isReady();
  31364. };
  31365. /**
  31366. * Sets the new light position for light scattering effect
  31367. * @param {BABYLON.Vector3} The new custom light position
  31368. */
  31369. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31370. this._customMeshPosition = position;
  31371. };
  31372. /**
  31373. * Returns the light position for light scattering effect
  31374. * @return {BABYLON.Vector3} The custom light position
  31375. */
  31376. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31377. return this._customMeshPosition;
  31378. };
  31379. /**
  31380. * Disposes the internal assets and detaches the post-process from the camera
  31381. */
  31382. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31383. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31384. if (rttIndex !== -1) {
  31385. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31386. }
  31387. this._volumetricLightScatteringRTT.dispose();
  31388. _super.prototype.dispose.call(this, camera);
  31389. };
  31390. /**
  31391. * Returns the render target texture used by the post-process
  31392. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31393. */
  31394. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31395. return this._volumetricLightScatteringRTT;
  31396. };
  31397. // Private methods
  31398. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31399. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31400. return true;
  31401. }
  31402. return false;
  31403. };
  31404. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31405. var _this = this;
  31406. var engine = scene.getEngine();
  31407. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31408. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31409. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31410. this._volumetricLightScatteringRTT.renderList = null;
  31411. this._volumetricLightScatteringRTT.renderParticles = false;
  31412. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31413. // Custom render function for submeshes
  31414. var renderSubMesh = function (subMesh) {
  31415. var mesh = subMesh.getRenderingMesh();
  31416. if (_this._meshExcluded(mesh)) {
  31417. return;
  31418. }
  31419. var scene = mesh.getScene();
  31420. var engine = scene.getEngine();
  31421. // Culling
  31422. engine.setState(subMesh.getMaterial().backFaceCulling);
  31423. // Managing instances
  31424. var batch = mesh._getInstancesRenderList(subMesh._id);
  31425. if (batch.mustReturn) {
  31426. return;
  31427. }
  31428. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31429. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31430. engine.enableEffect(_this._volumetricLightScatteringPass);
  31431. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31432. var material = subMesh.getMaterial();
  31433. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31434. // Alpha test
  31435. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31436. var alphaTexture = material.getAlphaTestTexture();
  31437. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  31438. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  31439. }
  31440. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  31441. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31442. if (alphaTexture) {
  31443. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31444. }
  31445. }
  31446. if (material.opacityTexture !== undefined) {
  31447. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31448. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31449. }
  31450. }
  31451. // Bones
  31452. if (mesh.useBones) {
  31453. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31454. }
  31455. // Draw
  31456. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31457. }
  31458. };
  31459. // Render target texture callbacks
  31460. var savedSceneClearColor;
  31461. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31462. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31463. savedSceneClearColor = scene.clearColor;
  31464. scene.clearColor = sceneClearColor;
  31465. };
  31466. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31467. scene.clearColor = savedSceneClearColor;
  31468. };
  31469. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31470. var engine = scene.getEngine();
  31471. var index;
  31472. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31473. renderSubMesh(opaqueSubMeshes.data[index]);
  31474. }
  31475. engine.setAlphaTesting(true);
  31476. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31477. renderSubMesh(alphaTestSubMeshes.data[index]);
  31478. }
  31479. engine.setAlphaTesting(false);
  31480. if (transparentSubMeshes.length) {
  31481. // Sort sub meshes
  31482. for (index = 0; index < transparentSubMeshes.length; index++) {
  31483. var submesh = transparentSubMeshes.data[index];
  31484. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31485. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31486. }
  31487. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31488. sortedArray.sort(function (a, b) {
  31489. // Alpha index first
  31490. if (a._alphaIndex > b._alphaIndex) {
  31491. return 1;
  31492. }
  31493. if (a._alphaIndex < b._alphaIndex) {
  31494. return -1;
  31495. }
  31496. // Then distance to camera
  31497. if (a._distanceToCamera < b._distanceToCamera) {
  31498. return 1;
  31499. }
  31500. if (a._distanceToCamera > b._distanceToCamera) {
  31501. return -1;
  31502. }
  31503. return 0;
  31504. });
  31505. // Render sub meshes
  31506. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31507. for (index = 0; index < sortedArray.length; index++) {
  31508. renderSubMesh(sortedArray[index]);
  31509. }
  31510. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31511. }
  31512. };
  31513. };
  31514. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31515. var transform = scene.getTransformMatrix();
  31516. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31517. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31518. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31519. if (this.invert)
  31520. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31521. };
  31522. // Static methods
  31523. /**
  31524. * Creates a default mesh for the Volumeric Light Scattering post-process
  31525. * @param {string} The mesh name
  31526. * @param {BABYLON.Scene} The scene where to create the mesh
  31527. * @return {BABYLON.Mesh} the default mesh
  31528. */
  31529. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31530. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31531. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31532. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31533. return mesh;
  31534. };
  31535. return VolumetricLightScatteringPostProcess;
  31536. })(BABYLON.PostProcess);
  31537. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31538. })(BABYLON || (BABYLON = {}));
  31539. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31540. var BABYLON;
  31541. (function (BABYLON) {
  31542. var LensRenderingPipeline = (function (_super) {
  31543. __extends(LensRenderingPipeline, _super);
  31544. /**
  31545. * @constructor
  31546. *
  31547. * Effect parameters are as follow:
  31548. * {
  31549. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31550. * edge_blur: number; // from 0 to x (1 for realism)
  31551. * distortion: number; // from 0 to x (1 for realism)
  31552. * grain_amount: number; // from 0 to 1
  31553. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31554. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  31555. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31556. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  31557. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31558. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  31559. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  31560. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31561. * }
  31562. * Note: if an effect parameter is unset, effect is disabled
  31563. *
  31564. * @param {string} name - The rendering pipeline name
  31565. * @param {object} parameters - An object containing all parameters (see above)
  31566. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31567. * @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)
  31568. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31569. */
  31570. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31571. var _this = this;
  31572. if (ratio === void 0) { ratio = 1.0; }
  31573. _super.call(this, scene.getEngine(), name);
  31574. // Lens effects can be of the following:
  31575. // - chromatic aberration (slight shift of RGB colors)
  31576. // - blur on the edge of the lens
  31577. // - lens distortion
  31578. // - depth-of-field blur & highlights enhancing
  31579. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31580. // - grain effect (noise or custom texture)
  31581. // Two additional texture samplers are needed:
  31582. // - depth map (for depth-of-field)
  31583. // - grain texture
  31584. /**
  31585. * The chromatic aberration PostProcess id in the pipeline
  31586. * @type {string}
  31587. */
  31588. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31589. /**
  31590. * The highlights enhancing PostProcess id in the pipeline
  31591. * @type {string}
  31592. */
  31593. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31594. /**
  31595. * The depth-of-field PostProcess id in the pipeline
  31596. * @type {string}
  31597. */
  31598. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31599. this._scene = scene;
  31600. // Fetch texture samplers
  31601. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31602. if (parameters.grain_texture) {
  31603. this._grainTexture = parameters.grain_texture;
  31604. }
  31605. else {
  31606. this._createGrainTexture();
  31607. }
  31608. // save parameters
  31609. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31610. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31611. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31612. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31613. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31614. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31615. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  31616. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31617. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  31618. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31619. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31620. // Create effects
  31621. this._createChromaticAberrationPostProcess(ratio);
  31622. this._createHighlightsPostProcess(ratio);
  31623. this._createDepthOfFieldPostProcess(ratio / 4);
  31624. // Set up pipeline
  31625. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  31626. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  31627. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  31628. if (this._highlightsGain == -1) {
  31629. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31630. }
  31631. // Finish
  31632. scene.postProcessRenderPipelineManager.addPipeline(this);
  31633. if (cameras) {
  31634. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31635. }
  31636. }
  31637. // public methods (self explanatory)
  31638. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  31639. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  31640. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  31641. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  31642. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  31643. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  31644. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  31645. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  31646. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  31647. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  31648. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  31649. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  31650. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  31651. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  31652. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  31653. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  31654. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31655. this._highlightsGain = amount;
  31656. };
  31657. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31658. if (this._highlightsGain == -1) {
  31659. this._highlightsGain = 1.0;
  31660. }
  31661. this._highlightsThreshold = amount;
  31662. };
  31663. LensRenderingPipeline.prototype.disableHighlights = function () {
  31664. this._highlightsGain = -1;
  31665. };
  31666. /**
  31667. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31668. */
  31669. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31670. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31671. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31672. this._chromaticAberrationPostProcess = undefined;
  31673. this._highlightsPostProcess = undefined;
  31674. this._depthOfFieldPostProcess = undefined;
  31675. this._grainTexture.dispose();
  31676. if (disableDepthRender)
  31677. this._scene.disableDepthRenderer();
  31678. };
  31679. // colors shifting and distortion
  31680. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31681. var _this = this;
  31682. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31683. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31684. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31685. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31686. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31687. };
  31688. };
  31689. // highlights enhancing
  31690. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31691. var _this = this;
  31692. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31693. this._highlightsPostProcess.onApply = function (effect) {
  31694. effect.setFloat('gain', _this._highlightsGain);
  31695. effect.setFloat('threshold', _this._highlightsThreshold);
  31696. effect.setBool('pentagon', _this._dofPentagon);
  31697. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31698. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31699. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31700. };
  31701. };
  31702. // colors shifting and distortion
  31703. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31704. var _this = this;
  31705. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31706. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  31707. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  31708. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31709. this._depthOfFieldPostProcess.onApply = function (effect) {
  31710. effect.setTexture("depthSampler", _this._depthTexture);
  31711. effect.setTexture("grainSampler", _this._grainTexture);
  31712. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31713. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31714. effect.setFloat('grain_amount', _this._grainAmount);
  31715. effect.setBool('blur_noise', _this._blurNoise);
  31716. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31717. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31718. effect.setFloat('distortion', _this._distortion);
  31719. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  31720. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  31721. effect.setFloat('aperture', _this._dofAperture);
  31722. effect.setFloat('darken', _this._dofDarken);
  31723. effect.setFloat('edge_blur', _this._edgeBlur);
  31724. effect.setBool('highlights', (_this._highlightsGain != -1));
  31725. effect.setFloat('near', _this._scene.activeCamera.minZ);
  31726. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  31727. };
  31728. };
  31729. // creates a black and white random noise texture, 512x512
  31730. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31731. var size = 512;
  31732. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31733. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31734. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31735. var context = this._grainTexture.getContext();
  31736. var rand = function (min, max) {
  31737. return Math.random() * (max - min) + min;
  31738. };
  31739. var value;
  31740. for (var x = 0; x < size; x++) {
  31741. for (var y = 0; y < size; y++) {
  31742. value = Math.floor(rand(0.42, 0.58) * 255);
  31743. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31744. context.fillRect(x, y, 1, 1);
  31745. }
  31746. }
  31747. this._grainTexture.update(false);
  31748. };
  31749. return LensRenderingPipeline;
  31750. })(BABYLON.PostProcessRenderPipeline);
  31751. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31752. })(BABYLON || (BABYLON = {}));
  31753. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31754. //
  31755. // This post-process allows the modification of rendered colors by using
  31756. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31757. //
  31758. // The object needs to be provided an url to a texture containing the color
  31759. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31760. // Use an image editing software to tweak the LUT to match your needs.
  31761. //
  31762. // For an example of a color LUT, see here:
  31763. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31764. // For explanations on color grading, see here:
  31765. // http://udn.epicgames.com/Three/ColorGrading.html
  31766. //
  31767. var BABYLON;
  31768. (function (BABYLON) {
  31769. var ColorCorrectionPostProcess = (function (_super) {
  31770. __extends(ColorCorrectionPostProcess, _super);
  31771. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31772. var _this = this;
  31773. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31774. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31775. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31776. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31777. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31778. this.onApply = function (effect) {
  31779. effect.setTexture("colorTable", _this._colorTableTexture);
  31780. };
  31781. }
  31782. return ColorCorrectionPostProcess;
  31783. })(BABYLON.PostProcess);
  31784. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31785. })(BABYLON || (BABYLON = {}));
  31786. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31787. var BABYLON;
  31788. (function (BABYLON) {
  31789. var AnaglyphFreeCamera = (function (_super) {
  31790. __extends(AnaglyphFreeCamera, _super);
  31791. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  31792. _super.call(this, name, position, scene);
  31793. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  31794. }
  31795. return AnaglyphFreeCamera;
  31796. })(BABYLON.FreeCamera);
  31797. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  31798. var AnaglyphArcRotateCamera = (function (_super) {
  31799. __extends(AnaglyphArcRotateCamera, _super);
  31800. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  31801. _super.call(this, name, alpha, beta, radius, target, scene);
  31802. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  31803. }
  31804. return AnaglyphArcRotateCamera;
  31805. })(BABYLON.ArcRotateCamera);
  31806. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  31807. var AnaglyphGamepadCamera = (function (_super) {
  31808. __extends(AnaglyphGamepadCamera, _super);
  31809. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  31810. _super.call(this, name, position, scene);
  31811. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  31812. }
  31813. return AnaglyphGamepadCamera;
  31814. })(BABYLON.GamepadCamera);
  31815. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  31816. var StereoscopicFreeCamera = (function (_super) {
  31817. __extends(StereoscopicFreeCamera, _super);
  31818. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  31819. _super.call(this, name, position, scene);
  31820. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  31821. }
  31822. return StereoscopicFreeCamera;
  31823. })(BABYLON.FreeCamera);
  31824. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  31825. var StereoscopicArcRotateCamera = (function (_super) {
  31826. __extends(StereoscopicArcRotateCamera, _super);
  31827. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  31828. _super.call(this, name, alpha, beta, radius, target, scene);
  31829. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  31830. }
  31831. return StereoscopicArcRotateCamera;
  31832. })(BABYLON.ArcRotateCamera);
  31833. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  31834. var StereoscopicGamepadCamera = (function (_super) {
  31835. __extends(StereoscopicGamepadCamera, _super);
  31836. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  31837. _super.call(this, name, position, scene);
  31838. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  31839. }
  31840. return StereoscopicGamepadCamera;
  31841. })(BABYLON.GamepadCamera);
  31842. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  31843. })(BABYLON || (BABYLON = {}));
  31844. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  31845. 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 vec3 skyColor;\r\nuniform vec3 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\tvec3 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = vec4(c, 1);\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\nuniform vec4 vSpecularColor;\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\nuniform vec3 vLightSpecular0;\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\nuniform vec3 vLightSpecular1;\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\nuniform vec3 vLightSpecular2;\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\nuniform vec3 vLightSpecular3;\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#ifdef SPECULAR\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\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)\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 visibility;\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)\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 1.0 - ChebychevInequality(moments, depth.z, bias);\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\tvec3 specular;\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\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\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., vSpecularColor.a));\r\n\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n\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) {\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\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\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n\tresult.specular = vec3(0.);\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) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\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\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\tresult.specular = specComp * specularColor;\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 VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\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\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\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\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\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\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\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\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\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\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\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\tspecularBase += info.specular * shadow;\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\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).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\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\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\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\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\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\tvec3 finalSpecular = specularBase * specularColor;\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\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}","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#ifdef SPECULAR\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#ifdef SPECULAR\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}","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\nuniform vec4 vSpecularColor;\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\nuniform vec3 vLightSpecular0;\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\nuniform vec3 vLightSpecular1;\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\nuniform vec3 vLightSpecular2;\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\nuniform vec3 vLightSpecular3;\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#ifdef SPECULAR\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\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\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\tresult[1] = specComp * specularColor;\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\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\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\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\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\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\tresult[1] = specComp * specularColor;\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 VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\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\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\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\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\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\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\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\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\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\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\tspecularBase += info[1] * shadow;\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\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\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\tvec3 finalSpecular = specularBase * specularColor;\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#ifdef SPECULAR\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#ifdef SPECULAR\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}","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}","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}"};
  31846. 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(e){var o=[];e.subMeshes&&(o=e.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 i=e.geometry?e.geometry.id:null;return{uniqueId:e.uniqueId,id:e.id,name:e.name,geometryId:i,sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:e.worldMatrixFromCache.asArray(),subMeshes:o,checkCollisions:e.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 t(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 t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},t.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},t.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b)},t.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},t.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b)},t.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},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b)},t.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},t.prototype.clone=function(){return new t(this.r,this.g,this.b)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},t.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2])},t.FromInts=function(i,o,n){return new t(i/255,o/255,n/255)},t.Lerp=function(i,o,n){var r=i.r+(o.r-i.r)*n,s=i.g+(o.g-i.g)*n,e=i.b+(o.b-i.b)*n;return new t(r,s,e)},t.Red=function(){return new t(1,0,0)},t.Green=function(){return new t(0,1,0)},t.Blue=function(){return new t(0,0,1)},t.Black=function(){return new t(0,0,0)},t.White=function(){return new t(1,1,1)},t.Purple=function(){return new t(.5,0,.5)},t.Magenta=function(){return new t(1,0,1)},t.Yellow=function(){return new t(1,1,0)},t.Gray=function(){return new t(.5,.5,.5)},t}();t.Color3=i;var o=function(){function t(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.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},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.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},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.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},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.Lerp=function(i,o,n){var r=new t(0,0,0,0);return t.LerpToRef(i,o,n,r),r},t.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},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.FromInts=function(i,o,n,r){return new t(i/255,o/255,n/255,r/255)},t}();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.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(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var u=i.TransformCoordinates(o,h),l=o.x*h.m[3]+o.y*h.m[7]+o.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(l,1)&&(u=u.scale(1/l)),u},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(t,o,n){var r,s,e,a=i.Normalize(t),h=(i.Normalize(o),i.Normalize(n)),u=f.X,l=f.Y,m=(f.Z,0),x=0,y=0,c=0,p=0,z=0,M=0,w=-1,I=(Math.PI,0),d=0;0==h.z?z=1:0==h.x?c=1:(M=h.z/h.x,c=-M*Math.sqrt(1/(1+M*M)),z=Math.sqrt(1/(1+M*M))),s=new i(c,p,z),e=i.Cross(h,s),r=i.Cross(a,s),i.Dot(h,r)<0&&(w=1),d=i.Dot(a,s),y=Math.acos(d)*w,i.Dot(s,u)<0&&(y=Math.PI+y,s=s.scaleInPlace(-1),e=e.scaleInPlace(-1),I++);var D,S;return c=0,p=0,z=0,w=-1,0==h.z?c=1:(M=s.z/s.x,c=-M*Math.sqrt(1/(1+M*M)),z=Math.sqrt(1/(1+M*M))),D=new i(c,p,z),S=i.Cross(D,s),r=i.Cross(h,D),i.Dot(s,r)<0&&(w=1),d=i.Dot(h,D),x=Math.acos(d)*w,i.Dot(S,l)<0&&(x=Math.PI+x,S=S.scaleInPlace(-1),D=D.scaleInPlace(-1),I++),w=-1,r=i.Cross(u,s),i.Dot(r,l)<0&&(w=1),d=i.Dot(s,u),m=-Math.acos(d)*w,0>d&&2>I&&(m=Math.PI+m),new i(x,m,y)},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.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,I=u*p-f*x,d=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*I+h*d),g=s*M-e*I+h*D,T=-(s*w-e*d+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,A=e*c-a*y,F=s*p-h*x,P=s*c-a*x,C=s*y-e*x,L=a*f-h*m,q=e*f-h*l,E=e*m-a*l,Z=s*f-h*u,N=s*m-a*u,V=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*I+r*d)*R,t.m[9]=-(i*M-o*I+r*D)*R,t.m[13]=(i*w-o*d+n*D)*R,t.m[2]=(o*_-n*b+r*A)*R,t.m[6]=-(i*_-n*F+r*P)*R,t.m[10]=(i*b-o*F+r*C)*R,t.m[14]=-(i*A-o*P+n*C)*R,t.m[3]=-(o*L-n*q+r*E)*R,t.m[7]=(i*L-n*Z+r*N)*R,t.m[11]=-(i*q-o*Z+r*V)*R,t.m[15]=(i*E-o*N+n*V)*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],I=t.m[1],d=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],A=t.m[11],F=t.m[12],P=t.m[13],C=t.m[14],L=t.m[15];return i[o]=n*w+r*S+s*R+e*F,i[o+1]=n*I+r*v+s*_+e*P,i[o+2]=n*d+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*A+e*L,i[o+4]=a*w+h*S+u*R+l*F,i[o+5]=a*I+h*v+u*_+l*P,i[o+6]=a*d+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*A+l*L,i[o+8]=m*w+f*S+x*R+y*F,i[o+9]=m*I+f*v+x*_+y*P,i[o+10]=m*d+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*A+y*L,i[o+12]=c*w+p*S+z*R+M*F,i[o+13]=c*I+p*v+z*_+M*P,i[o+14]=c*d+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*A+M*L,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)))));var 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]);\n\n},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.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),I=SIMD.float32x4(0,1,0,0),d=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(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,8,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,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.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[10]+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=0,n=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{var r=1/this.direction.x,s=(t.x-this.origin.x)*r,e=(i.x-this.origin.x)*r;if(e===-(1/0)&&(e=1/0),s>e){var a=s;s=e,e=a}if(o=Math.max(s,o),n=Math.min(e,n),o>n)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(r=1/this.direction.y,s=(t.y-this.origin.y)*r,e=(i.y-this.origin.y)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)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(r=1/this.direction.z,s=(t.z-this.origin.z)*r,e=(i.z-this.origin.z)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)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 t(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 t.prototype.getCurve=function(){return this._curve},t.prototype.getTangents=function(){return this._tangents},t.prototype.getNormals=function(){return this._normals},t.prototype.getBinormals=function(){return this._binormals},t.prototype.getDistances=function(){return this._distances},t.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},t.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,l=1;i>l;l++)s=this._getLastNonNullVector(l),i-1>l&&(e=this._getFirstNonNullVector(l),this._tangents[l]=s.add(e),this._tangents[l].normalize()),this._distances[l]=this._distances[l-1]+s.length(),a=this._tangents[l],h=this._normals[l-1],u=this._binormals[l-1],this._normals[l]=r.Cross(u,a),this._normals[l].normalize(),this._binormals[l]=r.Cross(a,this._normals[l]),this._binormals[l].normalize()},t.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},t.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},t.prototype._normalVector=function(t,i,o){var n;if(void 0===o||null===o){var s;1!==i.y?s=new r(0,-1,0):1!==i.x?s=new r(1,0,0):1!==i.z&&(s=new r(0,0,1)),n=r.Cross(i,s)}else n=r.Cross(i,o),r.CrossToRef(n,i,n);return n.normalize(),n},t}();t.Path3D=w;var I=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=I;var d=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=d;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={}));";
  31847. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  31848. module.exports = BABYLON;
  31849. };