babylon.2.2.max.js 1.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  680. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  681. var m0 = SIMD.float32x4.load(transformation.m, 0);
  682. var m1 = SIMD.float32x4.load(transformation.m, 4);
  683. var m2 = SIMD.float32x4.load(transformation.m, 8);
  684. var m3 = SIMD.float32x4.load(transformation.m, 12);
  685. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  686. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  687. SIMD.float32x4.storeXYZ(result._data, 0, r);
  688. };
  689. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  690. var v0 = SIMD.float32x4.splat(x);
  691. var v1 = SIMD.float32x4.splat(y);
  692. var v2 = SIMD.float32x4.splat(z);
  693. var m0 = SIMD.float32x4.load(transformation.m, 0);
  694. var m1 = SIMD.float32x4.load(transformation.m, 4);
  695. var m2 = SIMD.float32x4.load(transformation.m, 8);
  696. var m3 = SIMD.float32x4.load(transformation.m, 12);
  697. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  698. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  699. SIMD.float32x4.storeXYZ(result._data, 0, r);
  700. };
  701. Vector3.TransformNormal = function (vector, transformation) {
  702. var result = Vector3.Zero();
  703. Vector3.TransformNormalToRef(vector, transformation, result);
  704. return result;
  705. };
  706. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  707. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  708. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  709. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  710. };
  711. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  712. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  713. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  714. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  715. };
  716. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  717. var squared = amount * amount;
  718. var cubed = amount * squared;
  719. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  720. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  721. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  722. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  723. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  724. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  725. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  726. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  727. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  728. return new Vector3(x, y, z);
  729. };
  730. Vector3.Clamp = function (value, min, max) {
  731. var x = value.x;
  732. x = (x > max.x) ? max.x : x;
  733. x = (x < min.x) ? min.x : x;
  734. var y = value.y;
  735. y = (y > max.y) ? max.y : y;
  736. y = (y < min.y) ? min.y : y;
  737. var z = value.z;
  738. z = (z > max.z) ? max.z : z;
  739. z = (z < min.z) ? min.z : z;
  740. return new Vector3(x, y, z);
  741. };
  742. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  743. var squared = amount * amount;
  744. var cubed = amount * squared;
  745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  747. var part3 = (cubed - (2.0 * squared)) + amount;
  748. var part4 = cubed - squared;
  749. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  750. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  751. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  752. return new Vector3(x, y, z);
  753. };
  754. Vector3.Lerp = function (start, end, amount) {
  755. var x = start.x + ((end.x - start.x) * amount);
  756. var y = start.y + ((end.y - start.y) * amount);
  757. var z = start.z + ((end.z - start.z) * amount);
  758. return new Vector3(x, y, z);
  759. };
  760. Vector3.Dot = function (left, right) {
  761. return (left.x * right.x + left.y * right.y + left.z * right.z);
  762. };
  763. Vector3.Cross = function (left, right) {
  764. var result = Vector3.Zero();
  765. Vector3.CrossToRef(left, right, result);
  766. return result;
  767. };
  768. Vector3.CrossToRef = function (left, right, result) {
  769. result.x = left.y * right.z - left.z * right.y;
  770. result.y = left.z * right.x - left.x * right.z;
  771. result.z = left.x * right.y - left.y * right.x;
  772. };
  773. Vector3.Normalize = function (vector) {
  774. var result = Vector3.Zero();
  775. Vector3.NormalizeToRef(vector, result);
  776. return result;
  777. };
  778. Vector3.NormalizeToRef = function (vector, result) {
  779. result.copyFrom(vector);
  780. result.normalize();
  781. };
  782. Vector3.Project = function (vector, world, transform, viewport) {
  783. var cw = viewport.width;
  784. var ch = viewport.height;
  785. var cx = viewport.x;
  786. var cy = viewport.y;
  787. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  788. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  789. return Vector3.TransformCoordinates(vector, finalMatrix);
  790. };
  791. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  792. var matrix = world.multiply(transform);
  793. matrix.invert();
  794. source.x = source.x / viewportWidth * 2 - 1;
  795. source.y = -(source.y / viewportHeight * 2 - 1);
  796. var vector = Vector3.TransformCoordinates(source, matrix);
  797. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  798. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  799. vector = vector.scale(1.0 / num);
  800. }
  801. return vector;
  802. };
  803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  804. var matrix = world.multiply(view).multiply(projection);
  805. matrix.invert();
  806. source.x = source.x / viewportWidth * 2 - 1;
  807. source.y = -(source.y / viewportHeight * 2 - 1);
  808. var vector = Vector3.TransformCoordinates(source, matrix);
  809. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  810. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  811. vector = vector.scale(1.0 / num);
  812. }
  813. return vector;
  814. };
  815. Vector3.Minimize = function (left, right) {
  816. var min = left.clone();
  817. min.MinimizeInPlace(right);
  818. return min;
  819. };
  820. Vector3.Maximize = function (left, right) {
  821. var max = left.clone();
  822. max.MaximizeInPlace(right);
  823. return max;
  824. };
  825. Vector3.Distance = function (value1, value2) {
  826. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  827. };
  828. Vector3.DistanceSquared = function (value1, value2) {
  829. var x = value1.x - value2.x;
  830. var y = value1.y - value2.y;
  831. var z = value1.z - value2.z;
  832. return (x * x) + (y * y) + (z * z);
  833. };
  834. Vector3.Center = function (value1, value2) {
  835. var center = value1.add(value2);
  836. center.scaleInPlace(0.5);
  837. return center;
  838. };
  839. /**
  840. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  841. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  842. * to something in order to rotate it from its local system to the given target system.
  843. */
  844. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  845. var u = Vector3.Normalize(axis1);
  846. var w = Vector3.Normalize(axis3);
  847. // world axis
  848. var X = Axis.X;
  849. var Y = Axis.Y;
  850. // equation unknowns and vars
  851. var yaw = 0.0;
  852. var pitch = 0.0;
  853. var roll = 0.0;
  854. var x = 0.0;
  855. var y = 0.0;
  856. var z = 0.0;
  857. var t = 0.0;
  858. var sign = -1.0;
  859. var nbRevert = 0;
  860. var cross;
  861. var dot = 0.0;
  862. // step 1 : rotation around w
  863. // Rv3(u) = u1, and u1 belongs to plane xOz
  864. // Rv3(w) = w1 = w invariant
  865. var u1;
  866. var v1;
  867. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  868. z = 1.0;
  869. }
  870. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  871. x = 1.0;
  872. }
  873. else {
  874. t = w.z / w.x;
  875. x = -t * Math.sqrt(1 / (1 + t * t));
  876. z = Math.sqrt(1 / (1 + t * t));
  877. }
  878. u1 = new Vector3(x, y, z);
  879. u1.normalize();
  880. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  881. v1.normalize();
  882. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  883. cross.normalize();
  884. if (Vector3.Dot(w, cross) < 0) {
  885. sign = 1.0;
  886. }
  887. dot = Vector3.Dot(u, u1);
  888. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  889. roll = Math.acos(dot) * sign;
  890. if (Vector3.Dot(u1, X) < 0) {
  891. roll = Math.PI + roll;
  892. u1 = u1.scaleInPlace(-1);
  893. v1 = v1.scaleInPlace(-1);
  894. nbRevert++;
  895. }
  896. // step 2 : rotate around u1
  897. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  898. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  899. var w2;
  900. var v2;
  901. x = 0.0;
  902. y = 0.0;
  903. z = 0.0;
  904. sign = -1;
  905. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  906. x = 1.0;
  907. }
  908. else {
  909. t = u1.z / u1.x;
  910. x = -t * Math.sqrt(1 / (1 + t * t));
  911. z = Math.sqrt(1 / (1 + t * t));
  912. }
  913. w2 = new Vector3(x, y, z);
  914. w2.normalize();
  915. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  916. v2.normalize();
  917. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  918. cross.normalize();
  919. if (Vector3.Dot(u1, cross) < 0) {
  920. sign = 1.0;
  921. }
  922. dot = Vector3.Dot(w, w2);
  923. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  924. pitch = Math.acos(dot) * sign;
  925. if (Vector3.Dot(v2, Y) < 0) {
  926. pitch = Math.PI + pitch;
  927. v2 = v2.scaleInPlace(-1);
  928. w2 = w2.scaleInPlace(-1);
  929. nbRevert++;
  930. }
  931. // step 3 : rotate around v2
  932. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  933. sign = -1;
  934. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  935. cross.normalize();
  936. if (Vector3.Dot(cross, Y) < 0) {
  937. sign = 1.0;
  938. }
  939. dot = Vector3.Dot(u1, X);
  940. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  941. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  942. if (dot < 0 && nbRevert < 2) {
  943. yaw = Math.PI + yaw;
  944. }
  945. return new Vector3(pitch, yaw, roll);
  946. };
  947. return Vector3;
  948. })();
  949. BABYLON.Vector3 = Vector3;
  950. //Vector4 class created for EulerAngle class conversion to Quaternion
  951. var Vector4 = (function () {
  952. function Vector4(x, y, z, w) {
  953. this.x = x;
  954. this.y = y;
  955. this.z = z;
  956. this.w = w;
  957. }
  958. Vector4.prototype.toString = function () {
  959. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  960. };
  961. // Operators
  962. Vector4.prototype.asArray = function () {
  963. var result = [];
  964. this.toArray(result, 0);
  965. return result;
  966. };
  967. Vector4.prototype.toArray = function (array, index) {
  968. if (index === undefined) {
  969. index = 0;
  970. }
  971. array[index] = this.x;
  972. array[index + 1] = this.y;
  973. array[index + 2] = this.z;
  974. array[index + 3] = this.w;
  975. return this;
  976. };
  977. Vector4.prototype.addInPlace = function (otherVector) {
  978. this.x += otherVector.x;
  979. this.y += otherVector.y;
  980. this.z += otherVector.z;
  981. this.w += otherVector.w;
  982. return this;
  983. };
  984. Vector4.prototype.add = function (otherVector) {
  985. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  986. };
  987. Vector4.prototype.addToRef = function (otherVector, result) {
  988. result.x = this.x + otherVector.x;
  989. result.y = this.y + otherVector.y;
  990. result.z = this.z + otherVector.z;
  991. result.w = this.w + otherVector.w;
  992. return this;
  993. };
  994. Vector4.prototype.subtractInPlace = function (otherVector) {
  995. this.x -= otherVector.x;
  996. this.y -= otherVector.y;
  997. this.z -= otherVector.z;
  998. this.w -= otherVector.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.subtract = function (otherVector) {
  1002. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1003. };
  1004. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1005. result.x = this.x - otherVector.x;
  1006. result.y = this.y - otherVector.y;
  1007. result.z = this.z - otherVector.z;
  1008. result.w = this.w - otherVector.w;
  1009. return this;
  1010. };
  1011. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1012. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1013. };
  1014. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1015. result.x = this.x - x;
  1016. result.y = this.y - y;
  1017. result.z = this.z - z;
  1018. result.w = this.w - w;
  1019. return this;
  1020. };
  1021. Vector4.prototype.negate = function () {
  1022. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1023. };
  1024. Vector4.prototype.scaleInPlace = function (scale) {
  1025. this.x *= scale;
  1026. this.y *= scale;
  1027. this.z *= scale;
  1028. this.w *= scale;
  1029. return this;
  1030. };
  1031. Vector4.prototype.scale = function (scale) {
  1032. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1033. };
  1034. Vector4.prototype.scaleToRef = function (scale, result) {
  1035. result.x = this.x * scale;
  1036. result.y = this.y * scale;
  1037. result.z = this.z * scale;
  1038. result.w = this.w * scale;
  1039. };
  1040. Vector4.prototype.equals = function (otherVector) {
  1041. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1042. };
  1043. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1044. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1045. return otherVector
  1046. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1047. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1048. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1049. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1050. };
  1051. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1052. return this.x === x && this.y === y && this.z === z && this.w === w;
  1053. };
  1054. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1055. this.x *= otherVector.x;
  1056. this.y *= otherVector.y;
  1057. this.z *= otherVector.z;
  1058. this.w *= otherVector.w;
  1059. return this;
  1060. };
  1061. Vector4.prototype.multiply = function (otherVector) {
  1062. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1063. };
  1064. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1065. result.x = this.x * otherVector.x;
  1066. result.y = this.y * otherVector.y;
  1067. result.z = this.z * otherVector.z;
  1068. result.w = this.w * otherVector.w;
  1069. return this;
  1070. };
  1071. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1072. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1073. };
  1074. Vector4.prototype.divide = function (otherVector) {
  1075. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1076. };
  1077. Vector4.prototype.divideToRef = function (otherVector, result) {
  1078. result.x = this.x / otherVector.x;
  1079. result.y = this.y / otherVector.y;
  1080. result.z = this.z / otherVector.z;
  1081. result.w = this.w / otherVector.w;
  1082. return this;
  1083. };
  1084. Vector4.prototype.MinimizeInPlace = function (other) {
  1085. if (other.x < this.x)
  1086. this.x = other.x;
  1087. if (other.y < this.y)
  1088. this.y = other.y;
  1089. if (other.z < this.z)
  1090. this.z = other.z;
  1091. if (other.w < this.w)
  1092. this.w = other.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.MaximizeInPlace = function (other) {
  1096. if (other.x > this.x)
  1097. this.x = other.x;
  1098. if (other.y > this.y)
  1099. this.y = other.y;
  1100. if (other.z > this.z)
  1101. this.z = other.z;
  1102. if (other.w > this.w)
  1103. this.w = other.w;
  1104. return this;
  1105. };
  1106. // Properties
  1107. Vector4.prototype.length = function () {
  1108. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1109. };
  1110. Vector4.prototype.lengthSquared = function () {
  1111. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1112. };
  1113. // Methods
  1114. Vector4.prototype.normalize = function () {
  1115. var len = this.length();
  1116. if (len === 0)
  1117. return this;
  1118. var num = 1.0 / len;
  1119. this.x *= num;
  1120. this.y *= num;
  1121. this.z *= num;
  1122. this.w *= num;
  1123. return this;
  1124. };
  1125. Vector4.prototype.clone = function () {
  1126. return new Vector4(this.x, this.y, this.z, this.w);
  1127. };
  1128. Vector4.prototype.copyFrom = function (source) {
  1129. this.x = source.x;
  1130. this.y = source.y;
  1131. this.z = source.z;
  1132. this.w = source.w;
  1133. return this;
  1134. };
  1135. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1136. this.x = x;
  1137. this.y = y;
  1138. this.z = z;
  1139. this.w = w;
  1140. return this;
  1141. };
  1142. // Statics
  1143. Vector4.FromArray = function (array, offset) {
  1144. if (!offset) {
  1145. offset = 0;
  1146. }
  1147. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1148. };
  1149. Vector4.FromArrayToRef = function (array, offset, result) {
  1150. result.x = array[offset];
  1151. result.y = array[offset + 1];
  1152. result.z = array[offset + 2];
  1153. result.w = array[offset + 3];
  1154. };
  1155. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1156. result.x = array[offset];
  1157. result.y = array[offset + 1];
  1158. result.z = array[offset + 2];
  1159. result.w = array[offset + 3];
  1160. };
  1161. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1162. result.x = x;
  1163. result.y = y;
  1164. result.z = z;
  1165. result.w = w;
  1166. };
  1167. Vector4.Zero = function () {
  1168. return new Vector4(0, 0, 0, 0);
  1169. };
  1170. Vector4.Normalize = function (vector) {
  1171. var result = Vector4.Zero();
  1172. Vector4.NormalizeToRef(vector, result);
  1173. return result;
  1174. };
  1175. Vector4.NormalizeToRef = function (vector, result) {
  1176. result.copyFrom(vector);
  1177. result.normalize();
  1178. };
  1179. Vector4.Minimize = function (left, right) {
  1180. var min = left.clone();
  1181. min.MinimizeInPlace(right);
  1182. return min;
  1183. };
  1184. Vector4.Maximize = function (left, right) {
  1185. var max = left.clone();
  1186. max.MaximizeInPlace(right);
  1187. return max;
  1188. };
  1189. Vector4.Distance = function (value1, value2) {
  1190. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1191. };
  1192. Vector4.DistanceSquared = function (value1, value2) {
  1193. var x = value1.x - value2.x;
  1194. var y = value1.y - value2.y;
  1195. var z = value1.z - value2.z;
  1196. var w = value1.w - value2.w;
  1197. return (x * x) + (y * y) + (z * z) + (w * w);
  1198. };
  1199. Vector4.Center = function (value1, value2) {
  1200. var center = value1.add(value2);
  1201. center.scaleInPlace(0.5);
  1202. return center;
  1203. };
  1204. return Vector4;
  1205. })();
  1206. BABYLON.Vector4 = Vector4;
  1207. var Quaternion = (function () {
  1208. function Quaternion(x, y, z, w) {
  1209. if (x === void 0) { x = 0; }
  1210. if (y === void 0) { y = 0; }
  1211. if (z === void 0) { z = 0; }
  1212. if (w === void 0) { w = 1; }
  1213. this.x = x;
  1214. this.y = y;
  1215. this.z = z;
  1216. this.w = w;
  1217. }
  1218. Quaternion.prototype.toString = function () {
  1219. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1220. };
  1221. Quaternion.prototype.asArray = function () {
  1222. return [this.x, this.y, this.z, this.w];
  1223. };
  1224. Quaternion.prototype.equals = function (otherQuaternion) {
  1225. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1226. };
  1227. Quaternion.prototype.clone = function () {
  1228. return new Quaternion(this.x, this.y, this.z, this.w);
  1229. };
  1230. Quaternion.prototype.copyFrom = function (other) {
  1231. this.x = other.x;
  1232. this.y = other.y;
  1233. this.z = other.z;
  1234. this.w = other.w;
  1235. return this;
  1236. };
  1237. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1238. this.x = x;
  1239. this.y = y;
  1240. this.z = z;
  1241. this.w = w;
  1242. return this;
  1243. };
  1244. Quaternion.prototype.add = function (other) {
  1245. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1246. };
  1247. Quaternion.prototype.subtract = function (other) {
  1248. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1249. };
  1250. Quaternion.prototype.scale = function (value) {
  1251. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1252. };
  1253. Quaternion.prototype.multiply = function (q1) {
  1254. var result = new Quaternion(0, 0, 0, 1.0);
  1255. this.multiplyToRef(q1, result);
  1256. return result;
  1257. };
  1258. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1259. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1260. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1261. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1262. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1263. result.copyFromFloats(x, y, z, w);
  1264. return this;
  1265. };
  1266. Quaternion.prototype.length = function () {
  1267. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1268. };
  1269. Quaternion.prototype.normalize = function () {
  1270. var length = 1.0 / this.length();
  1271. this.x *= length;
  1272. this.y *= length;
  1273. this.z *= length;
  1274. this.w *= length;
  1275. return this;
  1276. };
  1277. Quaternion.prototype.toEulerAngles = function () {
  1278. var result = Vector3.Zero();
  1279. this.toEulerAnglesToRef(result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1283. //result is an EulerAngles in the in the z-x-z convention
  1284. var qx = this.x;
  1285. var qy = this.y;
  1286. var qz = this.z;
  1287. var qw = this.w;
  1288. var qxy = qx * qy;
  1289. var qxz = qx * qz;
  1290. var qwy = qw * qy;
  1291. var qwz = qw * qz;
  1292. var qwx = qw * qx;
  1293. var qyz = qy * qz;
  1294. var sqx = qx * qx;
  1295. var sqy = qy * qy;
  1296. var determinant = sqx + sqy;
  1297. if (determinant !== 0.000 && determinant !== 1.000) {
  1298. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1299. result.y = Math.acos(1 - 2 * determinant);
  1300. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1301. }
  1302. else {
  1303. if (determinant === 0.0) {
  1304. result.x = 0.0;
  1305. result.y = 0.0;
  1306. 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)
  1307. }
  1308. else {
  1309. 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)
  1310. result.y = Math.PI;
  1311. result.z = 0.0;
  1312. }
  1313. }
  1314. return this;
  1315. };
  1316. Quaternion.prototype.toRotationMatrix = function (result) {
  1317. var xx = this.x * this.x;
  1318. var yy = this.y * this.y;
  1319. var zz = this.z * this.z;
  1320. var xy = this.x * this.y;
  1321. var zw = this.z * this.w;
  1322. var zx = this.z * this.x;
  1323. var yw = this.y * this.w;
  1324. var yz = this.y * this.z;
  1325. var xw = this.x * this.w;
  1326. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1327. result.m[1] = 2.0 * (xy + zw);
  1328. result.m[2] = 2.0 * (zx - yw);
  1329. result.m[3] = 0;
  1330. result.m[4] = 2.0 * (xy - zw);
  1331. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1332. result.m[6] = 2.0 * (yz + xw);
  1333. result.m[7] = 0;
  1334. result.m[8] = 2.0 * (zx + yw);
  1335. result.m[9] = 2.0 * (yz - xw);
  1336. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1337. result.m[11] = 0;
  1338. result.m[12] = 0;
  1339. result.m[13] = 0;
  1340. result.m[14] = 0;
  1341. result.m[15] = 1.0;
  1342. return this;
  1343. };
  1344. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1345. Quaternion.FromRotationMatrixToRef(matrix, this);
  1346. return this;
  1347. };
  1348. // Statics
  1349. Quaternion.FromRotationMatrix = function (matrix) {
  1350. var result = new Quaternion();
  1351. Quaternion.FromRotationMatrixToRef(matrix, result);
  1352. return result;
  1353. };
  1354. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1355. var data = matrix.m;
  1356. var m11 = data[0], m12 = data[4], m13 = data[8];
  1357. var m21 = data[1], m22 = data[5], m23 = data[9];
  1358. var m31 = data[2], m32 = data[6], m33 = data[10];
  1359. var trace = m11 + m22 + m33;
  1360. var s;
  1361. if (trace > 0) {
  1362. s = 0.5 / Math.sqrt(trace + 1.0);
  1363. result.w = 0.25 / s;
  1364. result.x = (m32 - m23) * s;
  1365. result.y = (m13 - m31) * s;
  1366. result.z = (m21 - m12) * s;
  1367. }
  1368. else if (m11 > m22 && m11 > m33) {
  1369. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1370. result.w = (m32 - m23) / s;
  1371. result.x = 0.25 * s;
  1372. result.y = (m12 + m21) / s;
  1373. result.z = (m13 + m31) / s;
  1374. }
  1375. else if (m22 > m33) {
  1376. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1377. result.w = (m13 - m31) / s;
  1378. result.x = (m12 + m21) / s;
  1379. result.y = 0.25 * s;
  1380. result.z = (m23 + m32) / s;
  1381. }
  1382. else {
  1383. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1384. result.w = (m21 - m12) / s;
  1385. result.x = (m13 + m31) / s;
  1386. result.y = (m23 + m32) / s;
  1387. result.z = 0.25 * s;
  1388. }
  1389. };
  1390. Quaternion.Inverse = function (q) {
  1391. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1392. };
  1393. Quaternion.Identity = function () {
  1394. return new Quaternion(0, 0, 0, 1);
  1395. };
  1396. Quaternion.RotationAxis = function (axis, angle) {
  1397. var result = new Quaternion();
  1398. var sin = Math.sin(angle / 2);
  1399. result.w = Math.cos(angle / 2);
  1400. result.x = axis.x * sin;
  1401. result.y = axis.y * sin;
  1402. result.z = axis.z * sin;
  1403. return result;
  1404. };
  1405. Quaternion.FromArray = function (array, offset) {
  1406. if (!offset) {
  1407. offset = 0;
  1408. }
  1409. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1410. };
  1411. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1412. var result = new Quaternion();
  1413. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1414. return result;
  1415. };
  1416. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1417. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1418. var halfRoll = roll * 0.5;
  1419. var halfPitch = pitch * 0.5;
  1420. var halfYaw = yaw * 0.5;
  1421. var sinRoll = Math.sin(halfRoll);
  1422. var cosRoll = Math.cos(halfRoll);
  1423. var sinPitch = Math.sin(halfPitch);
  1424. var cosPitch = Math.cos(halfPitch);
  1425. var sinYaw = Math.sin(halfYaw);
  1426. var cosYaw = Math.cos(halfYaw);
  1427. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1428. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1429. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1430. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1431. };
  1432. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1433. var result = new Quaternion();
  1434. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1435. return result;
  1436. };
  1437. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1438. // Produces a quaternion from Euler angles in the z-x-z orientation
  1439. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1440. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1441. var halfBeta = beta * 0.5;
  1442. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1443. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1444. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1445. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1446. };
  1447. Quaternion.Slerp = function (left, right, amount) {
  1448. var num2;
  1449. var num3;
  1450. var num = amount;
  1451. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1452. var flag = false;
  1453. if (num4 < 0) {
  1454. flag = true;
  1455. num4 = -num4;
  1456. }
  1457. if (num4 > 0.999999) {
  1458. num3 = 1 - num;
  1459. num2 = flag ? -num : num;
  1460. }
  1461. else {
  1462. var num5 = Math.acos(num4);
  1463. var num6 = (1.0 / Math.sin(num5));
  1464. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1465. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1466. }
  1467. 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));
  1468. };
  1469. return Quaternion;
  1470. })();
  1471. BABYLON.Quaternion = Quaternion;
  1472. var Matrix = (function () {
  1473. function Matrix() {
  1474. this.m = new Float32Array(16);
  1475. }
  1476. // Properties
  1477. Matrix.prototype.isIdentity = function () {
  1478. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1479. return false;
  1480. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1481. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1482. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1483. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1484. return false;
  1485. return true;
  1486. };
  1487. Matrix.prototype.determinant = function () {
  1488. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1489. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1490. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1491. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1492. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1493. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1494. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1495. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1496. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1497. };
  1498. // Methods
  1499. Matrix.prototype.toArray = function () {
  1500. return this.m;
  1501. };
  1502. Matrix.prototype.asArray = function () {
  1503. return this.toArray();
  1504. };
  1505. Matrix.prototype.invert = function () {
  1506. this.invertToRef(this);
  1507. return this;
  1508. };
  1509. Matrix.prototype.reset = function () {
  1510. for (var index = 0; index < 16; index++) {
  1511. this.m[index] = 0;
  1512. }
  1513. return this;
  1514. };
  1515. Matrix.prototype.add = function (other) {
  1516. var result = new Matrix();
  1517. this.addToRef(other, result);
  1518. return result;
  1519. };
  1520. Matrix.prototype.addToRef = function (other, result) {
  1521. for (var index = 0; index < 16; index++) {
  1522. result.m[index] = this.m[index] + other.m[index];
  1523. }
  1524. return this;
  1525. };
  1526. Matrix.prototype.addToSelf = function (other) {
  1527. for (var index = 0; index < 16; index++) {
  1528. this.m[index] += other.m[index];
  1529. }
  1530. return this;
  1531. };
  1532. Matrix.prototype.invertToRef = function (other) {
  1533. var l1 = this.m[0];
  1534. var l2 = this.m[1];
  1535. var l3 = this.m[2];
  1536. var l4 = this.m[3];
  1537. var l5 = this.m[4];
  1538. var l6 = this.m[5];
  1539. var l7 = this.m[6];
  1540. var l8 = this.m[7];
  1541. var l9 = this.m[8];
  1542. var l10 = this.m[9];
  1543. var l11 = this.m[10];
  1544. var l12 = this.m[11];
  1545. var l13 = this.m[12];
  1546. var l14 = this.m[13];
  1547. var l15 = this.m[14];
  1548. var l16 = this.m[15];
  1549. var l17 = (l11 * l16) - (l12 * l15);
  1550. var l18 = (l10 * l16) - (l12 * l14);
  1551. var l19 = (l10 * l15) - (l11 * l14);
  1552. var l20 = (l9 * l16) - (l12 * l13);
  1553. var l21 = (l9 * l15) - (l11 * l13);
  1554. var l22 = (l9 * l14) - (l10 * l13);
  1555. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1556. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1557. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1558. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1559. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1560. var l28 = (l7 * l16) - (l8 * l15);
  1561. var l29 = (l6 * l16) - (l8 * l14);
  1562. var l30 = (l6 * l15) - (l7 * l14);
  1563. var l31 = (l5 * l16) - (l8 * l13);
  1564. var l32 = (l5 * l15) - (l7 * l13);
  1565. var l33 = (l5 * l14) - (l6 * l13);
  1566. var l34 = (l7 * l12) - (l8 * l11);
  1567. var l35 = (l6 * l12) - (l8 * l10);
  1568. var l36 = (l6 * l11) - (l7 * l10);
  1569. var l37 = (l5 * l12) - (l8 * l9);
  1570. var l38 = (l5 * l11) - (l7 * l9);
  1571. var l39 = (l5 * l10) - (l6 * l9);
  1572. other.m[0] = l23 * l27;
  1573. other.m[4] = l24 * l27;
  1574. other.m[8] = l25 * l27;
  1575. other.m[12] = l26 * l27;
  1576. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1577. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1578. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1579. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1580. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1581. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1582. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1583. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1584. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1585. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1586. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1587. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1588. return this;
  1589. };
  1590. Matrix.prototype.invertToRefSIMD = function (other) {
  1591. var src = this.m;
  1592. var dest = other.m;
  1593. var row0, row1, row2, row3;
  1594. var tmp1;
  1595. var minor0, minor1, minor2, minor3;
  1596. var det;
  1597. // Load the 4 rows
  1598. var src0 = SIMD.float32x4.load(src, 0);
  1599. var src1 = SIMD.float32x4.load(src, 4);
  1600. var src2 = SIMD.float32x4.load(src, 8);
  1601. var src3 = SIMD.float32x4.load(src, 12);
  1602. // Transpose the source matrix. Sort of. Not a true transpose operation
  1603. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1604. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1605. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1606. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1607. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1608. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1609. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1610. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1611. // This is a true transposition, but it will lead to an incorrect result
  1612. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1613. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1614. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1615. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1616. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1617. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1618. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1619. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1620. // ----
  1621. tmp1 = SIMD.float32x4.mul(row2, row3);
  1622. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1623. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1624. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1625. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1626. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1627. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1628. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1629. // ----
  1630. tmp1 = SIMD.float32x4.mul(row1, row2);
  1631. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1632. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1633. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1634. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1635. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1636. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1637. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1638. // ----
  1639. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1640. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1641. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1642. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1643. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1644. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1645. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1646. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1647. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1648. // ----
  1649. tmp1 = SIMD.float32x4.mul(row0, row1);
  1650. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1651. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1652. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1653. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1654. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1655. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1656. // ----
  1657. tmp1 = SIMD.float32x4.mul(row0, row3);
  1658. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1659. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1660. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1661. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1662. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1663. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1664. // ----
  1665. tmp1 = SIMD.float32x4.mul(row0, row2);
  1666. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1667. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1668. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1669. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1670. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1671. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1672. // Compute determinant
  1673. det = SIMD.float32x4.mul(row0, minor0);
  1674. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1675. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1676. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1677. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1678. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1679. // These shuffles aren't necessary if the faulty transposition is done
  1680. // up at the top of this function.
  1681. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1682. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1683. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1684. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1685. // Compute final values by multiplying with 1/det
  1686. minor0 = SIMD.float32x4.mul(det, minor0);
  1687. minor1 = SIMD.float32x4.mul(det, minor1);
  1688. minor2 = SIMD.float32x4.mul(det, minor2);
  1689. minor3 = SIMD.float32x4.mul(det, minor3);
  1690. SIMD.float32x4.store(dest, 0, minor0);
  1691. SIMD.float32x4.store(dest, 4, minor1);
  1692. SIMD.float32x4.store(dest, 8, minor2);
  1693. SIMD.float32x4.store(dest, 12, minor3);
  1694. return this;
  1695. };
  1696. Matrix.prototype.setTranslation = function (vector3) {
  1697. this.m[12] = vector3.x;
  1698. this.m[13] = vector3.y;
  1699. this.m[14] = vector3.z;
  1700. return this;
  1701. };
  1702. Matrix.prototype.multiply = function (other) {
  1703. var result = new Matrix();
  1704. this.multiplyToRef(other, result);
  1705. return result;
  1706. };
  1707. Matrix.prototype.copyFrom = function (other) {
  1708. for (var index = 0; index < 16; index++) {
  1709. this.m[index] = other.m[index];
  1710. }
  1711. return this;
  1712. };
  1713. Matrix.prototype.copyToArray = function (array, offset) {
  1714. if (offset === void 0) { offset = 0; }
  1715. for (var index = 0; index < 16; index++) {
  1716. array[offset + index] = this.m[index];
  1717. }
  1718. return this;
  1719. };
  1720. Matrix.prototype.multiplyToRef = function (other, result) {
  1721. this.multiplyToArray(other, result.m, 0);
  1722. return this;
  1723. };
  1724. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1725. var tm0 = this.m[0];
  1726. var tm1 = this.m[1];
  1727. var tm2 = this.m[2];
  1728. var tm3 = this.m[3];
  1729. var tm4 = this.m[4];
  1730. var tm5 = this.m[5];
  1731. var tm6 = this.m[6];
  1732. var tm7 = this.m[7];
  1733. var tm8 = this.m[8];
  1734. var tm9 = this.m[9];
  1735. var tm10 = this.m[10];
  1736. var tm11 = this.m[11];
  1737. var tm12 = this.m[12];
  1738. var tm13 = this.m[13];
  1739. var tm14 = this.m[14];
  1740. var tm15 = this.m[15];
  1741. var om0 = other.m[0];
  1742. var om1 = other.m[1];
  1743. var om2 = other.m[2];
  1744. var om3 = other.m[3];
  1745. var om4 = other.m[4];
  1746. var om5 = other.m[5];
  1747. var om6 = other.m[6];
  1748. var om7 = other.m[7];
  1749. var om8 = other.m[8];
  1750. var om9 = other.m[9];
  1751. var om10 = other.m[10];
  1752. var om11 = other.m[11];
  1753. var om12 = other.m[12];
  1754. var om13 = other.m[13];
  1755. var om14 = other.m[14];
  1756. var om15 = other.m[15];
  1757. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1758. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1759. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1760. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1761. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1762. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1763. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1764. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1765. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1766. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1767. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1768. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1769. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1770. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1771. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1772. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1773. return this;
  1774. };
  1775. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1776. if (offset === void 0) { offset = 0; }
  1777. var tm = this.m;
  1778. var om = other.m;
  1779. var om0 = SIMD.float32x4.load(om, 0);
  1780. var om1 = SIMD.float32x4.load(om, 4);
  1781. var om2 = SIMD.float32x4.load(om, 8);
  1782. var om3 = SIMD.float32x4.load(om, 12);
  1783. var tm0 = SIMD.float32x4.load(tm, 0);
  1784. 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)))));
  1785. var tm1 = SIMD.float32x4.load(tm, 4);
  1786. 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)))));
  1787. var tm2 = SIMD.float32x4.load(tm, 8);
  1788. 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)))));
  1789. var tm3 = SIMD.float32x4.load(tm, 12);
  1790. 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)))));
  1791. };
  1792. Matrix.prototype.equals = function (value) {
  1793. return value &&
  1794. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1795. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1796. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1797. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1798. };
  1799. Matrix.prototype.clone = function () {
  1800. 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]);
  1801. };
  1802. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1803. translation.x = this.m[12];
  1804. translation.y = this.m[13];
  1805. translation.z = this.m[14];
  1806. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1807. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1808. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1809. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1810. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1811. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1812. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1813. rotation.x = 0;
  1814. rotation.y = 0;
  1815. rotation.z = 0;
  1816. rotation.w = 1;
  1817. return false;
  1818. }
  1819. 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);
  1820. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1821. return true;
  1822. };
  1823. // Statics
  1824. Matrix.FromArray = function (array, offset) {
  1825. var result = new Matrix();
  1826. if (!offset) {
  1827. offset = 0;
  1828. }
  1829. Matrix.FromArrayToRef(array, offset, result);
  1830. return result;
  1831. };
  1832. Matrix.FromArrayToRef = function (array, offset, result) {
  1833. for (var index = 0; index < 16; index++) {
  1834. result.m[index] = array[index + offset];
  1835. }
  1836. };
  1837. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1838. for (var index = 0; index < 16; index++) {
  1839. result.m[index] = array[index + offset] * scale;
  1840. }
  1841. };
  1842. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1843. result.m[0] = initialM11;
  1844. result.m[1] = initialM12;
  1845. result.m[2] = initialM13;
  1846. result.m[3] = initialM14;
  1847. result.m[4] = initialM21;
  1848. result.m[5] = initialM22;
  1849. result.m[6] = initialM23;
  1850. result.m[7] = initialM24;
  1851. result.m[8] = initialM31;
  1852. result.m[9] = initialM32;
  1853. result.m[10] = initialM33;
  1854. result.m[11] = initialM34;
  1855. result.m[12] = initialM41;
  1856. result.m[13] = initialM42;
  1857. result.m[14] = initialM43;
  1858. result.m[15] = initialM44;
  1859. };
  1860. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1861. var result = new Matrix();
  1862. result.m[0] = initialM11;
  1863. result.m[1] = initialM12;
  1864. result.m[2] = initialM13;
  1865. result.m[3] = initialM14;
  1866. result.m[4] = initialM21;
  1867. result.m[5] = initialM22;
  1868. result.m[6] = initialM23;
  1869. result.m[7] = initialM24;
  1870. result.m[8] = initialM31;
  1871. result.m[9] = initialM32;
  1872. result.m[10] = initialM33;
  1873. result.m[11] = initialM34;
  1874. result.m[12] = initialM41;
  1875. result.m[13] = initialM42;
  1876. result.m[14] = initialM43;
  1877. result.m[15] = initialM44;
  1878. return result;
  1879. };
  1880. Matrix.Compose = function (scale, rotation, translation) {
  1881. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1882. var rotationMatrix = Matrix.Identity();
  1883. rotation.toRotationMatrix(rotationMatrix);
  1884. result = result.multiply(rotationMatrix);
  1885. result.setTranslation(translation);
  1886. return result;
  1887. };
  1888. Matrix.Identity = function () {
  1889. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1890. };
  1891. Matrix.IdentityToRef = function (result) {
  1892. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1893. };
  1894. Matrix.Zero = function () {
  1895. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1896. };
  1897. Matrix.RotationX = function (angle) {
  1898. var result = new Matrix();
  1899. Matrix.RotationXToRef(angle, result);
  1900. return result;
  1901. };
  1902. Matrix.Invert = function (source) {
  1903. var result = new Matrix();
  1904. source.invertToRef(result);
  1905. return result;
  1906. };
  1907. Matrix.RotationXToRef = function (angle, result) {
  1908. var s = Math.sin(angle);
  1909. var c = Math.cos(angle);
  1910. result.m[0] = 1.0;
  1911. result.m[15] = 1.0;
  1912. result.m[5] = c;
  1913. result.m[10] = c;
  1914. result.m[9] = -s;
  1915. result.m[6] = s;
  1916. result.m[1] = 0;
  1917. result.m[2] = 0;
  1918. result.m[3] = 0;
  1919. result.m[4] = 0;
  1920. result.m[7] = 0;
  1921. result.m[8] = 0;
  1922. result.m[11] = 0;
  1923. result.m[12] = 0;
  1924. result.m[13] = 0;
  1925. result.m[14] = 0;
  1926. };
  1927. Matrix.RotationY = function (angle) {
  1928. var result = new Matrix();
  1929. Matrix.RotationYToRef(angle, result);
  1930. return result;
  1931. };
  1932. Matrix.RotationYToRef = function (angle, result) {
  1933. var s = Math.sin(angle);
  1934. var c = Math.cos(angle);
  1935. result.m[5] = 1.0;
  1936. result.m[15] = 1.0;
  1937. result.m[0] = c;
  1938. result.m[2] = -s;
  1939. result.m[8] = s;
  1940. result.m[10] = c;
  1941. result.m[1] = 0;
  1942. result.m[3] = 0;
  1943. result.m[4] = 0;
  1944. result.m[6] = 0;
  1945. result.m[7] = 0;
  1946. result.m[9] = 0;
  1947. result.m[11] = 0;
  1948. result.m[12] = 0;
  1949. result.m[13] = 0;
  1950. result.m[14] = 0;
  1951. };
  1952. Matrix.RotationZ = function (angle) {
  1953. var result = new Matrix();
  1954. Matrix.RotationZToRef(angle, result);
  1955. return result;
  1956. };
  1957. Matrix.RotationZToRef = function (angle, result) {
  1958. var s = Math.sin(angle);
  1959. var c = Math.cos(angle);
  1960. result.m[10] = 1.0;
  1961. result.m[15] = 1.0;
  1962. result.m[0] = c;
  1963. result.m[1] = s;
  1964. result.m[4] = -s;
  1965. result.m[5] = c;
  1966. result.m[2] = 0;
  1967. result.m[3] = 0;
  1968. result.m[6] = 0;
  1969. result.m[7] = 0;
  1970. result.m[8] = 0;
  1971. result.m[9] = 0;
  1972. result.m[11] = 0;
  1973. result.m[12] = 0;
  1974. result.m[13] = 0;
  1975. result.m[14] = 0;
  1976. };
  1977. Matrix.RotationAxis = function (axis, angle) {
  1978. var s = Math.sin(-angle);
  1979. var c = Math.cos(-angle);
  1980. var c1 = 1 - c;
  1981. axis.normalize();
  1982. var result = Matrix.Zero();
  1983. result.m[0] = (axis.x * axis.x) * c1 + c;
  1984. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1985. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1986. result.m[3] = 0.0;
  1987. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1988. result.m[5] = (axis.y * axis.y) * c1 + c;
  1989. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1990. result.m[7] = 0.0;
  1991. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1992. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1993. result.m[10] = (axis.z * axis.z) * c1 + c;
  1994. result.m[11] = 0.0;
  1995. result.m[15] = 1.0;
  1996. return result;
  1997. };
  1998. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1999. var result = new Matrix();
  2000. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2001. return result;
  2002. };
  2003. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2004. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2005. this._tempQuaternion.toRotationMatrix(result);
  2006. };
  2007. Matrix.Scaling = function (x, y, z) {
  2008. var result = Matrix.Zero();
  2009. Matrix.ScalingToRef(x, y, z, result);
  2010. return result;
  2011. };
  2012. Matrix.ScalingToRef = function (x, y, z, result) {
  2013. result.m[0] = x;
  2014. result.m[1] = 0;
  2015. result.m[2] = 0;
  2016. result.m[3] = 0;
  2017. result.m[4] = 0;
  2018. result.m[5] = y;
  2019. result.m[6] = 0;
  2020. result.m[7] = 0;
  2021. result.m[8] = 0;
  2022. result.m[9] = 0;
  2023. result.m[10] = z;
  2024. result.m[11] = 0;
  2025. result.m[12] = 0;
  2026. result.m[13] = 0;
  2027. result.m[14] = 0;
  2028. result.m[15] = 1.0;
  2029. };
  2030. Matrix.Translation = function (x, y, z) {
  2031. var result = Matrix.Identity();
  2032. Matrix.TranslationToRef(x, y, z, result);
  2033. return result;
  2034. };
  2035. Matrix.TranslationToRef = function (x, y, z, result) {
  2036. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2037. };
  2038. Matrix.LookAtLH = function (eye, target, up) {
  2039. var result = Matrix.Zero();
  2040. Matrix.LookAtLHToRef(eye, target, up, result);
  2041. return result;
  2042. };
  2043. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2044. // Z axis
  2045. target.subtractToRef(eye, this._zAxis);
  2046. this._zAxis.normalize();
  2047. // X axis
  2048. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2049. this._xAxis.normalize();
  2050. // Y axis
  2051. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2052. this._yAxis.normalize();
  2053. // Eye angles
  2054. var ex = -Vector3.Dot(this._xAxis, eye);
  2055. var ey = -Vector3.Dot(this._yAxis, eye);
  2056. var ez = -Vector3.Dot(this._zAxis, eye);
  2057. 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);
  2058. };
  2059. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2060. var out = result.m;
  2061. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2062. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2063. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2064. // cc.kmVec3Subtract(f, pCenter, pEye);
  2065. var f = SIMD.float32x4.sub(center, eye);
  2066. // cc.kmVec3Normalize(f, f);
  2067. var tmp = SIMD.float32x4.mul(f, f);
  2068. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2069. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2070. // cc.kmVec3Assign(up, pUp);
  2071. // cc.kmVec3Normalize(up, up);
  2072. tmp = SIMD.float32x4.mul(up, up);
  2073. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2074. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2075. // cc.kmVec3Cross(s, f, up);
  2076. 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)));
  2077. // cc.kmVec3Normalize(s, s);
  2078. tmp = SIMD.float32x4.mul(s, s);
  2079. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2080. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2081. // cc.kmVec3Cross(u, s, f);
  2082. 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)));
  2083. // cc.kmVec3Normalize(s, s);
  2084. tmp = SIMD.float32x4.mul(s, s);
  2085. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2086. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2087. var zero = SIMD.float32x4.splat(0.0);
  2088. s = SIMD.float32x4.neg(s);
  2089. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2090. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2091. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2092. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2093. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2094. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2095. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2096. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2097. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2098. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2099. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2100. var b3 = SIMD.float32x4.neg(eye);
  2101. b3 = SIMD.float32x4.withW(b3, 1.0);
  2102. 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)))));
  2103. 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)))));
  2104. 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)))));
  2105. 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)))));
  2106. };
  2107. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2108. var matrix = Matrix.Zero();
  2109. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2110. return matrix;
  2111. };
  2112. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2113. var hw = 2.0 / width;
  2114. var hh = 2.0 / height;
  2115. var id = 1.0 / (zfar - znear);
  2116. var nid = znear / (znear - zfar);
  2117. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2118. };
  2119. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2120. var matrix = Matrix.Zero();
  2121. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2122. return matrix;
  2123. };
  2124. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2125. result.m[0] = 2.0 / (right - left);
  2126. result.m[1] = result.m[2] = result.m[3] = 0;
  2127. result.m[5] = 2.0 / (top - bottom);
  2128. result.m[4] = result.m[6] = result.m[7] = 0;
  2129. result.m[10] = -1.0 / (znear - zfar);
  2130. result.m[8] = result.m[9] = result.m[11] = 0;
  2131. result.m[12] = (left + right) / (left - right);
  2132. result.m[13] = (top + bottom) / (bottom - top);
  2133. result.m[14] = znear / (znear - zfar);
  2134. result.m[15] = 1.0;
  2135. };
  2136. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2137. var matrix = Matrix.Zero();
  2138. matrix.m[0] = (2.0 * znear) / width;
  2139. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2140. matrix.m[5] = (2.0 * znear) / height;
  2141. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2142. matrix.m[10] = -zfar / (znear - zfar);
  2143. matrix.m[8] = matrix.m[9] = 0.0;
  2144. matrix.m[11] = 1.0;
  2145. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2146. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2147. return matrix;
  2148. };
  2149. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2150. var matrix = Matrix.Zero();
  2151. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2152. return matrix;
  2153. };
  2154. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2155. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2156. var tan = 1.0 / (Math.tan(fov * 0.5));
  2157. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2158. if (v_fixed) {
  2159. result.m[0] = tan / aspect;
  2160. }
  2161. else {
  2162. result.m[0] = tan;
  2163. }
  2164. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2165. if (v_fixed) {
  2166. result.m[5] = tan;
  2167. }
  2168. else {
  2169. result.m[5] = tan * aspect;
  2170. }
  2171. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2172. result.m[8] = result.m[9] = 0.0;
  2173. result.m[10] = -zfar / (znear - zfar);
  2174. result.m[11] = 1.0;
  2175. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2176. result.m[14] = (znear * zfar) / (znear - zfar);
  2177. };
  2178. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2179. var cw = viewport.width;
  2180. var ch = viewport.height;
  2181. var cx = viewport.x;
  2182. var cy = viewport.y;
  2183. 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);
  2184. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2185. };
  2186. Matrix.GetAsMatrix2x2 = function (matrix) {
  2187. return new Float32Array([
  2188. matrix.m[0], matrix.m[1],
  2189. matrix.m[4], matrix.m[5]
  2190. ]);
  2191. };
  2192. Matrix.GetAsMatrix3x3 = function (matrix) {
  2193. return new Float32Array([
  2194. matrix.m[0], matrix.m[1], matrix.m[2],
  2195. matrix.m[4], matrix.m[5], matrix.m[6],
  2196. matrix.m[8], matrix.m[9], matrix.m[10]
  2197. ]);
  2198. };
  2199. Matrix.Transpose = function (matrix) {
  2200. var result = new Matrix();
  2201. result.m[0] = matrix.m[0];
  2202. result.m[1] = matrix.m[4];
  2203. result.m[2] = matrix.m[8];
  2204. result.m[3] = matrix.m[12];
  2205. result.m[4] = matrix.m[1];
  2206. result.m[5] = matrix.m[5];
  2207. result.m[6] = matrix.m[9];
  2208. result.m[7] = matrix.m[13];
  2209. result.m[8] = matrix.m[2];
  2210. result.m[9] = matrix.m[6];
  2211. result.m[10] = matrix.m[10];
  2212. result.m[11] = matrix.m[14];
  2213. result.m[12] = matrix.m[3];
  2214. result.m[13] = matrix.m[7];
  2215. result.m[14] = matrix.m[11];
  2216. result.m[15] = matrix.m[15];
  2217. return result;
  2218. };
  2219. Matrix.Reflection = function (plane) {
  2220. var matrix = new Matrix();
  2221. Matrix.ReflectionToRef(plane, matrix);
  2222. return matrix;
  2223. };
  2224. Matrix.ReflectionToRef = function (plane, result) {
  2225. plane.normalize();
  2226. var x = plane.normal.x;
  2227. var y = plane.normal.y;
  2228. var z = plane.normal.z;
  2229. var temp = -2 * x;
  2230. var temp2 = -2 * y;
  2231. var temp3 = -2 * z;
  2232. result.m[0] = (temp * x) + 1;
  2233. result.m[1] = temp2 * x;
  2234. result.m[2] = temp3 * x;
  2235. result.m[3] = 0.0;
  2236. result.m[4] = temp * y;
  2237. result.m[5] = (temp2 * y) + 1;
  2238. result.m[6] = temp3 * y;
  2239. result.m[7] = 0.0;
  2240. result.m[8] = temp * z;
  2241. result.m[9] = temp2 * z;
  2242. result.m[10] = (temp3 * z) + 1;
  2243. result.m[11] = 0.0;
  2244. result.m[12] = temp * plane.d;
  2245. result.m[13] = temp2 * plane.d;
  2246. result.m[14] = temp3 * plane.d;
  2247. result.m[15] = 1.0;
  2248. };
  2249. Matrix._tempQuaternion = new Quaternion();
  2250. Matrix._xAxis = Vector3.Zero();
  2251. Matrix._yAxis = Vector3.Zero();
  2252. Matrix._zAxis = Vector3.Zero();
  2253. return Matrix;
  2254. })();
  2255. BABYLON.Matrix = Matrix;
  2256. var Plane = (function () {
  2257. function Plane(a, b, c, d) {
  2258. this.normal = new Vector3(a, b, c);
  2259. this.d = d;
  2260. }
  2261. Plane.prototype.asArray = function () {
  2262. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2263. };
  2264. // Methods
  2265. Plane.prototype.clone = function () {
  2266. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2267. };
  2268. Plane.prototype.normalize = function () {
  2269. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2270. var magnitude = 0;
  2271. if (norm !== 0) {
  2272. magnitude = 1.0 / norm;
  2273. }
  2274. this.normal.x *= magnitude;
  2275. this.normal.y *= magnitude;
  2276. this.normal.z *= magnitude;
  2277. this.d *= magnitude;
  2278. return this;
  2279. };
  2280. Plane.prototype.transform = function (transformation) {
  2281. var transposedMatrix = Matrix.Transpose(transformation);
  2282. var x = this.normal.x;
  2283. var y = this.normal.y;
  2284. var z = this.normal.z;
  2285. var d = this.d;
  2286. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2287. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2288. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2289. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2290. return new Plane(normalX, normalY, normalZ, finalD);
  2291. };
  2292. Plane.prototype.dotCoordinate = function (point) {
  2293. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2294. };
  2295. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2296. var x1 = point2.x - point1.x;
  2297. var y1 = point2.y - point1.y;
  2298. var z1 = point2.z - point1.z;
  2299. var x2 = point3.x - point1.x;
  2300. var y2 = point3.y - point1.y;
  2301. var z2 = point3.z - point1.z;
  2302. var yz = (y1 * z2) - (z1 * y2);
  2303. var xz = (z1 * x2) - (x1 * z2);
  2304. var xy = (x1 * y2) - (y1 * x2);
  2305. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2306. var invPyth;
  2307. if (pyth !== 0) {
  2308. invPyth = 1.0 / pyth;
  2309. }
  2310. else {
  2311. invPyth = 0;
  2312. }
  2313. this.normal.x = yz * invPyth;
  2314. this.normal.y = xz * invPyth;
  2315. this.normal.z = xy * invPyth;
  2316. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2317. return this;
  2318. };
  2319. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2320. var dot = Vector3.Dot(this.normal, direction);
  2321. return (dot <= epsilon);
  2322. };
  2323. Plane.prototype.signedDistanceTo = function (point) {
  2324. return Vector3.Dot(point, this.normal) + this.d;
  2325. };
  2326. // Statics
  2327. Plane.FromArray = function (array) {
  2328. return new Plane(array[0], array[1], array[2], array[3]);
  2329. };
  2330. Plane.FromPoints = function (point1, point2, point3) {
  2331. var result = new Plane(0, 0, 0, 0);
  2332. result.copyFromPoints(point1, point2, point3);
  2333. return result;
  2334. };
  2335. Plane.FromPositionAndNormal = function (origin, normal) {
  2336. var result = new Plane(0, 0, 0, 0);
  2337. normal.normalize();
  2338. result.normal = normal;
  2339. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2340. return result;
  2341. };
  2342. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2343. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2344. return Vector3.Dot(point, normal) + d;
  2345. };
  2346. return Plane;
  2347. })();
  2348. BABYLON.Plane = Plane;
  2349. var Viewport = (function () {
  2350. function Viewport(x, y, width, height) {
  2351. this.x = x;
  2352. this.y = y;
  2353. this.width = width;
  2354. this.height = height;
  2355. }
  2356. Viewport.prototype.toGlobal = function (engine) {
  2357. var width = engine.getRenderWidth();
  2358. var height = engine.getRenderHeight();
  2359. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2360. };
  2361. return Viewport;
  2362. })();
  2363. BABYLON.Viewport = Viewport;
  2364. var Frustum = (function () {
  2365. function Frustum() {
  2366. }
  2367. Frustum.GetPlanes = function (transform) {
  2368. var frustumPlanes = [];
  2369. for (var index = 0; index < 6; index++) {
  2370. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2371. }
  2372. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2373. return frustumPlanes;
  2374. };
  2375. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2376. // Near
  2377. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2378. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2379. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2380. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2381. frustumPlanes[0].normalize();
  2382. // Far
  2383. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2384. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2385. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2386. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2387. frustumPlanes[1].normalize();
  2388. // Left
  2389. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2390. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2391. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2392. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2393. frustumPlanes[2].normalize();
  2394. // Right
  2395. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2396. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2397. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2398. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2399. frustumPlanes[3].normalize();
  2400. // Top
  2401. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2402. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2403. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2404. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2405. frustumPlanes[4].normalize();
  2406. // Bottom
  2407. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2408. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2409. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2410. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2411. frustumPlanes[5].normalize();
  2412. };
  2413. return Frustum;
  2414. })();
  2415. BABYLON.Frustum = Frustum;
  2416. var Ray = (function () {
  2417. function Ray(origin, direction, length) {
  2418. if (length === void 0) { length = Number.MAX_VALUE; }
  2419. this.origin = origin;
  2420. this.direction = direction;
  2421. this.length = length;
  2422. }
  2423. // Methods
  2424. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2425. var d = 0.0;
  2426. var maxValue = Number.MAX_VALUE;
  2427. var inv;
  2428. var min;
  2429. var max;
  2430. var temp;
  2431. if (Math.abs(this.direction.x) < 0.0000001) {
  2432. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2433. return false;
  2434. }
  2435. }
  2436. else {
  2437. inv = 1.0 / this.direction.x;
  2438. min = (minimum.x - this.origin.x) * inv;
  2439. max = (maximum.x - this.origin.x) * inv;
  2440. if (max === -Infinity) {
  2441. max = Infinity;
  2442. }
  2443. if (min > max) {
  2444. temp = min;
  2445. min = max;
  2446. max = temp;
  2447. }
  2448. d = Math.max(min, d);
  2449. maxValue = Math.min(max, maxValue);
  2450. if (d > maxValue) {
  2451. return false;
  2452. }
  2453. }
  2454. if (Math.abs(this.direction.y) < 0.0000001) {
  2455. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2456. return false;
  2457. }
  2458. }
  2459. else {
  2460. inv = 1.0 / this.direction.y;
  2461. min = (minimum.y - this.origin.y) * inv;
  2462. max = (maximum.y - this.origin.y) * inv;
  2463. if (max === -Infinity) {
  2464. max = Infinity;
  2465. }
  2466. if (min > max) {
  2467. temp = min;
  2468. min = max;
  2469. max = temp;
  2470. }
  2471. d = Math.max(min, d);
  2472. maxValue = Math.min(max, maxValue);
  2473. if (d > maxValue) {
  2474. return false;
  2475. }
  2476. }
  2477. if (Math.abs(this.direction.z) < 0.0000001) {
  2478. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2479. return false;
  2480. }
  2481. }
  2482. else {
  2483. inv = 1.0 / this.direction.z;
  2484. min = (minimum.z - this.origin.z) * inv;
  2485. max = (maximum.z - this.origin.z) * inv;
  2486. if (max === -Infinity) {
  2487. max = Infinity;
  2488. }
  2489. if (min > max) {
  2490. temp = min;
  2491. min = max;
  2492. max = temp;
  2493. }
  2494. d = Math.max(min, d);
  2495. maxValue = Math.min(max, maxValue);
  2496. if (d > maxValue) {
  2497. return false;
  2498. }
  2499. }
  2500. return true;
  2501. };
  2502. Ray.prototype.intersectsBox = function (box) {
  2503. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2504. };
  2505. Ray.prototype.intersectsSphere = function (sphere) {
  2506. var x = sphere.center.x - this.origin.x;
  2507. var y = sphere.center.y - this.origin.y;
  2508. var z = sphere.center.z - this.origin.z;
  2509. var pyth = (x * x) + (y * y) + (z * z);
  2510. var rr = sphere.radius * sphere.radius;
  2511. if (pyth <= rr) {
  2512. return true;
  2513. }
  2514. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2515. if (dot < 0.0) {
  2516. return false;
  2517. }
  2518. var temp = pyth - (dot * dot);
  2519. return temp <= rr;
  2520. };
  2521. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2522. if (!this._edge1) {
  2523. this._edge1 = Vector3.Zero();
  2524. this._edge2 = Vector3.Zero();
  2525. this._pvec = Vector3.Zero();
  2526. this._tvec = Vector3.Zero();
  2527. this._qvec = Vector3.Zero();
  2528. }
  2529. vertex1.subtractToRef(vertex0, this._edge1);
  2530. vertex2.subtractToRef(vertex0, this._edge2);
  2531. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2532. var det = Vector3.Dot(this._edge1, this._pvec);
  2533. if (det === 0) {
  2534. return null;
  2535. }
  2536. var invdet = 1 / det;
  2537. this.origin.subtractToRef(vertex0, this._tvec);
  2538. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2539. if (bu < 0 || bu > 1.0) {
  2540. return null;
  2541. }
  2542. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2543. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2544. if (bv < 0 || bu + bv > 1.0) {
  2545. return null;
  2546. }
  2547. //check if the distance is longer than the predefined length.
  2548. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2549. if (distance > this.length) {
  2550. return null;
  2551. }
  2552. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2553. };
  2554. // Statics
  2555. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2556. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2557. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2558. var direction = end.subtract(start);
  2559. direction.normalize();
  2560. return new Ray(start, direction);
  2561. };
  2562. /**
  2563. * 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
  2564. * transformed to the given world matrix.
  2565. * @param origin The origin point
  2566. * @param end The end point
  2567. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2568. */
  2569. Ray.CreateNewFromTo = function (origin, end, world) {
  2570. if (world === void 0) { world = Matrix.Identity(); }
  2571. var direction = end.subtract(origin);
  2572. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2573. direction.normalize();
  2574. return Ray.Transform(new Ray(origin, direction, length), world);
  2575. };
  2576. Ray.Transform = function (ray, matrix) {
  2577. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2578. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2579. return new Ray(newOrigin, newDirection, ray.length);
  2580. };
  2581. return Ray;
  2582. })();
  2583. BABYLON.Ray = Ray;
  2584. (function (Space) {
  2585. Space[Space["LOCAL"] = 0] = "LOCAL";
  2586. Space[Space["WORLD"] = 1] = "WORLD";
  2587. })(BABYLON.Space || (BABYLON.Space = {}));
  2588. var Space = BABYLON.Space;
  2589. var Axis = (function () {
  2590. function Axis() {
  2591. }
  2592. Axis.X = new Vector3(1, 0, 0);
  2593. Axis.Y = new Vector3(0, 1, 0);
  2594. Axis.Z = new Vector3(0, 0, 1);
  2595. return Axis;
  2596. })();
  2597. BABYLON.Axis = Axis;
  2598. ;
  2599. var BezierCurve = (function () {
  2600. function BezierCurve() {
  2601. }
  2602. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2603. // Extract X (which is equal to time here)
  2604. var f0 = 1 - 3 * x2 + 3 * x1;
  2605. var f1 = 3 * x2 - 6 * x1;
  2606. var f2 = 3 * x1;
  2607. var refinedT = t;
  2608. for (var i = 0; i < 5; i++) {
  2609. var refinedT2 = refinedT * refinedT;
  2610. var refinedT3 = refinedT2 * refinedT;
  2611. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2612. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2613. refinedT -= (x - t) * slope;
  2614. refinedT = Math.min(1, Math.max(0, refinedT));
  2615. }
  2616. // Resolve cubic bezier for the given x
  2617. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2618. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2619. Math.pow(refinedT, 3);
  2620. };
  2621. return BezierCurve;
  2622. })();
  2623. BABYLON.BezierCurve = BezierCurve;
  2624. (function (Orientation) {
  2625. Orientation[Orientation["CW"] = 0] = "CW";
  2626. Orientation[Orientation["CCW"] = 1] = "CCW";
  2627. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2628. var Orientation = BABYLON.Orientation;
  2629. var Angle = (function () {
  2630. function Angle(radians) {
  2631. var _this = this;
  2632. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2633. this.radians = function () { return _this._radians; };
  2634. this._radians = radians;
  2635. if (this._radians < 0)
  2636. this._radians += (2 * Math.PI);
  2637. }
  2638. Angle.BetweenTwoPoints = function (a, b) {
  2639. var delta = b.subtract(a);
  2640. var theta = Math.atan2(delta.y, delta.x);
  2641. return new Angle(theta);
  2642. };
  2643. Angle.FromRadians = function (radians) {
  2644. return new Angle(radians);
  2645. };
  2646. Angle.FromDegrees = function (degrees) {
  2647. return new Angle(degrees * Math.PI / 180);
  2648. };
  2649. return Angle;
  2650. })();
  2651. BABYLON.Angle = Angle;
  2652. var Arc2 = (function () {
  2653. function Arc2(startPoint, midPoint, endPoint) {
  2654. this.startPoint = startPoint;
  2655. this.midPoint = midPoint;
  2656. this.endPoint = endPoint;
  2657. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2658. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2659. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2660. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2661. 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);
  2662. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2663. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2664. var a1 = this.startAngle.degrees();
  2665. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2666. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2667. // angles correction
  2668. if (a2 - a1 > +180.0)
  2669. a2 -= 360.0;
  2670. if (a2 - a1 < -180.0)
  2671. a2 += 360.0;
  2672. if (a3 - a2 > +180.0)
  2673. a3 -= 360.0;
  2674. if (a3 - a2 < -180.0)
  2675. a3 += 360.0;
  2676. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2677. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2678. }
  2679. return Arc2;
  2680. })();
  2681. BABYLON.Arc2 = Arc2;
  2682. var PathCursor = (function () {
  2683. function PathCursor(path) {
  2684. this.path = path;
  2685. this._onchange = new Array();
  2686. this.value = 0;
  2687. this.animations = new Array();
  2688. }
  2689. PathCursor.prototype.getPoint = function () {
  2690. var point = this.path.getPointAtLengthPosition(this.value);
  2691. return new Vector3(point.x, 0, point.y);
  2692. };
  2693. PathCursor.prototype.moveAhead = function (step) {
  2694. if (step === void 0) { step = 0.002; }
  2695. this.move(step);
  2696. return this;
  2697. };
  2698. PathCursor.prototype.moveBack = function (step) {
  2699. if (step === void 0) { step = 0.002; }
  2700. this.move(-step);
  2701. return this;
  2702. };
  2703. PathCursor.prototype.move = function (step) {
  2704. if (Math.abs(step) > 1) {
  2705. throw "step size should be less than 1.";
  2706. }
  2707. this.value += step;
  2708. this.ensureLimits();
  2709. this.raiseOnChange();
  2710. return this;
  2711. };
  2712. PathCursor.prototype.ensureLimits = function () {
  2713. while (this.value > 1) {
  2714. this.value -= 1;
  2715. }
  2716. while (this.value < 0) {
  2717. this.value += 1;
  2718. }
  2719. return this;
  2720. };
  2721. // used by animation engine
  2722. PathCursor.prototype.markAsDirty = function (propertyName) {
  2723. this.ensureLimits();
  2724. this.raiseOnChange();
  2725. return this;
  2726. };
  2727. PathCursor.prototype.raiseOnChange = function () {
  2728. var _this = this;
  2729. this._onchange.forEach(function (f) { return f(_this); });
  2730. return this;
  2731. };
  2732. PathCursor.prototype.onchange = function (f) {
  2733. this._onchange.push(f);
  2734. return this;
  2735. };
  2736. return PathCursor;
  2737. })();
  2738. BABYLON.PathCursor = PathCursor;
  2739. var Path2 = (function () {
  2740. function Path2(x, y) {
  2741. this._points = new Array();
  2742. this._length = 0;
  2743. this.closed = false;
  2744. this._points.push(new Vector2(x, y));
  2745. }
  2746. Path2.prototype.addLineTo = function (x, y) {
  2747. if (closed) {
  2748. BABYLON.Tools.Error("cannot add lines to closed paths");
  2749. return this;
  2750. }
  2751. var newPoint = new Vector2(x, y);
  2752. var previousPoint = this._points[this._points.length - 1];
  2753. this._points.push(newPoint);
  2754. this._length += newPoint.subtract(previousPoint).length();
  2755. return this;
  2756. };
  2757. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2758. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2759. if (closed) {
  2760. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2761. return this;
  2762. }
  2763. var startPoint = this._points[this._points.length - 1];
  2764. var midPoint = new Vector2(midX, midY);
  2765. var endPoint = new Vector2(endX, endY);
  2766. var arc = new Arc2(startPoint, midPoint, endPoint);
  2767. var increment = arc.angle.radians() / numberOfSegments;
  2768. if (arc.orientation === Orientation.CW)
  2769. increment *= -1;
  2770. var currentAngle = arc.startAngle.radians() + increment;
  2771. for (var i = 0; i < numberOfSegments; i++) {
  2772. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2773. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2774. this.addLineTo(x, y);
  2775. currentAngle += increment;
  2776. }
  2777. return this;
  2778. };
  2779. Path2.prototype.close = function () {
  2780. this.closed = true;
  2781. return this;
  2782. };
  2783. Path2.prototype.length = function () {
  2784. var result = this._length;
  2785. if (!this.closed) {
  2786. var lastPoint = this._points[this._points.length - 1];
  2787. var firstPoint = this._points[0];
  2788. result += (firstPoint.subtract(lastPoint).length());
  2789. }
  2790. return result;
  2791. };
  2792. Path2.prototype.getPoints = function () {
  2793. return this._points;
  2794. };
  2795. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2796. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2797. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2798. return Vector2.Zero();
  2799. }
  2800. var lengthPosition = normalizedLengthPosition * this.length();
  2801. var previousOffset = 0;
  2802. for (var i = 0; i < this._points.length; i++) {
  2803. var j = (i + 1) % this._points.length;
  2804. var a = this._points[i];
  2805. var b = this._points[j];
  2806. var bToA = b.subtract(a);
  2807. var nextOffset = (bToA.length() + previousOffset);
  2808. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2809. var dir = bToA.normalize();
  2810. var localOffset = lengthPosition - previousOffset;
  2811. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2812. }
  2813. previousOffset = nextOffset;
  2814. }
  2815. BABYLON.Tools.Error("internal error");
  2816. return Vector2.Zero();
  2817. };
  2818. Path2.StartingAt = function (x, y) {
  2819. return new Path2(x, y);
  2820. };
  2821. return Path2;
  2822. })();
  2823. BABYLON.Path2 = Path2;
  2824. var Path3D = (function () {
  2825. function Path3D(path, firstNormal) {
  2826. this.path = path;
  2827. this._curve = new Array();
  2828. this._distances = new Array();
  2829. this._tangents = new Array();
  2830. this._normals = new Array();
  2831. this._binormals = new Array();
  2832. for (var p = 0; p < path.length; p++) {
  2833. this._curve[p] = path[p].clone(); // hard copy
  2834. }
  2835. this._compute(firstNormal);
  2836. }
  2837. Path3D.prototype.getCurve = function () {
  2838. return this._curve;
  2839. };
  2840. Path3D.prototype.getTangents = function () {
  2841. return this._tangents;
  2842. };
  2843. Path3D.prototype.getNormals = function () {
  2844. return this._normals;
  2845. };
  2846. Path3D.prototype.getBinormals = function () {
  2847. return this._binormals;
  2848. };
  2849. Path3D.prototype.getDistances = function () {
  2850. return this._distances;
  2851. };
  2852. Path3D.prototype.update = function (path, firstNormal) {
  2853. for (var p = 0; p < path.length; p++) {
  2854. this._curve[p].x = path[p].x;
  2855. this._curve[p].y = path[p].y;
  2856. this._curve[p].z = path[p].z;
  2857. }
  2858. this._compute(firstNormal);
  2859. return this;
  2860. };
  2861. // private function compute() : computes tangents, normals and binormals
  2862. Path3D.prototype._compute = function (firstNormal) {
  2863. var l = this._curve.length;
  2864. // first and last tangents
  2865. this._tangents[0] = this._getFirstNonNullVector(0);
  2866. this._tangents[0].normalize();
  2867. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2868. this._tangents[l - 1].normalize();
  2869. // normals and binormals at first point : arbitrary vector with _normalVector()
  2870. var tg0 = this._tangents[0];
  2871. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2872. this._normals[0] = pp0;
  2873. this._normals[0].normalize();
  2874. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2875. this._binormals[0].normalize();
  2876. this._distances[0] = 0;
  2877. // normals and binormals : next points
  2878. var prev; // previous vector (segment)
  2879. var cur; // current vector (segment)
  2880. var curTang; // current tangent
  2881. // previous normal
  2882. var prevBinor; // previous binormal
  2883. for (var i = 1; i < l; i++) {
  2884. // tangents
  2885. prev = this._getLastNonNullVector(i);
  2886. if (i < l - 1) {
  2887. cur = this._getFirstNonNullVector(i);
  2888. this._tangents[i] = prev.add(cur);
  2889. this._tangents[i].normalize();
  2890. }
  2891. this._distances[i] = this._distances[i - 1] + prev.length();
  2892. // normals and binormals
  2893. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2894. curTang = this._tangents[i];
  2895. prevBinor = this._binormals[i - 1];
  2896. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2897. this._normals[i].normalize();
  2898. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2899. this._binormals[i].normalize();
  2900. }
  2901. };
  2902. // private function getFirstNonNullVector(index)
  2903. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2904. Path3D.prototype._getFirstNonNullVector = function (index) {
  2905. var i = 1;
  2906. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2907. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2908. i++;
  2909. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2910. }
  2911. return nNVector;
  2912. };
  2913. // private function getLastNonNullVector(index)
  2914. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2915. Path3D.prototype._getLastNonNullVector = function (index) {
  2916. var i = 1;
  2917. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2918. while (nLVector.length() === 0 && index > i + 1) {
  2919. i++;
  2920. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2921. }
  2922. return nLVector;
  2923. };
  2924. // private function normalVector(v0, vt, va) :
  2925. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2926. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2927. Path3D.prototype._normalVector = function (v0, vt, va) {
  2928. var normal0;
  2929. if (va === undefined || va === null) {
  2930. var point;
  2931. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2932. point = new Vector3(0, -1, 0);
  2933. }
  2934. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2935. point = new Vector3(1, 0, 0);
  2936. }
  2937. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2938. point = new Vector3(0, 0, 1);
  2939. }
  2940. normal0 = Vector3.Cross(vt, point);
  2941. }
  2942. else {
  2943. normal0 = Vector3.Cross(vt, va);
  2944. Vector3.CrossToRef(normal0, vt, normal0);
  2945. }
  2946. normal0.normalize();
  2947. return normal0;
  2948. };
  2949. return Path3D;
  2950. })();
  2951. BABYLON.Path3D = Path3D;
  2952. var Curve3 = (function () {
  2953. function Curve3(points) {
  2954. this._length = 0;
  2955. this._points = points;
  2956. this._length = this._computeLength(points);
  2957. }
  2958. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2959. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2960. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2961. var bez = new Array();
  2962. var equation = function (t, val0, val1, val2) {
  2963. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2964. return res;
  2965. };
  2966. for (var i = 0; i <= nbPoints; i++) {
  2967. 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)));
  2968. }
  2969. return new Curve3(bez);
  2970. };
  2971. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2972. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2973. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2974. var bez = new Array();
  2975. var equation = function (t, val0, val1, val2, val3) {
  2976. 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;
  2977. return res;
  2978. };
  2979. for (var i = 0; i <= nbPoints; i++) {
  2980. 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)));
  2981. }
  2982. return new Curve3(bez);
  2983. };
  2984. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2985. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2986. var hermite = new Array();
  2987. var step = 1 / nbPoints;
  2988. for (var i = 0; i <= nbPoints; i++) {
  2989. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2990. }
  2991. return new Curve3(hermite);
  2992. };
  2993. Curve3.prototype.getPoints = function () {
  2994. return this._points;
  2995. };
  2996. Curve3.prototype.length = function () {
  2997. return this._length;
  2998. };
  2999. Curve3.prototype.continue = function (curve) {
  3000. var lastPoint = this._points[this._points.length - 1];
  3001. var continuedPoints = this._points.slice();
  3002. var curvePoints = curve.getPoints();
  3003. for (var i = 1; i < curvePoints.length; i++) {
  3004. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3005. }
  3006. var continuedCurve = new Curve3(continuedPoints);
  3007. return continuedCurve;
  3008. };
  3009. Curve3.prototype._computeLength = function (path) {
  3010. var l = 0;
  3011. for (var i = 1; i < path.length; i++) {
  3012. l += (path[i].subtract(path[i - 1])).length();
  3013. }
  3014. return l;
  3015. };
  3016. return Curve3;
  3017. })();
  3018. BABYLON.Curve3 = Curve3;
  3019. // Vertex formats
  3020. var PositionNormalVertex = (function () {
  3021. function PositionNormalVertex(position, normal) {
  3022. if (position === void 0) { position = Vector3.Zero(); }
  3023. if (normal === void 0) { normal = Vector3.Up(); }
  3024. this.position = position;
  3025. this.normal = normal;
  3026. }
  3027. PositionNormalVertex.prototype.clone = function () {
  3028. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3029. };
  3030. return PositionNormalVertex;
  3031. })();
  3032. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3033. var PositionNormalTextureVertex = (function () {
  3034. function PositionNormalTextureVertex(position, normal, uv) {
  3035. if (position === void 0) { position = Vector3.Zero(); }
  3036. if (normal === void 0) { normal = Vector3.Up(); }
  3037. if (uv === void 0) { uv = Vector2.Zero(); }
  3038. this.position = position;
  3039. this.normal = normal;
  3040. this.uv = uv;
  3041. }
  3042. PositionNormalTextureVertex.prototype.clone = function () {
  3043. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3044. };
  3045. return PositionNormalTextureVertex;
  3046. })();
  3047. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3048. // SIMD
  3049. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3050. var previousInvertToRef = Matrix.prototype.invertToRef;
  3051. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3052. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3053. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3054. var SIMDHelper = (function () {
  3055. function SIMDHelper() {
  3056. }
  3057. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3058. get: function () {
  3059. return SIMDHelper._isEnabled;
  3060. },
  3061. enumerable: true,
  3062. configurable: true
  3063. });
  3064. SIMDHelper.DisableSIMD = function () {
  3065. // Replace functions
  3066. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3067. Matrix.prototype.invertToRef = previousInvertToRef;
  3068. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3069. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3070. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3071. SIMDHelper._isEnabled = false;
  3072. };
  3073. SIMDHelper.EnableSIMD = function () {
  3074. if (window.SIMD === undefined) {
  3075. return;
  3076. }
  3077. // Replace functions
  3078. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3079. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3080. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3081. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3082. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3083. Object.defineProperty(Vector3.prototype, "x", {
  3084. get: function () { return this._data[0]; },
  3085. set: function (value) {
  3086. if (!this._data) {
  3087. this._data = new Float32Array(3);
  3088. }
  3089. this._data[0] = value;
  3090. }
  3091. });
  3092. Object.defineProperty(Vector3.prototype, "y", {
  3093. get: function () { return this._data[1]; },
  3094. set: function (value) {
  3095. this._data[1] = value;
  3096. }
  3097. });
  3098. Object.defineProperty(Vector3.prototype, "z", {
  3099. get: function () { return this._data[2]; },
  3100. set: function (value) {
  3101. this._data[2] = value;
  3102. }
  3103. });
  3104. SIMDHelper._isEnabled = true;
  3105. };
  3106. SIMDHelper._isEnabled = false;
  3107. return SIMDHelper;
  3108. })();
  3109. BABYLON.SIMDHelper = SIMDHelper;
  3110. })(BABYLON || (BABYLON = {}));
  3111. var BABYLON;
  3112. (function (BABYLON) {
  3113. var Database = (function () {
  3114. function Database(urlToScene, callbackManifestChecked) {
  3115. // Handling various flavors of prefixed version of IndexedDB
  3116. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3117. this.callbackManifestChecked = callbackManifestChecked;
  3118. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3119. this.db = null;
  3120. this.enableSceneOffline = false;
  3121. this.enableTexturesOffline = false;
  3122. this.manifestVersionFound = 0;
  3123. this.mustUpdateRessources = false;
  3124. this.hasReachedQuota = false;
  3125. if (!Database.IDBStorageEnabled) {
  3126. this.callbackManifestChecked(true);
  3127. }
  3128. else {
  3129. this.checkManifestFile();
  3130. }
  3131. }
  3132. Database.prototype.checkManifestFile = function () {
  3133. var _this = this;
  3134. function noManifestFile() {
  3135. that.enableSceneOffline = false;
  3136. that.enableTexturesOffline = false;
  3137. that.callbackManifestChecked(false);
  3138. }
  3139. var that = this;
  3140. var manifestURL = this.currentSceneUrl + ".manifest";
  3141. var xhr = new XMLHttpRequest();
  3142. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3143. xhr.open("GET", manifestURLTimeStamped, true);
  3144. xhr.addEventListener("load", function () {
  3145. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3146. try {
  3147. var manifestFile = JSON.parse(xhr.response);
  3148. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3149. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3150. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3151. _this.manifestVersionFound = manifestFile.version;
  3152. }
  3153. if (_this.callbackManifestChecked) {
  3154. _this.callbackManifestChecked(true);
  3155. }
  3156. }
  3157. catch (ex) {
  3158. noManifestFile();
  3159. }
  3160. }
  3161. else {
  3162. noManifestFile();
  3163. }
  3164. }, false);
  3165. xhr.addEventListener("error", function (event) {
  3166. noManifestFile();
  3167. }, false);
  3168. try {
  3169. xhr.send();
  3170. }
  3171. catch (ex) {
  3172. BABYLON.Tools.Error("Error on XHR send request.");
  3173. that.callbackManifestChecked(false);
  3174. }
  3175. };
  3176. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3177. var _this = this;
  3178. function handleError() {
  3179. that.isSupported = false;
  3180. if (errorCallback)
  3181. errorCallback();
  3182. }
  3183. var that = this;
  3184. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3185. // Your browser doesn't support IndexedDB
  3186. this.isSupported = false;
  3187. if (errorCallback)
  3188. errorCallback();
  3189. }
  3190. else {
  3191. // If the DB hasn't been opened or created yet
  3192. if (!this.db) {
  3193. this.hasReachedQuota = false;
  3194. this.isSupported = true;
  3195. var request = this.idbFactory.open("babylonjs", 1);
  3196. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3197. request.onerror = function (event) {
  3198. handleError();
  3199. };
  3200. // executes when a version change transaction cannot complete due to other active transactions
  3201. request.onblocked = function (event) {
  3202. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3203. handleError();
  3204. };
  3205. // DB has been opened successfully
  3206. request.onsuccess = function (event) {
  3207. _this.db = request.result;
  3208. successCallback();
  3209. };
  3210. // Initialization of the DB. Creating Scenes & Textures stores
  3211. request.onupgradeneeded = function (event) {
  3212. _this.db = (event.target).result;
  3213. try {
  3214. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3215. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3216. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3217. }
  3218. catch (ex) {
  3219. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3220. handleError();
  3221. }
  3222. };
  3223. }
  3224. else {
  3225. if (successCallback)
  3226. successCallback();
  3227. }
  3228. }
  3229. };
  3230. Database.prototype.loadImageFromDB = function (url, image) {
  3231. var _this = this;
  3232. var completeURL = Database.ReturnFullUrlLocation(url);
  3233. var saveAndLoadImage = function () {
  3234. if (!_this.hasReachedQuota && _this.db !== null) {
  3235. // the texture is not yet in the DB, let's try to save it
  3236. _this._saveImageIntoDBAsync(completeURL, image);
  3237. }
  3238. else {
  3239. image.src = url;
  3240. }
  3241. };
  3242. if (!this.mustUpdateRessources) {
  3243. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3244. }
  3245. else {
  3246. saveAndLoadImage();
  3247. }
  3248. };
  3249. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3250. if (this.isSupported && this.db !== null) {
  3251. var texture;
  3252. var transaction = this.db.transaction(["textures"]);
  3253. transaction.onabort = function (event) {
  3254. image.src = url;
  3255. };
  3256. transaction.oncomplete = function (event) {
  3257. var blobTextureURL;
  3258. if (texture) {
  3259. var URL = window.URL || window.webkitURL;
  3260. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3261. image.onerror = function () {
  3262. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3263. image.src = url;
  3264. };
  3265. image.src = blobTextureURL;
  3266. }
  3267. else {
  3268. notInDBCallback();
  3269. }
  3270. };
  3271. var getRequest = transaction.objectStore("textures").get(url);
  3272. getRequest.onsuccess = function (event) {
  3273. texture = (event.target).result;
  3274. };
  3275. getRequest.onerror = function (event) {
  3276. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3277. image.src = url;
  3278. };
  3279. }
  3280. else {
  3281. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3282. image.src = url;
  3283. }
  3284. };
  3285. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3286. var _this = this;
  3287. if (this.isSupported) {
  3288. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3289. var generateBlobUrl = function () {
  3290. var blobTextureURL;
  3291. if (blob) {
  3292. var URL = window.URL || window.webkitURL;
  3293. try {
  3294. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3295. }
  3296. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3297. catch (ex) {
  3298. blobTextureURL = URL.createObjectURL(blob);
  3299. }
  3300. }
  3301. image.src = blobTextureURL;
  3302. };
  3303. if (Database.IsUASupportingBlobStorage) {
  3304. var xhr = new XMLHttpRequest(), blob;
  3305. xhr.open("GET", url, true);
  3306. xhr.responseType = "blob";
  3307. xhr.addEventListener("load", function () {
  3308. if (xhr.status === 200) {
  3309. // Blob as response (XHR2)
  3310. blob = xhr.response;
  3311. var transaction = _this.db.transaction(["textures"], "readwrite");
  3312. // the transaction could abort because of a QuotaExceededError error
  3313. transaction.onabort = function (event) {
  3314. try {
  3315. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3316. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3317. this.hasReachedQuota = true;
  3318. }
  3319. }
  3320. catch (ex) { }
  3321. generateBlobUrl();
  3322. };
  3323. transaction.oncomplete = function (event) {
  3324. generateBlobUrl();
  3325. };
  3326. var newTexture = { textureUrl: url, data: blob };
  3327. try {
  3328. // Put the blob into the dabase
  3329. var addRequest = transaction.objectStore("textures").put(newTexture);
  3330. addRequest.onsuccess = function (event) {
  3331. };
  3332. addRequest.onerror = function (event) {
  3333. generateBlobUrl();
  3334. };
  3335. }
  3336. catch (ex) {
  3337. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3338. if (ex.code === 25) {
  3339. Database.IsUASupportingBlobStorage = false;
  3340. }
  3341. image.src = url;
  3342. }
  3343. }
  3344. else {
  3345. image.src = url;
  3346. }
  3347. }, false);
  3348. xhr.addEventListener("error", function (event) {
  3349. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3350. image.src = url;
  3351. }, false);
  3352. xhr.send();
  3353. }
  3354. else {
  3355. image.src = url;
  3356. }
  3357. }
  3358. else {
  3359. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3360. image.src = url;
  3361. }
  3362. };
  3363. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3364. var _this = this;
  3365. var updateVersion = function (event) {
  3366. // the version is not yet in the DB or we need to update it
  3367. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3368. };
  3369. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3370. };
  3371. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3372. var _this = this;
  3373. if (this.isSupported) {
  3374. var version;
  3375. try {
  3376. var transaction = this.db.transaction(["versions"]);
  3377. transaction.oncomplete = function (event) {
  3378. if (version) {
  3379. // If the version in the JSON file is > than the version in DB
  3380. if (_this.manifestVersionFound > version.data) {
  3381. _this.mustUpdateRessources = true;
  3382. updateInDBCallback();
  3383. }
  3384. else {
  3385. callback(version.data);
  3386. }
  3387. }
  3388. else {
  3389. _this.mustUpdateRessources = true;
  3390. updateInDBCallback();
  3391. }
  3392. };
  3393. transaction.onabort = function (event) {
  3394. callback(-1);
  3395. };
  3396. var getRequest = transaction.objectStore("versions").get(url);
  3397. getRequest.onsuccess = function (event) {
  3398. version = (event.target).result;
  3399. };
  3400. getRequest.onerror = function (event) {
  3401. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3402. callback(-1);
  3403. };
  3404. }
  3405. catch (ex) {
  3406. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3407. callback(-1);
  3408. }
  3409. }
  3410. else {
  3411. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3412. callback(-1);
  3413. }
  3414. };
  3415. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3416. var _this = this;
  3417. if (this.isSupported && !this.hasReachedQuota) {
  3418. try {
  3419. // Open a transaction to the database
  3420. var transaction = this.db.transaction(["versions"], "readwrite");
  3421. // the transaction could abort because of a QuotaExceededError error
  3422. transaction.onabort = function (event) {
  3423. try {
  3424. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3425. _this.hasReachedQuota = true;
  3426. }
  3427. }
  3428. catch (ex) { }
  3429. callback(-1);
  3430. };
  3431. transaction.oncomplete = function (event) {
  3432. callback(_this.manifestVersionFound);
  3433. };
  3434. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3435. // Put the scene into the database
  3436. var addRequest = transaction.objectStore("versions").put(newVersion);
  3437. addRequest.onsuccess = function (event) {
  3438. };
  3439. addRequest.onerror = function (event) {
  3440. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3441. };
  3442. }
  3443. catch (ex) {
  3444. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3445. callback(-1);
  3446. }
  3447. }
  3448. else {
  3449. callback(-1);
  3450. }
  3451. };
  3452. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3453. var _this = this;
  3454. var completeUrl = Database.ReturnFullUrlLocation(url);
  3455. var saveAndLoadFile = function (event) {
  3456. // the scene is not yet in the DB, let's try to save it
  3457. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3458. };
  3459. this._checkVersionFromDB(completeUrl, function (version) {
  3460. if (version !== -1) {
  3461. if (!_this.mustUpdateRessources) {
  3462. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3463. }
  3464. else {
  3465. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3466. }
  3467. }
  3468. else {
  3469. errorCallback();
  3470. }
  3471. });
  3472. };
  3473. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3474. if (this.isSupported) {
  3475. var targetStore;
  3476. if (url.indexOf(".babylon") !== -1) {
  3477. targetStore = "scenes";
  3478. }
  3479. else {
  3480. targetStore = "textures";
  3481. }
  3482. var file;
  3483. var transaction = this.db.transaction([targetStore]);
  3484. transaction.oncomplete = function (event) {
  3485. if (file) {
  3486. callback(file.data);
  3487. }
  3488. else {
  3489. notInDBCallback();
  3490. }
  3491. };
  3492. transaction.onabort = function (event) {
  3493. notInDBCallback();
  3494. };
  3495. var getRequest = transaction.objectStore(targetStore).get(url);
  3496. getRequest.onsuccess = function (event) {
  3497. file = (event.target).result;
  3498. };
  3499. getRequest.onerror = function (event) {
  3500. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3501. notInDBCallback();
  3502. };
  3503. }
  3504. else {
  3505. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3506. callback();
  3507. }
  3508. };
  3509. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3510. var _this = this;
  3511. if (this.isSupported) {
  3512. var targetStore;
  3513. if (url.indexOf(".babylon") !== -1) {
  3514. targetStore = "scenes";
  3515. }
  3516. else {
  3517. targetStore = "textures";
  3518. }
  3519. // Create XHR
  3520. var xhr = new XMLHttpRequest(), fileData;
  3521. xhr.open("GET", url, true);
  3522. if (useArrayBuffer) {
  3523. xhr.responseType = "arraybuffer";
  3524. }
  3525. xhr.onprogress = progressCallback;
  3526. xhr.addEventListener("load", function () {
  3527. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3528. // Blob as response (XHR2)
  3529. //fileData = xhr.responseText;
  3530. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3531. if (!_this.hasReachedQuota) {
  3532. // Open a transaction to the database
  3533. var transaction = _this.db.transaction([targetStore], "readwrite");
  3534. // the transaction could abort because of a QuotaExceededError error
  3535. transaction.onabort = function (event) {
  3536. try {
  3537. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3538. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3539. this.hasReachedQuota = true;
  3540. }
  3541. }
  3542. catch (ex) { }
  3543. callback(fileData);
  3544. };
  3545. transaction.oncomplete = function (event) {
  3546. callback(fileData);
  3547. };
  3548. var newFile;
  3549. if (targetStore === "scenes") {
  3550. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3551. }
  3552. else {
  3553. newFile = { textureUrl: url, data: fileData };
  3554. }
  3555. try {
  3556. // Put the scene into the database
  3557. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3558. addRequest.onsuccess = function (event) {
  3559. };
  3560. addRequest.onerror = function (event) {
  3561. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3562. };
  3563. }
  3564. catch (ex) {
  3565. callback(fileData);
  3566. }
  3567. }
  3568. else {
  3569. callback(fileData);
  3570. }
  3571. }
  3572. else {
  3573. callback();
  3574. }
  3575. }, false);
  3576. xhr.addEventListener("error", function (event) {
  3577. BABYLON.Tools.Error("error on XHR request.");
  3578. callback();
  3579. }, false);
  3580. xhr.send();
  3581. }
  3582. else {
  3583. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3584. callback();
  3585. }
  3586. };
  3587. Database.IsUASupportingBlobStorage = true;
  3588. Database.IDBStorageEnabled = true;
  3589. Database.parseURL = function (url) {
  3590. var a = document.createElement('a');
  3591. a.href = url;
  3592. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3593. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3594. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3595. return absLocation;
  3596. };
  3597. Database.ReturnFullUrlLocation = function (url) {
  3598. if (url.indexOf("http:/") === -1) {
  3599. return (Database.parseURL(window.location.href) + url);
  3600. }
  3601. else {
  3602. return url;
  3603. }
  3604. };
  3605. return Database;
  3606. })();
  3607. BABYLON.Database = Database;
  3608. })(BABYLON || (BABYLON = {}));
  3609. var BABYLON;
  3610. (function (BABYLON) {
  3611. var Internals;
  3612. (function (Internals) {
  3613. /*
  3614. * Based on jsTGALoader - Javascript loader for TGA file
  3615. * By Vincent Thibault
  3616. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3617. */
  3618. var TGATools = (function () {
  3619. function TGATools() {
  3620. }
  3621. TGATools.GetTGAHeader = function (data) {
  3622. var offset = 0;
  3623. var header = {
  3624. id_length: data[offset++],
  3625. colormap_type: data[offset++],
  3626. image_type: data[offset++],
  3627. colormap_index: data[offset++] | data[offset++] << 8,
  3628. colormap_length: data[offset++] | data[offset++] << 8,
  3629. colormap_size: data[offset++],
  3630. origin: [
  3631. data[offset++] | data[offset++] << 8,
  3632. data[offset++] | data[offset++] << 8
  3633. ],
  3634. width: data[offset++] | data[offset++] << 8,
  3635. height: data[offset++] | data[offset++] << 8,
  3636. pixel_size: data[offset++],
  3637. flags: data[offset++]
  3638. };
  3639. return header;
  3640. };
  3641. TGATools.UploadContent = function (gl, data) {
  3642. // Not enough data to contain header ?
  3643. if (data.length < 19) {
  3644. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3645. return;
  3646. }
  3647. // Read Header
  3648. var offset = 18;
  3649. var header = TGATools.GetTGAHeader(data);
  3650. // Assume it's a valid Targa file.
  3651. if (header.id_length + offset > data.length) {
  3652. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3653. return;
  3654. }
  3655. // Skip not needed data
  3656. offset += header.id_length;
  3657. var use_rle = false;
  3658. var use_pal = false;
  3659. var use_rgb = false;
  3660. var use_grey = false;
  3661. // Get some informations.
  3662. switch (header.image_type) {
  3663. case TGATools._TYPE_RLE_INDEXED:
  3664. use_rle = true;
  3665. case TGATools._TYPE_INDEXED:
  3666. use_pal = true;
  3667. break;
  3668. case TGATools._TYPE_RLE_RGB:
  3669. use_rle = true;
  3670. case TGATools._TYPE_RGB:
  3671. use_rgb = true;
  3672. break;
  3673. case TGATools._TYPE_RLE_GREY:
  3674. use_rle = true;
  3675. case TGATools._TYPE_GREY:
  3676. use_grey = true;
  3677. break;
  3678. }
  3679. var pixel_data;
  3680. var numAlphaBits = header.flags & 0xf;
  3681. var pixel_size = header.pixel_size >> 3;
  3682. var pixel_total = header.width * header.height * pixel_size;
  3683. // Read palettes
  3684. var palettes;
  3685. if (use_pal) {
  3686. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3687. }
  3688. // Read LRE
  3689. if (use_rle) {
  3690. pixel_data = new Uint8Array(pixel_total);
  3691. var c, count, i;
  3692. var localOffset = 0;
  3693. var pixels = new Uint8Array(pixel_size);
  3694. while (offset < pixel_total && localOffset < pixel_total) {
  3695. c = data[offset++];
  3696. count = (c & 0x7f) + 1;
  3697. // RLE pixels
  3698. if (c & 0x80) {
  3699. // Bind pixel tmp array
  3700. for (i = 0; i < pixel_size; ++i) {
  3701. pixels[i] = data[offset++];
  3702. }
  3703. // Copy pixel array
  3704. for (i = 0; i < count; ++i) {
  3705. pixel_data.set(pixels, localOffset + i * pixel_size);
  3706. }
  3707. localOffset += pixel_size * count;
  3708. }
  3709. else {
  3710. count *= pixel_size;
  3711. for (i = 0; i < count; ++i) {
  3712. pixel_data[localOffset + i] = data[offset++];
  3713. }
  3714. localOffset += count;
  3715. }
  3716. }
  3717. }
  3718. else {
  3719. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3720. }
  3721. // Load to texture
  3722. var x_start, y_start, x_step, y_step, y_end, x_end;
  3723. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3724. default:
  3725. case TGATools._ORIGIN_UL:
  3726. x_start = 0;
  3727. x_step = 1;
  3728. x_end = header.width;
  3729. y_start = 0;
  3730. y_step = 1;
  3731. y_end = header.height;
  3732. break;
  3733. case TGATools._ORIGIN_BL:
  3734. x_start = 0;
  3735. x_step = 1;
  3736. x_end = header.width;
  3737. y_start = header.height - 1;
  3738. y_step = -1;
  3739. y_end = -1;
  3740. break;
  3741. case TGATools._ORIGIN_UR:
  3742. x_start = header.width - 1;
  3743. x_step = -1;
  3744. x_end = -1;
  3745. y_start = 0;
  3746. y_step = 1;
  3747. y_end = header.height;
  3748. break;
  3749. case TGATools._ORIGIN_BR:
  3750. x_start = header.width - 1;
  3751. x_step = -1;
  3752. x_end = -1;
  3753. y_start = header.height - 1;
  3754. y_step = -1;
  3755. y_end = -1;
  3756. break;
  3757. }
  3758. // Load the specify method
  3759. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3760. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3761. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3762. };
  3763. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3764. var image = pixel_data, colormap = palettes;
  3765. var width = header.width, height = header.height;
  3766. var color, i = 0, x, y;
  3767. var imageData = new Uint8Array(width * height * 4);
  3768. for (y = y_start; y !== y_end; y += y_step) {
  3769. for (x = x_start; x !== x_end; x += x_step, i++) {
  3770. color = image[i];
  3771. imageData[(x + width * y) * 4 + 3] = 255;
  3772. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3773. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3774. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3775. }
  3776. }
  3777. return imageData;
  3778. };
  3779. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3780. var image = pixel_data;
  3781. var width = header.width, height = header.height;
  3782. var color, i = 0, x, y;
  3783. var imageData = new Uint8Array(width * height * 4);
  3784. for (y = y_start; y !== y_end; y += y_step) {
  3785. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3786. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3787. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3788. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3789. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3790. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3791. }
  3792. }
  3793. return imageData;
  3794. };
  3795. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3796. var image = pixel_data;
  3797. var width = header.width, height = header.height;
  3798. var i = 0, x, y;
  3799. var imageData = new Uint8Array(width * height * 4);
  3800. for (y = y_start; y !== y_end; y += y_step) {
  3801. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3802. imageData[(x + width * y) * 4 + 3] = 255;
  3803. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3804. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3805. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3806. }
  3807. }
  3808. return imageData;
  3809. };
  3810. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3811. var image = pixel_data;
  3812. var width = header.width, height = header.height;
  3813. var i = 0, x, y;
  3814. var imageData = new Uint8Array(width * height * 4);
  3815. for (y = y_start; y !== y_end; y += y_step) {
  3816. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3817. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3818. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3819. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3820. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3821. }
  3822. }
  3823. return imageData;
  3824. };
  3825. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3826. var image = pixel_data;
  3827. var width = header.width, height = header.height;
  3828. var color, i = 0, x, y;
  3829. var imageData = new Uint8Array(width * height * 4);
  3830. for (y = y_start; y !== y_end; y += y_step) {
  3831. for (x = x_start; x !== x_end; x += x_step, i++) {
  3832. color = image[i];
  3833. imageData[(x + width * y) * 4 + 0] = color;
  3834. imageData[(x + width * y) * 4 + 1] = color;
  3835. imageData[(x + width * y) * 4 + 2] = color;
  3836. imageData[(x + width * y) * 4 + 3] = 255;
  3837. }
  3838. }
  3839. return imageData;
  3840. };
  3841. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3842. var image = pixel_data;
  3843. var width = header.width, height = header.height;
  3844. var i = 0, x, y;
  3845. var imageData = new Uint8Array(width * height * 4);
  3846. for (y = y_start; y !== y_end; y += y_step) {
  3847. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3848. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3849. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3850. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3851. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3852. }
  3853. }
  3854. return imageData;
  3855. };
  3856. TGATools._TYPE_NO_DATA = 0;
  3857. TGATools._TYPE_INDEXED = 1;
  3858. TGATools._TYPE_RGB = 2;
  3859. TGATools._TYPE_GREY = 3;
  3860. TGATools._TYPE_RLE_INDEXED = 9;
  3861. TGATools._TYPE_RLE_RGB = 10;
  3862. TGATools._TYPE_RLE_GREY = 11;
  3863. TGATools._ORIGIN_MASK = 0x30;
  3864. TGATools._ORIGIN_SHIFT = 0x04;
  3865. TGATools._ORIGIN_BL = 0x00;
  3866. TGATools._ORIGIN_BR = 0x01;
  3867. TGATools._ORIGIN_UL = 0x02;
  3868. TGATools._ORIGIN_UR = 0x03;
  3869. return TGATools;
  3870. })();
  3871. Internals.TGATools = TGATools;
  3872. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3873. })(BABYLON || (BABYLON = {}));
  3874. var BABYLON;
  3875. (function (BABYLON) {
  3876. var Internals;
  3877. (function (Internals) {
  3878. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3879. // All values and structures referenced from:
  3880. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3881. var DDS_MAGIC = 0x20534444;
  3882. 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;
  3883. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3884. 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;
  3885. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3886. function FourCCToInt32(value) {
  3887. return value.charCodeAt(0) +
  3888. (value.charCodeAt(1) << 8) +
  3889. (value.charCodeAt(2) << 16) +
  3890. (value.charCodeAt(3) << 24);
  3891. }
  3892. function Int32ToFourCC(value) {
  3893. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3894. }
  3895. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3896. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3897. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3898. var headerLengthInt = 31; // The header length in 32 bit ints
  3899. // Offsets into the header array
  3900. var off_magic = 0;
  3901. var off_size = 1;
  3902. var off_flags = 2;
  3903. var off_height = 3;
  3904. var off_width = 4;
  3905. var off_mipmapCount = 7;
  3906. var off_pfFlags = 20;
  3907. var off_pfFourCC = 21;
  3908. var off_RGBbpp = 22;
  3909. var off_RMask = 23;
  3910. var off_GMask = 24;
  3911. var off_BMask = 25;
  3912. var off_AMask = 26;
  3913. var off_caps1 = 27;
  3914. var off_caps2 = 28;
  3915. ;
  3916. var DDSTools = (function () {
  3917. function DDSTools() {
  3918. }
  3919. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3920. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3921. var mipmapCount = 1;
  3922. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3923. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3924. }
  3925. return {
  3926. width: header[off_width],
  3927. height: header[off_height],
  3928. mipmapCount: mipmapCount,
  3929. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3930. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3931. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3932. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3933. };
  3934. };
  3935. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3936. var byteArray = new Uint8Array(dataLength);
  3937. var srcData = new Uint8Array(arrayBuffer);
  3938. var index = 0;
  3939. for (var y = height - 1; y >= 0; y--) {
  3940. for (var x = 0; x < width; x++) {
  3941. var srcPos = dataOffset + (x + y * width) * 4;
  3942. byteArray[index + 2] = srcData[srcPos];
  3943. byteArray[index + 1] = srcData[srcPos + 1];
  3944. byteArray[index] = srcData[srcPos + 2];
  3945. byteArray[index + 3] = srcData[srcPos + 3];
  3946. index += 4;
  3947. }
  3948. }
  3949. return byteArray;
  3950. };
  3951. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3952. var byteArray = new Uint8Array(dataLength);
  3953. var srcData = new Uint8Array(arrayBuffer);
  3954. var index = 0;
  3955. for (var y = height - 1; y >= 0; y--) {
  3956. for (var x = 0; x < width; x++) {
  3957. var srcPos = dataOffset + (x + y * width) * 3;
  3958. byteArray[index + 2] = srcData[srcPos];
  3959. byteArray[index + 1] = srcData[srcPos + 1];
  3960. byteArray[index] = srcData[srcPos + 2];
  3961. index += 3;
  3962. }
  3963. }
  3964. return byteArray;
  3965. };
  3966. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3967. var byteArray = new Uint8Array(dataLength);
  3968. var srcData = new Uint8Array(arrayBuffer);
  3969. var index = 0;
  3970. for (var y = height - 1; y >= 0; y--) {
  3971. for (var x = 0; x < width; x++) {
  3972. var srcPos = dataOffset + (x + y * width);
  3973. byteArray[index] = srcData[srcPos];
  3974. index++;
  3975. }
  3976. }
  3977. return byteArray;
  3978. };
  3979. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3980. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3981. if (header[off_magic] != DDS_MAGIC) {
  3982. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3983. return;
  3984. }
  3985. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3986. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3987. return;
  3988. }
  3989. if (info.isFourCC) {
  3990. fourCC = header[off_pfFourCC];
  3991. switch (fourCC) {
  3992. case FOURCC_DXT1:
  3993. blockBytes = 8;
  3994. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3995. break;
  3996. case FOURCC_DXT3:
  3997. blockBytes = 16;
  3998. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3999. break;
  4000. case FOURCC_DXT5:
  4001. blockBytes = 16;
  4002. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4003. break;
  4004. default:
  4005. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4006. return;
  4007. }
  4008. }
  4009. mipmapCount = 1;
  4010. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4011. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4012. }
  4013. var bpp = header[off_RGBbpp];
  4014. for (var face = 0; face < faces; face++) {
  4015. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4016. width = header[off_width];
  4017. height = header[off_height];
  4018. dataOffset = header[off_size] + 4;
  4019. for (i = 0; i < mipmapCount; ++i) {
  4020. if (info.isRGB) {
  4021. if (bpp == 24) {
  4022. dataLength = width * height * 3;
  4023. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4024. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4025. }
  4026. else {
  4027. dataLength = width * height * 4;
  4028. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4029. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4030. }
  4031. }
  4032. else if (info.isLuminance) {
  4033. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4034. var unpaddedRowSize = width;
  4035. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4036. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4037. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4038. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4039. }
  4040. else {
  4041. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4042. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4043. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4044. }
  4045. dataOffset += dataLength;
  4046. width *= 0.5;
  4047. height *= 0.5;
  4048. width = Math.max(1.0, width);
  4049. height = Math.max(1.0, height);
  4050. }
  4051. }
  4052. };
  4053. return DDSTools;
  4054. })();
  4055. Internals.DDSTools = DDSTools;
  4056. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4057. })(BABYLON || (BABYLON = {}));
  4058. var BABYLON;
  4059. (function (BABYLON) {
  4060. var SmartArray = (function () {
  4061. function SmartArray(capacity) {
  4062. this.length = 0;
  4063. this._duplicateId = 0;
  4064. this.data = new Array(capacity);
  4065. this._id = SmartArray._GlobalId++;
  4066. }
  4067. SmartArray.prototype.push = function (value) {
  4068. this.data[this.length++] = value;
  4069. if (this.length > this.data.length) {
  4070. this.data.length *= 2;
  4071. }
  4072. if (!value.__smartArrayFlags) {
  4073. value.__smartArrayFlags = {};
  4074. }
  4075. value.__smartArrayFlags[this._id] = this._duplicateId;
  4076. };
  4077. SmartArray.prototype.pushNoDuplicate = function (value) {
  4078. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4079. return;
  4080. }
  4081. this.push(value);
  4082. };
  4083. SmartArray.prototype.sort = function (compareFn) {
  4084. this.data.sort(compareFn);
  4085. };
  4086. SmartArray.prototype.reset = function () {
  4087. this.length = 0;
  4088. this._duplicateId++;
  4089. };
  4090. SmartArray.prototype.concat = function (array) {
  4091. if (array.length === 0) {
  4092. return;
  4093. }
  4094. if (this.length + array.length > this.data.length) {
  4095. this.data.length = (this.length + array.length) * 2;
  4096. }
  4097. for (var index = 0; index < array.length; index++) {
  4098. this.data[this.length++] = (array.data || array)[index];
  4099. }
  4100. };
  4101. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4102. if (array.length === 0) {
  4103. return;
  4104. }
  4105. if (this.length + array.length > this.data.length) {
  4106. this.data.length = (this.length + array.length) * 2;
  4107. }
  4108. for (var index = 0; index < array.length; index++) {
  4109. var item = (array.data || array)[index];
  4110. this.pushNoDuplicate(item);
  4111. }
  4112. };
  4113. SmartArray.prototype.indexOf = function (value) {
  4114. var position = this.data.indexOf(value);
  4115. if (position >= this.length) {
  4116. return -1;
  4117. }
  4118. return position;
  4119. };
  4120. // Statics
  4121. SmartArray._GlobalId = 0;
  4122. return SmartArray;
  4123. })();
  4124. BABYLON.SmartArray = SmartArray;
  4125. })(BABYLON || (BABYLON = {}));
  4126. var BABYLON;
  4127. (function (BABYLON) {
  4128. var SmartCollection = (function () {
  4129. function SmartCollection(capacity) {
  4130. if (capacity === void 0) { capacity = 10; }
  4131. this.count = 0;
  4132. this._initialCapacity = capacity;
  4133. this.items = {};
  4134. this._keys = new Array(this._initialCapacity);
  4135. }
  4136. SmartCollection.prototype.add = function (key, item) {
  4137. if (this.items[key] != undefined) {
  4138. return -1;
  4139. }
  4140. this.items[key] = item;
  4141. //literal keys are always strings, but we keep source type of key in _keys array
  4142. this._keys[this.count++] = key;
  4143. if (this.count > this._keys.length) {
  4144. this._keys.length *= 2;
  4145. }
  4146. return this.count;
  4147. };
  4148. SmartCollection.prototype.remove = function (key) {
  4149. if (this.items[key] == undefined) {
  4150. return -1;
  4151. }
  4152. return this.removeItemOfIndex(this.indexOf(key));
  4153. };
  4154. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4155. if (index < this.count && index > -1) {
  4156. delete this.items[this._keys[index]];
  4157. //here, shifting by hand is better optimised than .splice
  4158. while (index < this.count) {
  4159. this._keys[index] = this._keys[index + 1];
  4160. index++;
  4161. }
  4162. }
  4163. else {
  4164. return -1;
  4165. }
  4166. return --this.count;
  4167. };
  4168. SmartCollection.prototype.indexOf = function (key) {
  4169. for (var i = 0; i !== this.count; i++) {
  4170. if (this._keys[i] === key) {
  4171. return i;
  4172. }
  4173. }
  4174. return -1;
  4175. };
  4176. SmartCollection.prototype.item = function (key) {
  4177. return this.items[key];
  4178. };
  4179. SmartCollection.prototype.getAllKeys = function () {
  4180. if (this.count > 0) {
  4181. var keys = new Array(this.count);
  4182. for (var i = 0; i < this.count; i++) {
  4183. keys[i] = this._keys[i];
  4184. }
  4185. return keys;
  4186. }
  4187. else {
  4188. return undefined;
  4189. }
  4190. };
  4191. SmartCollection.prototype.getKeyByIndex = function (index) {
  4192. if (index < this.count && index > -1) {
  4193. return this._keys[index];
  4194. }
  4195. else {
  4196. return undefined;
  4197. }
  4198. };
  4199. SmartCollection.prototype.getItemByIndex = function (index) {
  4200. if (index < this.count && index > -1) {
  4201. return this.items[this._keys[index]];
  4202. }
  4203. else {
  4204. return undefined;
  4205. }
  4206. };
  4207. SmartCollection.prototype.empty = function () {
  4208. if (this.count > 0) {
  4209. this.count = 0;
  4210. this.items = {};
  4211. this._keys = new Array(this._initialCapacity);
  4212. }
  4213. };
  4214. SmartCollection.prototype.forEach = function (block) {
  4215. var key;
  4216. for (key in this.items) {
  4217. if (this.items.hasOwnProperty(key)) {
  4218. block(this.items[key]);
  4219. }
  4220. }
  4221. };
  4222. return SmartCollection;
  4223. })();
  4224. BABYLON.SmartCollection = SmartCollection;
  4225. })(BABYLON || (BABYLON = {}));
  4226. var BABYLON;
  4227. (function (BABYLON) {
  4228. // Screenshots
  4229. var screenshotCanvas;
  4230. var cloneValue = function (source, destinationObject) {
  4231. if (!source)
  4232. return null;
  4233. if (source instanceof BABYLON.Mesh) {
  4234. return null;
  4235. }
  4236. if (source instanceof BABYLON.SubMesh) {
  4237. return source.clone(destinationObject);
  4238. }
  4239. else if (source.clone) {
  4240. return source.clone();
  4241. }
  4242. return null;
  4243. };
  4244. var Tools = (function () {
  4245. function Tools() {
  4246. }
  4247. Tools.ToHex = function (i) {
  4248. var str = i.toString(16);
  4249. if (i <= 15) {
  4250. return ("0" + str).toUpperCase();
  4251. }
  4252. return str.toUpperCase();
  4253. };
  4254. Tools.SetImmediate = function (action) {
  4255. if (window.setImmediate) {
  4256. window.setImmediate(action);
  4257. }
  4258. else {
  4259. setTimeout(action, 1);
  4260. }
  4261. };
  4262. Tools.IsExponantOfTwo = function (value) {
  4263. var count = 1;
  4264. do {
  4265. count *= 2;
  4266. } while (count < value);
  4267. return count === value;
  4268. };
  4269. Tools.GetExponantOfTwo = function (value, max) {
  4270. var count = 1;
  4271. do {
  4272. count *= 2;
  4273. } while (count < value);
  4274. if (count > max)
  4275. count = max;
  4276. return count;
  4277. };
  4278. Tools.GetFilename = function (path) {
  4279. var index = path.lastIndexOf("/");
  4280. if (index < 0)
  4281. return path;
  4282. return path.substring(index + 1);
  4283. };
  4284. Tools.GetDOMTextContent = function (element) {
  4285. var result = "";
  4286. var child = element.firstChild;
  4287. while (child) {
  4288. if (child.nodeType === 3) {
  4289. result += child.textContent;
  4290. }
  4291. child = child.nextSibling;
  4292. }
  4293. return result;
  4294. };
  4295. Tools.ToDegrees = function (angle) {
  4296. return angle * 180 / Math.PI;
  4297. };
  4298. Tools.ToRadians = function (angle) {
  4299. return angle * Math.PI / 180;
  4300. };
  4301. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4302. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4303. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4304. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4305. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4306. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4307. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4308. }
  4309. return {
  4310. minimum: minimum,
  4311. maximum: maximum
  4312. };
  4313. };
  4314. Tools.ExtractMinAndMax = function (positions, start, count) {
  4315. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4316. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4317. for (var index = start; index < start + count; index++) {
  4318. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4319. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4320. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4321. }
  4322. return {
  4323. minimum: minimum,
  4324. maximum: maximum
  4325. };
  4326. };
  4327. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4328. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4329. return undefined;
  4330. return Array.isArray(obj) ? obj : [obj];
  4331. };
  4332. // Misc.
  4333. Tools.GetPointerPrefix = function () {
  4334. var eventPrefix = "pointer";
  4335. // Check if hand.js is referenced or if the browser natively supports pointer events
  4336. if (!navigator.pointerEnabled) {
  4337. eventPrefix = "mouse";
  4338. }
  4339. return eventPrefix;
  4340. };
  4341. Tools.QueueNewFrame = function (func) {
  4342. if (window.requestAnimationFrame)
  4343. window.requestAnimationFrame(func);
  4344. else if (window.msRequestAnimationFrame)
  4345. window.msRequestAnimationFrame(func);
  4346. else if (window.webkitRequestAnimationFrame)
  4347. window.webkitRequestAnimationFrame(func);
  4348. else if (window.mozRequestAnimationFrame)
  4349. window.mozRequestAnimationFrame(func);
  4350. else if (window.oRequestAnimationFrame)
  4351. window.oRequestAnimationFrame(func);
  4352. else {
  4353. window.setTimeout(func, 16);
  4354. }
  4355. };
  4356. Tools.RequestFullscreen = function (element) {
  4357. if (element.requestFullscreen)
  4358. element.requestFullscreen();
  4359. else if (element.msRequestFullscreen)
  4360. element.msRequestFullscreen();
  4361. else if (element.webkitRequestFullscreen)
  4362. element.webkitRequestFullscreen();
  4363. else if (element.mozRequestFullScreen)
  4364. element.mozRequestFullScreen();
  4365. };
  4366. Tools.ExitFullscreen = function () {
  4367. if (document.exitFullscreen) {
  4368. document.exitFullscreen();
  4369. }
  4370. else if (document.mozCancelFullScreen) {
  4371. document.mozCancelFullScreen();
  4372. }
  4373. else if (document.webkitCancelFullScreen) {
  4374. document.webkitCancelFullScreen();
  4375. }
  4376. else if (document.msCancelFullScreen) {
  4377. document.msCancelFullScreen();
  4378. }
  4379. };
  4380. // External files
  4381. Tools.CleanUrl = function (url) {
  4382. url = url.replace(/#/mg, "%23");
  4383. return url;
  4384. };
  4385. Tools.LoadImage = function (url, onload, onerror, database) {
  4386. url = Tools.CleanUrl(url);
  4387. var img = new Image();
  4388. if (url.substr(0, 5) !== "data:")
  4389. img.crossOrigin = 'anonymous';
  4390. img.onload = function () {
  4391. onload(img);
  4392. };
  4393. img.onerror = function (err) {
  4394. Tools.Error("Error while trying to load texture: " + url);
  4395. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4396. onload(img);
  4397. };
  4398. var noIndexedDB = function () {
  4399. img.src = url;
  4400. };
  4401. var loadFromIndexedDB = function () {
  4402. database.loadImageFromDB(url, img);
  4403. };
  4404. //ANY database to do!
  4405. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4406. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4407. }
  4408. else {
  4409. if (url.indexOf("file:") === -1) {
  4410. noIndexedDB();
  4411. }
  4412. else {
  4413. try {
  4414. var textureName = url.substring(5);
  4415. var blobURL;
  4416. try {
  4417. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4418. }
  4419. catch (ex) {
  4420. // Chrome doesn't support oneTimeOnly parameter
  4421. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4422. }
  4423. img.src = blobURL;
  4424. }
  4425. catch (e) {
  4426. img.src = null;
  4427. }
  4428. }
  4429. }
  4430. return img;
  4431. };
  4432. //ANY
  4433. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4434. url = Tools.CleanUrl(url);
  4435. var noIndexedDB = function () {
  4436. var request = new XMLHttpRequest();
  4437. var loadUrl = Tools.BaseUrl + url;
  4438. request.open('GET', loadUrl, true);
  4439. if (useArrayBuffer) {
  4440. request.responseType = "arraybuffer";
  4441. }
  4442. request.onprogress = progressCallBack;
  4443. request.onreadystatechange = function () {
  4444. if (request.readyState === 4) {
  4445. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4446. callback(!useArrayBuffer ? request.responseText : request.response);
  4447. }
  4448. else {
  4449. if (onError) {
  4450. onError();
  4451. }
  4452. else {
  4453. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4454. }
  4455. }
  4456. }
  4457. };
  4458. request.send(null);
  4459. };
  4460. var loadFromIndexedDB = function () {
  4461. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4462. };
  4463. if (url.indexOf("file:") !== -1) {
  4464. var fileName = url.substring(5);
  4465. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4466. }
  4467. else {
  4468. // Caching all files
  4469. if (database && database.enableSceneOffline) {
  4470. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4471. }
  4472. else {
  4473. noIndexedDB();
  4474. }
  4475. }
  4476. };
  4477. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4478. var reader = new FileReader();
  4479. reader.onload = function (e) {
  4480. //target doesn't have result from ts 1.3
  4481. callback(e.target['result']);
  4482. };
  4483. reader.onprogress = progressCallback;
  4484. reader.readAsDataURL(fileToLoad);
  4485. };
  4486. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4487. var reader = new FileReader();
  4488. reader.onerror = function (e) {
  4489. Tools.Log("Error while reading file: " + fileToLoad.name);
  4490. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4491. };
  4492. reader.onload = function (e) {
  4493. //target doesn't have result from ts 1.3
  4494. callback(e.target['result']);
  4495. };
  4496. reader.onprogress = progressCallBack;
  4497. if (!useArrayBuffer) {
  4498. // Asynchronous read
  4499. reader.readAsText(fileToLoad);
  4500. }
  4501. else {
  4502. reader.readAsArrayBuffer(fileToLoad);
  4503. }
  4504. };
  4505. // Misc.
  4506. Tools.Clamp = function (value, min, max) {
  4507. if (min === void 0) { min = 0; }
  4508. if (max === void 0) { max = 1; }
  4509. return Math.min(max, Math.max(min, value));
  4510. };
  4511. // Returns -1 when value is a negative number and
  4512. // +1 when value is a positive number.
  4513. Tools.Sign = function (value) {
  4514. value = +value; // convert to a number
  4515. if (value === 0 || isNaN(value))
  4516. return value;
  4517. return value > 0 ? 1 : -1;
  4518. };
  4519. Tools.Format = function (value, decimals) {
  4520. if (decimals === void 0) { decimals = 2; }
  4521. return value.toFixed(decimals);
  4522. };
  4523. Tools.CheckExtends = function (v, min, max) {
  4524. if (v.x < min.x)
  4525. min.x = v.x;
  4526. if (v.y < min.y)
  4527. min.y = v.y;
  4528. if (v.z < min.z)
  4529. min.z = v.z;
  4530. if (v.x > max.x)
  4531. max.x = v.x;
  4532. if (v.y > max.y)
  4533. max.y = v.y;
  4534. if (v.z > max.z)
  4535. max.z = v.z;
  4536. };
  4537. Tools.WithinEpsilon = function (a, b, epsilon) {
  4538. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4539. var num = a - b;
  4540. return -epsilon <= num && num <= epsilon;
  4541. };
  4542. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4543. for (var prop in source) {
  4544. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4545. continue;
  4546. }
  4547. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4548. continue;
  4549. }
  4550. var sourceValue = source[prop];
  4551. var typeOfSourceValue = typeof sourceValue;
  4552. if (typeOfSourceValue === "function") {
  4553. continue;
  4554. }
  4555. if (typeOfSourceValue === "object") {
  4556. if (sourceValue instanceof Array) {
  4557. destination[prop] = [];
  4558. if (sourceValue.length > 0) {
  4559. if (typeof sourceValue[0] == "object") {
  4560. for (var index = 0; index < sourceValue.length; index++) {
  4561. var clonedValue = cloneValue(sourceValue[index], destination);
  4562. if (destination[prop].indexOf(clonedValue) === -1) {
  4563. destination[prop].push(clonedValue);
  4564. }
  4565. }
  4566. }
  4567. else {
  4568. destination[prop] = sourceValue.slice(0);
  4569. }
  4570. }
  4571. }
  4572. else {
  4573. destination[prop] = cloneValue(sourceValue, destination);
  4574. }
  4575. }
  4576. else {
  4577. destination[prop] = sourceValue;
  4578. }
  4579. }
  4580. };
  4581. Tools.IsEmpty = function (obj) {
  4582. for (var i in obj) {
  4583. return false;
  4584. }
  4585. return true;
  4586. };
  4587. Tools.RegisterTopRootEvents = function (events) {
  4588. for (var index = 0; index < events.length; index++) {
  4589. var event = events[index];
  4590. window.addEventListener(event.name, event.handler, false);
  4591. try {
  4592. if (window.parent) {
  4593. window.parent.addEventListener(event.name, event.handler, false);
  4594. }
  4595. }
  4596. catch (e) {
  4597. }
  4598. }
  4599. };
  4600. Tools.UnregisterTopRootEvents = function (events) {
  4601. for (var index = 0; index < events.length; index++) {
  4602. var event = events[index];
  4603. window.removeEventListener(event.name, event.handler);
  4604. try {
  4605. if (window.parent) {
  4606. window.parent.removeEventListener(event.name, event.handler);
  4607. }
  4608. }
  4609. catch (e) {
  4610. }
  4611. }
  4612. };
  4613. Tools.DumpFramebuffer = function (width, height, engine) {
  4614. // Read the contents of the framebuffer
  4615. var numberOfChannelsByLine = width * 4;
  4616. var halfHeight = height / 2;
  4617. //Reading datas from WebGL
  4618. var data = engine.readPixels(0, 0, width, height);
  4619. //To flip image on Y axis.
  4620. for (var i = 0; i < halfHeight; i++) {
  4621. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4622. var currentCell = j + i * numberOfChannelsByLine;
  4623. var targetLine = height - i - 1;
  4624. var targetCell = j + targetLine * numberOfChannelsByLine;
  4625. var temp = data[currentCell];
  4626. data[currentCell] = data[targetCell];
  4627. data[targetCell] = temp;
  4628. }
  4629. }
  4630. // Create a 2D canvas to store the result
  4631. if (!screenshotCanvas) {
  4632. screenshotCanvas = document.createElement('canvas');
  4633. }
  4634. screenshotCanvas.width = width;
  4635. screenshotCanvas.height = height;
  4636. var context = screenshotCanvas.getContext('2d');
  4637. // Copy the pixels to a 2D canvas
  4638. var imageData = context.createImageData(width, height);
  4639. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4640. var castData = imageData.data;
  4641. castData.set(data);
  4642. context.putImageData(imageData, 0, 0);
  4643. var base64Image = screenshotCanvas.toDataURL();
  4644. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4645. if (("download" in document.createElement("a"))) {
  4646. var a = window.document.createElement("a");
  4647. a.href = base64Image;
  4648. var date = new Date();
  4649. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4650. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4651. window.document.body.appendChild(a);
  4652. a.addEventListener("click", function () {
  4653. a.parentElement.removeChild(a);
  4654. });
  4655. a.click();
  4656. }
  4657. else {
  4658. var newWindow = window.open("");
  4659. var img = newWindow.document.createElement("img");
  4660. img.src = base64Image;
  4661. newWindow.document.body.appendChild(img);
  4662. }
  4663. };
  4664. Tools.CreateScreenshot = function (engine, camera, size) {
  4665. var width;
  4666. var height;
  4667. var scene = camera.getScene();
  4668. var previousCamera = null;
  4669. if (scene.activeCamera !== camera) {
  4670. previousCamera = scene.activeCamera;
  4671. scene.activeCamera = camera;
  4672. }
  4673. //If a precision value is specified
  4674. if (size.precision) {
  4675. width = Math.round(engine.getRenderWidth() * size.precision);
  4676. height = Math.round(width / engine.getAspectRatio(camera));
  4677. size = { width: width, height: height };
  4678. }
  4679. else if (size.width && size.height) {
  4680. width = size.width;
  4681. height = size.height;
  4682. }
  4683. else if (size.width && !size.height) {
  4684. width = size.width;
  4685. height = Math.round(width / engine.getAspectRatio(camera));
  4686. size = { width: width, height: height };
  4687. }
  4688. else if (size.height && !size.width) {
  4689. height = size.height;
  4690. width = Math.round(height * engine.getAspectRatio(camera));
  4691. size = { width: width, height: height };
  4692. }
  4693. else if (!isNaN(size)) {
  4694. height = size;
  4695. width = size;
  4696. }
  4697. else {
  4698. Tools.Error("Invalid 'size' parameter !");
  4699. return;
  4700. }
  4701. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4702. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4703. texture.renderList = scene.meshes;
  4704. texture.onAfterRender = function () {
  4705. Tools.DumpFramebuffer(width, height, engine);
  4706. };
  4707. scene.incrementRenderId();
  4708. texture.render(true);
  4709. texture.dispose();
  4710. if (previousCamera) {
  4711. scene.activeCamera = previousCamera;
  4712. }
  4713. };
  4714. // XHR response validator for local file scenario
  4715. Tools.ValidateXHRData = function (xhr, dataType) {
  4716. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4717. if (dataType === void 0) { dataType = 7; }
  4718. try {
  4719. if (dataType & 1) {
  4720. if (xhr.responseText && xhr.responseText.length > 0) {
  4721. return true;
  4722. }
  4723. else if (dataType === 1) {
  4724. return false;
  4725. }
  4726. }
  4727. if (dataType & 2) {
  4728. // Check header width and height since there is no "TGA" magic number
  4729. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4730. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4731. return true;
  4732. }
  4733. else if (dataType === 2) {
  4734. return false;
  4735. }
  4736. }
  4737. if (dataType & 4) {
  4738. // Check for the "DDS" magic number
  4739. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4740. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4741. return true;
  4742. }
  4743. else {
  4744. return false;
  4745. }
  4746. }
  4747. }
  4748. catch (e) {
  4749. }
  4750. return false;
  4751. };
  4752. Object.defineProperty(Tools, "NoneLogLevel", {
  4753. get: function () {
  4754. return Tools._NoneLogLevel;
  4755. },
  4756. enumerable: true,
  4757. configurable: true
  4758. });
  4759. Object.defineProperty(Tools, "MessageLogLevel", {
  4760. get: function () {
  4761. return Tools._MessageLogLevel;
  4762. },
  4763. enumerable: true,
  4764. configurable: true
  4765. });
  4766. Object.defineProperty(Tools, "WarningLogLevel", {
  4767. get: function () {
  4768. return Tools._WarningLogLevel;
  4769. },
  4770. enumerable: true,
  4771. configurable: true
  4772. });
  4773. Object.defineProperty(Tools, "ErrorLogLevel", {
  4774. get: function () {
  4775. return Tools._ErrorLogLevel;
  4776. },
  4777. enumerable: true,
  4778. configurable: true
  4779. });
  4780. Object.defineProperty(Tools, "AllLogLevel", {
  4781. get: function () {
  4782. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4783. },
  4784. enumerable: true,
  4785. configurable: true
  4786. });
  4787. Tools._AddLogEntry = function (entry) {
  4788. Tools._LogCache = entry + Tools._LogCache;
  4789. if (Tools.OnNewCacheEntry) {
  4790. Tools.OnNewCacheEntry(entry);
  4791. }
  4792. };
  4793. Tools._FormatMessage = function (message) {
  4794. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4795. var date = new Date();
  4796. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4797. };
  4798. Tools._LogDisabled = function (message) {
  4799. // nothing to do
  4800. };
  4801. Tools._LogEnabled = function (message) {
  4802. var formattedMessage = Tools._FormatMessage(message);
  4803. console.log("BJS - " + formattedMessage);
  4804. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4805. Tools._AddLogEntry(entry);
  4806. };
  4807. Tools._WarnDisabled = function (message) {
  4808. // nothing to do
  4809. };
  4810. Tools._WarnEnabled = function (message) {
  4811. var formattedMessage = Tools._FormatMessage(message);
  4812. console.warn("BJS - " + formattedMessage);
  4813. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4814. Tools._AddLogEntry(entry);
  4815. };
  4816. Tools._ErrorDisabled = function (message) {
  4817. // nothing to do
  4818. };
  4819. Tools._ErrorEnabled = function (message) {
  4820. Tools.errorsCount++;
  4821. var formattedMessage = Tools._FormatMessage(message);
  4822. console.error("BJS - " + formattedMessage);
  4823. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4824. Tools._AddLogEntry(entry);
  4825. };
  4826. Object.defineProperty(Tools, "LogCache", {
  4827. get: function () {
  4828. return Tools._LogCache;
  4829. },
  4830. enumerable: true,
  4831. configurable: true
  4832. });
  4833. Tools.ClearLogCache = function () {
  4834. Tools._LogCache = "";
  4835. Tools.errorsCount = 0;
  4836. };
  4837. Object.defineProperty(Tools, "LogLevels", {
  4838. set: function (level) {
  4839. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4840. Tools.Log = Tools._LogEnabled;
  4841. }
  4842. else {
  4843. Tools.Log = Tools._LogDisabled;
  4844. }
  4845. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4846. Tools.Warn = Tools._WarnEnabled;
  4847. }
  4848. else {
  4849. Tools.Warn = Tools._WarnDisabled;
  4850. }
  4851. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4852. Tools.Error = Tools._ErrorEnabled;
  4853. }
  4854. else {
  4855. Tools.Error = Tools._ErrorDisabled;
  4856. }
  4857. },
  4858. enumerable: true,
  4859. configurable: true
  4860. });
  4861. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4862. get: function () {
  4863. return Tools._PerformanceNoneLogLevel;
  4864. },
  4865. enumerable: true,
  4866. configurable: true
  4867. });
  4868. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4869. get: function () {
  4870. return Tools._PerformanceUserMarkLogLevel;
  4871. },
  4872. enumerable: true,
  4873. configurable: true
  4874. });
  4875. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4876. get: function () {
  4877. return Tools._PerformanceConsoleLogLevel;
  4878. },
  4879. enumerable: true,
  4880. configurable: true
  4881. });
  4882. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4883. set: function (level) {
  4884. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4885. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4886. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4887. return;
  4888. }
  4889. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4890. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4891. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4892. return;
  4893. }
  4894. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4895. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4896. },
  4897. enumerable: true,
  4898. configurable: true
  4899. });
  4900. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4901. };
  4902. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4903. };
  4904. Tools._StartUserMark = function (counterName, condition) {
  4905. if (condition === void 0) { condition = true; }
  4906. if (!condition || !Tools._performance.mark) {
  4907. return;
  4908. }
  4909. Tools._performance.mark(counterName + "-Begin");
  4910. };
  4911. Tools._EndUserMark = function (counterName, condition) {
  4912. if (condition === void 0) { condition = true; }
  4913. if (!condition || !Tools._performance.mark) {
  4914. return;
  4915. }
  4916. Tools._performance.mark(counterName + "-End");
  4917. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4918. };
  4919. Tools._StartPerformanceConsole = function (counterName, condition) {
  4920. if (condition === void 0) { condition = true; }
  4921. if (!condition) {
  4922. return;
  4923. }
  4924. Tools._StartUserMark(counterName, condition);
  4925. if (console.time) {
  4926. console.time(counterName);
  4927. }
  4928. };
  4929. Tools._EndPerformanceConsole = function (counterName, condition) {
  4930. if (condition === void 0) { condition = true; }
  4931. if (!condition) {
  4932. return;
  4933. }
  4934. Tools._EndUserMark(counterName, condition);
  4935. if (console.time) {
  4936. console.timeEnd(counterName);
  4937. }
  4938. };
  4939. Object.defineProperty(Tools, "Now", {
  4940. get: function () {
  4941. if (window.performance && window.performance.now) {
  4942. return window.performance.now();
  4943. }
  4944. return new Date().getTime();
  4945. },
  4946. enumerable: true,
  4947. configurable: true
  4948. });
  4949. // Deprecated
  4950. Tools.GetFps = function () {
  4951. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4952. return 0;
  4953. };
  4954. Tools.BaseUrl = "";
  4955. // Logs
  4956. Tools._NoneLogLevel = 0;
  4957. Tools._MessageLogLevel = 1;
  4958. Tools._WarningLogLevel = 2;
  4959. Tools._ErrorLogLevel = 4;
  4960. Tools._LogCache = "";
  4961. Tools.errorsCount = 0;
  4962. Tools.Log = Tools._LogEnabled;
  4963. Tools.Warn = Tools._WarnEnabled;
  4964. Tools.Error = Tools._ErrorEnabled;
  4965. // Performances
  4966. Tools._PerformanceNoneLogLevel = 0;
  4967. Tools._PerformanceUserMarkLogLevel = 1;
  4968. Tools._PerformanceConsoleLogLevel = 2;
  4969. Tools._performance = window.performance;
  4970. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4971. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4972. return Tools;
  4973. })();
  4974. BABYLON.Tools = Tools;
  4975. /**
  4976. * An implementation of a loop for asynchronous functions.
  4977. */
  4978. var AsyncLoop = (function () {
  4979. /**
  4980. * Constroctor.
  4981. * @param iterations the number of iterations.
  4982. * @param _fn the function to run each iteration
  4983. * @param _successCallback the callback that will be called upon succesful execution
  4984. * @param offset starting offset.
  4985. */
  4986. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4987. if (offset === void 0) { offset = 0; }
  4988. this.iterations = iterations;
  4989. this._fn = _fn;
  4990. this._successCallback = _successCallback;
  4991. this.index = offset - 1;
  4992. this._done = false;
  4993. }
  4994. /**
  4995. * Execute the next iteration. Must be called after the last iteration was finished.
  4996. */
  4997. AsyncLoop.prototype.executeNext = function () {
  4998. if (!this._done) {
  4999. if (this.index + 1 < this.iterations) {
  5000. ++this.index;
  5001. this._fn(this);
  5002. }
  5003. else {
  5004. this.breakLoop();
  5005. }
  5006. }
  5007. };
  5008. /**
  5009. * Break the loop and run the success callback.
  5010. */
  5011. AsyncLoop.prototype.breakLoop = function () {
  5012. this._done = true;
  5013. this._successCallback();
  5014. };
  5015. /**
  5016. * Helper function
  5017. */
  5018. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5019. if (offset === void 0) { offset = 0; }
  5020. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5021. loop.executeNext();
  5022. return loop;
  5023. };
  5024. /**
  5025. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5026. * @param iterations total number of iterations
  5027. * @param syncedIterations number of synchronous iterations in each async iteration.
  5028. * @param fn the function to call each iteration.
  5029. * @param callback a success call back that will be called when iterating stops.
  5030. * @param breakFunction a break condition (optional)
  5031. * @param timeout timeout settings for the setTimeout function. default - 0.
  5032. * @constructor
  5033. */
  5034. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5035. if (timeout === void 0) { timeout = 0; }
  5036. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5037. if (breakFunction && breakFunction())
  5038. loop.breakLoop();
  5039. else {
  5040. setTimeout(function () {
  5041. for (var i = 0; i < syncedIterations; ++i) {
  5042. var iteration = (loop.index * syncedIterations) + i;
  5043. if (iteration >= iterations)
  5044. break;
  5045. fn(iteration);
  5046. if (breakFunction && breakFunction()) {
  5047. loop.breakLoop();
  5048. break;
  5049. }
  5050. }
  5051. loop.executeNext();
  5052. }, timeout);
  5053. }
  5054. }, callback);
  5055. };
  5056. return AsyncLoop;
  5057. })();
  5058. BABYLON.AsyncLoop = AsyncLoop;
  5059. })(BABYLON || (BABYLON = {}));
  5060. var BABYLON;
  5061. (function (BABYLON) {
  5062. var _DepthCullingState = (function () {
  5063. function _DepthCullingState() {
  5064. this._isDepthTestDirty = false;
  5065. this._isDepthMaskDirty = false;
  5066. this._isDepthFuncDirty = false;
  5067. this._isCullFaceDirty = false;
  5068. this._isCullDirty = false;
  5069. this._isZOffsetDirty = false;
  5070. }
  5071. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5072. get: function () {
  5073. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5074. },
  5075. enumerable: true,
  5076. configurable: true
  5077. });
  5078. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5079. get: function () {
  5080. return this._zOffset;
  5081. },
  5082. set: function (value) {
  5083. if (this._zOffset === value) {
  5084. return;
  5085. }
  5086. this._zOffset = value;
  5087. this._isZOffsetDirty = true;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5093. get: function () {
  5094. return this._cullFace;
  5095. },
  5096. set: function (value) {
  5097. if (this._cullFace === value) {
  5098. return;
  5099. }
  5100. this._cullFace = value;
  5101. this._isCullFaceDirty = true;
  5102. },
  5103. enumerable: true,
  5104. configurable: true
  5105. });
  5106. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5107. get: function () {
  5108. return this._cull;
  5109. },
  5110. set: function (value) {
  5111. if (this._cull === value) {
  5112. return;
  5113. }
  5114. this._cull = value;
  5115. this._isCullDirty = true;
  5116. },
  5117. enumerable: true,
  5118. configurable: true
  5119. });
  5120. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5121. get: function () {
  5122. return this._depthFunc;
  5123. },
  5124. set: function (value) {
  5125. if (this._depthFunc === value) {
  5126. return;
  5127. }
  5128. this._depthFunc = value;
  5129. this._isDepthFuncDirty = true;
  5130. },
  5131. enumerable: true,
  5132. configurable: true
  5133. });
  5134. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5135. get: function () {
  5136. return this._depthMask;
  5137. },
  5138. set: function (value) {
  5139. if (this._depthMask === value) {
  5140. return;
  5141. }
  5142. this._depthMask = value;
  5143. this._isDepthMaskDirty = true;
  5144. },
  5145. enumerable: true,
  5146. configurable: true
  5147. });
  5148. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5149. get: function () {
  5150. return this._depthTest;
  5151. },
  5152. set: function (value) {
  5153. if (this._depthTest === value) {
  5154. return;
  5155. }
  5156. this._depthTest = value;
  5157. this._isDepthTestDirty = true;
  5158. },
  5159. enumerable: true,
  5160. configurable: true
  5161. });
  5162. _DepthCullingState.prototype.reset = function () {
  5163. this._depthMask = true;
  5164. this._depthTest = true;
  5165. this._depthFunc = null;
  5166. this._cull = null;
  5167. this._cullFace = null;
  5168. this._zOffset = 0;
  5169. this._isDepthTestDirty = true;
  5170. this._isDepthMaskDirty = true;
  5171. this._isDepthFuncDirty = false;
  5172. this._isCullFaceDirty = false;
  5173. this._isCullDirty = false;
  5174. this._isZOffsetDirty = false;
  5175. };
  5176. _DepthCullingState.prototype.apply = function (gl) {
  5177. if (!this.isDirty) {
  5178. return;
  5179. }
  5180. // Cull
  5181. if (this._isCullDirty) {
  5182. if (this.cull) {
  5183. gl.enable(gl.CULL_FACE);
  5184. }
  5185. else {
  5186. gl.disable(gl.CULL_FACE);
  5187. }
  5188. this._isCullDirty = false;
  5189. }
  5190. // Cull face
  5191. if (this._isCullFaceDirty) {
  5192. gl.cullFace(this.cullFace);
  5193. this._isCullFaceDirty = false;
  5194. }
  5195. // Depth mask
  5196. if (this._isDepthMaskDirty) {
  5197. gl.depthMask(this.depthMask);
  5198. this._isDepthMaskDirty = false;
  5199. }
  5200. // Depth test
  5201. if (this._isDepthTestDirty) {
  5202. if (this.depthTest) {
  5203. gl.enable(gl.DEPTH_TEST);
  5204. }
  5205. else {
  5206. gl.disable(gl.DEPTH_TEST);
  5207. }
  5208. this._isDepthTestDirty = false;
  5209. }
  5210. // Depth func
  5211. if (this._isDepthFuncDirty) {
  5212. gl.depthFunc(this.depthFunc);
  5213. this._isDepthFuncDirty = false;
  5214. }
  5215. // zOffset
  5216. if (this._isZOffsetDirty) {
  5217. if (this.zOffset) {
  5218. gl.enable(gl.POLYGON_OFFSET_FILL);
  5219. gl.polygonOffset(this.zOffset, 0);
  5220. }
  5221. else {
  5222. gl.disable(gl.POLYGON_OFFSET_FILL);
  5223. }
  5224. this._isZOffsetDirty = false;
  5225. }
  5226. };
  5227. return _DepthCullingState;
  5228. })();
  5229. BABYLON._DepthCullingState = _DepthCullingState;
  5230. var _AlphaState = (function () {
  5231. function _AlphaState() {
  5232. this._isAlphaBlendDirty = false;
  5233. this._isBlendFunctionParametersDirty = false;
  5234. this._alphaBlend = false;
  5235. this._blendFunctionParameters = new Array(4);
  5236. }
  5237. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5238. get: function () {
  5239. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5240. },
  5241. enumerable: true,
  5242. configurable: true
  5243. });
  5244. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5245. get: function () {
  5246. return this._alphaBlend;
  5247. },
  5248. set: function (value) {
  5249. if (this._alphaBlend === value) {
  5250. return;
  5251. }
  5252. this._alphaBlend = value;
  5253. this._isAlphaBlendDirty = true;
  5254. },
  5255. enumerable: true,
  5256. configurable: true
  5257. });
  5258. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5259. if (this._blendFunctionParameters[0] === value0 &&
  5260. this._blendFunctionParameters[1] === value1 &&
  5261. this._blendFunctionParameters[2] === value2 &&
  5262. this._blendFunctionParameters[3] === value3) {
  5263. return;
  5264. }
  5265. this._blendFunctionParameters[0] = value0;
  5266. this._blendFunctionParameters[1] = value1;
  5267. this._blendFunctionParameters[2] = value2;
  5268. this._blendFunctionParameters[3] = value3;
  5269. this._isBlendFunctionParametersDirty = true;
  5270. };
  5271. _AlphaState.prototype.reset = function () {
  5272. this._alphaBlend = false;
  5273. this._blendFunctionParameters[0] = null;
  5274. this._blendFunctionParameters[1] = null;
  5275. this._blendFunctionParameters[2] = null;
  5276. this._blendFunctionParameters[3] = null;
  5277. this._isAlphaBlendDirty = true;
  5278. this._isBlendFunctionParametersDirty = false;
  5279. };
  5280. _AlphaState.prototype.apply = function (gl) {
  5281. if (!this.isDirty) {
  5282. return;
  5283. }
  5284. // Alpha blend
  5285. if (this._isAlphaBlendDirty) {
  5286. if (this._alphaBlend) {
  5287. gl.enable(gl.BLEND);
  5288. }
  5289. else {
  5290. gl.disable(gl.BLEND);
  5291. }
  5292. this._isAlphaBlendDirty = false;
  5293. }
  5294. // Alpha function
  5295. if (this._isBlendFunctionParametersDirty) {
  5296. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5297. this._isBlendFunctionParametersDirty = false;
  5298. }
  5299. };
  5300. return _AlphaState;
  5301. })();
  5302. BABYLON._AlphaState = _AlphaState;
  5303. var compileShader = function (gl, source, type, defines) {
  5304. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5305. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5306. gl.compileShader(shader);
  5307. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5308. throw new Error(gl.getShaderInfoLog(shader));
  5309. }
  5310. return shader;
  5311. };
  5312. var getWebGLTextureType = function (gl, type) {
  5313. var textureType = gl.UNSIGNED_BYTE;
  5314. if (type === Engine.TEXTURETYPE_FLOAT)
  5315. textureType = gl.FLOAT;
  5316. return textureType;
  5317. };
  5318. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5319. var magFilter = gl.NEAREST;
  5320. var minFilter = gl.NEAREST;
  5321. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5322. magFilter = gl.LINEAR;
  5323. if (generateMipMaps) {
  5324. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5325. }
  5326. else {
  5327. minFilter = gl.LINEAR;
  5328. }
  5329. }
  5330. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5331. magFilter = gl.LINEAR;
  5332. if (generateMipMaps) {
  5333. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5334. }
  5335. else {
  5336. minFilter = gl.LINEAR;
  5337. }
  5338. }
  5339. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5340. magFilter = gl.NEAREST;
  5341. if (generateMipMaps) {
  5342. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5343. }
  5344. else {
  5345. minFilter = gl.NEAREST;
  5346. }
  5347. }
  5348. return {
  5349. min: minFilter,
  5350. mag: magFilter
  5351. };
  5352. };
  5353. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5355. var engine = scene.getEngine();
  5356. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5357. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5358. gl.bindTexture(gl.TEXTURE_2D, texture);
  5359. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5360. texture._baseWidth = width;
  5361. texture._baseHeight = height;
  5362. texture._width = potWidth;
  5363. texture._height = potHeight;
  5364. texture.isReady = true;
  5365. processFunction(potWidth, potHeight);
  5366. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5369. if (!noMipmap && !isCompressed) {
  5370. gl.generateMipmap(gl.TEXTURE_2D);
  5371. }
  5372. gl.bindTexture(gl.TEXTURE_2D, null);
  5373. engine._activeTexturesCache = [];
  5374. scene._removePendingData(texture);
  5375. };
  5376. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5377. var onload = function () {
  5378. loadedImages[index] = img;
  5379. loadedImages._internalCount++;
  5380. scene._removePendingData(img);
  5381. if (loadedImages._internalCount === 6) {
  5382. onfinish(loadedImages);
  5383. }
  5384. };
  5385. var onerror = function () {
  5386. scene._removePendingData(img);
  5387. };
  5388. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5389. scene._addPendingData(img);
  5390. };
  5391. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5392. var loadedImages = [];
  5393. loadedImages._internalCount = 0;
  5394. for (var index = 0; index < 6; index++) {
  5395. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5396. }
  5397. };
  5398. var EngineCapabilities = (function () {
  5399. function EngineCapabilities() {
  5400. }
  5401. return EngineCapabilities;
  5402. })();
  5403. BABYLON.EngineCapabilities = EngineCapabilities;
  5404. /**
  5405. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5406. */
  5407. var Engine = (function () {
  5408. /**
  5409. * @constructor
  5410. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5411. * @param {boolean} [antialias] - enable antialias
  5412. * @param options - further options to be sent to the getContext function
  5413. */
  5414. function Engine(canvas, antialias, options) {
  5415. var _this = this;
  5416. // Public members
  5417. this.isFullscreen = false;
  5418. this.isPointerLock = false;
  5419. this.cullBackFaces = true;
  5420. this.renderEvenInBackground = true;
  5421. // To enable/disable IDB support and avoid XHR on .manifest
  5422. this.enableOfflineSupport = true;
  5423. this.scenes = new Array();
  5424. this._windowIsBackground = false;
  5425. this._loadingDivBackgroundColor = "black";
  5426. this._drawCalls = 0;
  5427. this._renderingQueueLaunched = false;
  5428. this._activeRenderLoops = [];
  5429. // FPS
  5430. this.fpsRange = 60;
  5431. this.previousFramesDuration = [];
  5432. this.fps = 60;
  5433. this.deltaTime = 0;
  5434. // States
  5435. this._depthCullingState = new _DepthCullingState();
  5436. this._alphaState = new _AlphaState();
  5437. this._alphaMode = Engine.ALPHA_DISABLE;
  5438. // Cache
  5439. this._loadedTexturesCache = new Array();
  5440. this._activeTexturesCache = new Array();
  5441. this._compiledEffects = {};
  5442. this._uintIndicesCurrentlySet = false;
  5443. this._renderingCanvas = canvas;
  5444. options = options || {};
  5445. options.antialias = antialias;
  5446. if (options.preserveDrawingBuffer === undefined) {
  5447. options.preserveDrawingBuffer = false;
  5448. }
  5449. // GL
  5450. try {
  5451. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5452. }
  5453. catch (e) {
  5454. throw new Error("WebGL not supported");
  5455. }
  5456. if (!this._gl) {
  5457. throw new Error("WebGL not supported");
  5458. }
  5459. this._onBlur = function () {
  5460. _this._windowIsBackground = true;
  5461. };
  5462. this._onFocus = function () {
  5463. _this._windowIsBackground = false;
  5464. };
  5465. window.addEventListener("blur", this._onBlur);
  5466. window.addEventListener("focus", this._onFocus);
  5467. // Viewport
  5468. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5469. this.resize();
  5470. // Caps
  5471. this._caps = new EngineCapabilities();
  5472. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5473. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5474. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5475. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5476. // Infos
  5477. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5478. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5479. if (rendererInfo != null) {
  5480. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5481. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5482. }
  5483. if (!this._glVendor) {
  5484. this._glVendor = "Unknown vendor";
  5485. }
  5486. if (!this._glRenderer) {
  5487. this._glRenderer = "Unknown renderer";
  5488. }
  5489. // Extensions
  5490. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5491. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5492. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5493. 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');
  5494. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5495. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5496. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5497. this._caps.highPrecisionShaderSupported = true;
  5498. if (this._gl.getShaderPrecisionFormat) {
  5499. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5500. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5501. }
  5502. // Depth buffer
  5503. this.setDepthBuffer(true);
  5504. this.setDepthFunctionToLessOrEqual();
  5505. this.setDepthWrite(true);
  5506. // Fullscreen
  5507. this._onFullscreenChange = function () {
  5508. if (document.fullscreen !== undefined) {
  5509. _this.isFullscreen = document.fullscreen;
  5510. }
  5511. else if (document.mozFullScreen !== undefined) {
  5512. _this.isFullscreen = document.mozFullScreen;
  5513. }
  5514. else if (document.webkitIsFullScreen !== undefined) {
  5515. _this.isFullscreen = document.webkitIsFullScreen;
  5516. }
  5517. else if (document.msIsFullScreen !== undefined) {
  5518. _this.isFullscreen = document.msIsFullScreen;
  5519. }
  5520. // Pointer lock
  5521. if (_this.isFullscreen && _this._pointerLockRequested) {
  5522. canvas.requestPointerLock = canvas.requestPointerLock ||
  5523. canvas.msRequestPointerLock ||
  5524. canvas.mozRequestPointerLock ||
  5525. canvas.webkitRequestPointerLock;
  5526. if (canvas.requestPointerLock) {
  5527. canvas.requestPointerLock();
  5528. }
  5529. }
  5530. };
  5531. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5532. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5533. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5534. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5535. // Pointer lock
  5536. this._onPointerLockChange = function () {
  5537. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5538. document.webkitPointerLockElement === canvas ||
  5539. document.msPointerLockElement === canvas ||
  5540. document.pointerLockElement === canvas);
  5541. };
  5542. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5543. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5544. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5545. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5546. if (!Engine.audioEngine) {
  5547. Engine.audioEngine = new BABYLON.AudioEngine();
  5548. }
  5549. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5550. }
  5551. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5552. get: function () {
  5553. return Engine._ALPHA_DISABLE;
  5554. },
  5555. enumerable: true,
  5556. configurable: true
  5557. });
  5558. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5559. get: function () {
  5560. return Engine._ALPHA_ONEONE;
  5561. },
  5562. enumerable: true,
  5563. configurable: true
  5564. });
  5565. Object.defineProperty(Engine, "ALPHA_ADD", {
  5566. get: function () {
  5567. return Engine._ALPHA_ADD;
  5568. },
  5569. enumerable: true,
  5570. configurable: true
  5571. });
  5572. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5573. get: function () {
  5574. return Engine._ALPHA_COMBINE;
  5575. },
  5576. enumerable: true,
  5577. configurable: true
  5578. });
  5579. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5580. get: function () {
  5581. return Engine._ALPHA_SUBTRACT;
  5582. },
  5583. enumerable: true,
  5584. configurable: true
  5585. });
  5586. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5587. get: function () {
  5588. return Engine._ALPHA_MULTIPLY;
  5589. },
  5590. enumerable: true,
  5591. configurable: true
  5592. });
  5593. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5594. get: function () {
  5595. return Engine._ALPHA_MAXIMIZED;
  5596. },
  5597. enumerable: true,
  5598. configurable: true
  5599. });
  5600. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5601. get: function () {
  5602. return Engine._DELAYLOADSTATE_NONE;
  5603. },
  5604. enumerable: true,
  5605. configurable: true
  5606. });
  5607. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5608. get: function () {
  5609. return Engine._DELAYLOADSTATE_LOADED;
  5610. },
  5611. enumerable: true,
  5612. configurable: true
  5613. });
  5614. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5615. get: function () {
  5616. return Engine._DELAYLOADSTATE_LOADING;
  5617. },
  5618. enumerable: true,
  5619. configurable: true
  5620. });
  5621. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5622. get: function () {
  5623. return Engine._DELAYLOADSTATE_NOTLOADED;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5629. get: function () {
  5630. return Engine._TEXTUREFORMAT_ALPHA;
  5631. },
  5632. enumerable: true,
  5633. configurable: true
  5634. });
  5635. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5636. get: function () {
  5637. return Engine._TEXTUREFORMAT_LUMINANCE;
  5638. },
  5639. enumerable: true,
  5640. configurable: true
  5641. });
  5642. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5643. get: function () {
  5644. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5645. },
  5646. enumerable: true,
  5647. configurable: true
  5648. });
  5649. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5650. get: function () {
  5651. return Engine._TEXTUREFORMAT_RGB;
  5652. },
  5653. enumerable: true,
  5654. configurable: true
  5655. });
  5656. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5657. get: function () {
  5658. return Engine._TEXTUREFORMAT_RGBA;
  5659. },
  5660. enumerable: true,
  5661. configurable: true
  5662. });
  5663. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5664. get: function () {
  5665. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5666. },
  5667. enumerable: true,
  5668. configurable: true
  5669. });
  5670. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5671. get: function () {
  5672. return Engine._TEXTURETYPE_FLOAT;
  5673. },
  5674. enumerable: true,
  5675. configurable: true
  5676. });
  5677. Object.defineProperty(Engine, "Version", {
  5678. get: function () {
  5679. return "2.2.0-beta";
  5680. },
  5681. enumerable: true,
  5682. configurable: true
  5683. });
  5684. Engine.prototype._prepareWorkingCanvas = function () {
  5685. if (this._workingCanvas) {
  5686. return;
  5687. }
  5688. this._workingCanvas = document.createElement("canvas");
  5689. this._workingContext = this._workingCanvas.getContext("2d");
  5690. };
  5691. Engine.prototype.getGlInfo = function () {
  5692. return {
  5693. vendor: this._glVendor,
  5694. renderer: this._glRenderer,
  5695. version: this._glVersion
  5696. };
  5697. };
  5698. Engine.prototype.getAspectRatio = function (camera) {
  5699. var viewport = camera.viewport;
  5700. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5701. };
  5702. Engine.prototype.getRenderWidth = function () {
  5703. if (this._currentRenderTarget) {
  5704. return this._currentRenderTarget._width;
  5705. }
  5706. return this._renderingCanvas.width;
  5707. };
  5708. Engine.prototype.getRenderHeight = function () {
  5709. if (this._currentRenderTarget) {
  5710. return this._currentRenderTarget._height;
  5711. }
  5712. return this._renderingCanvas.height;
  5713. };
  5714. Engine.prototype.getRenderingCanvas = function () {
  5715. return this._renderingCanvas;
  5716. };
  5717. Engine.prototype.getRenderingCanvasClientRect = function () {
  5718. return this._renderingCanvas.getBoundingClientRect();
  5719. };
  5720. Engine.prototype.setHardwareScalingLevel = function (level) {
  5721. this._hardwareScalingLevel = level;
  5722. this.resize();
  5723. };
  5724. Engine.prototype.getHardwareScalingLevel = function () {
  5725. return this._hardwareScalingLevel;
  5726. };
  5727. Engine.prototype.getLoadedTexturesCache = function () {
  5728. return this._loadedTexturesCache;
  5729. };
  5730. Engine.prototype.getCaps = function () {
  5731. return this._caps;
  5732. };
  5733. Object.defineProperty(Engine.prototype, "drawCalls", {
  5734. get: function () {
  5735. return this._drawCalls;
  5736. },
  5737. enumerable: true,
  5738. configurable: true
  5739. });
  5740. // Methods
  5741. Engine.prototype.resetDrawCalls = function () {
  5742. this._drawCalls = 0;
  5743. };
  5744. Engine.prototype.setDepthFunctionToGreater = function () {
  5745. this._depthCullingState.depthFunc = this._gl.GREATER;
  5746. };
  5747. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5748. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5749. };
  5750. Engine.prototype.setDepthFunctionToLess = function () {
  5751. this._depthCullingState.depthFunc = this._gl.LESS;
  5752. };
  5753. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5754. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5755. };
  5756. /**
  5757. * stop executing a render loop function and remove it from the execution array
  5758. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5759. */
  5760. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5761. if (!renderFunction) {
  5762. this._activeRenderLoops = [];
  5763. return;
  5764. }
  5765. var index = this._activeRenderLoops.indexOf(renderFunction);
  5766. if (index >= 0) {
  5767. this._activeRenderLoops.splice(index, 1);
  5768. }
  5769. };
  5770. Engine.prototype._renderLoop = function () {
  5771. var _this = this;
  5772. var shouldRender = true;
  5773. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5774. shouldRender = false;
  5775. }
  5776. if (shouldRender) {
  5777. // Start new frame
  5778. this.beginFrame();
  5779. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5780. var renderFunction = this._activeRenderLoops[index];
  5781. renderFunction();
  5782. }
  5783. // Present
  5784. this.endFrame();
  5785. }
  5786. if (this._activeRenderLoops.length > 0) {
  5787. // Register new frame
  5788. BABYLON.Tools.QueueNewFrame(function () {
  5789. _this._renderLoop();
  5790. });
  5791. }
  5792. else {
  5793. this._renderingQueueLaunched = false;
  5794. }
  5795. };
  5796. /**
  5797. * Register and execute a render loop. The engine can have more than one render function.
  5798. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5799. * @example
  5800. * engine.runRenderLoop(function () {
  5801. * scene.render()
  5802. * })
  5803. */
  5804. Engine.prototype.runRenderLoop = function (renderFunction) {
  5805. var _this = this;
  5806. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5807. return;
  5808. }
  5809. this._activeRenderLoops.push(renderFunction);
  5810. if (!this._renderingQueueLaunched) {
  5811. this._renderingQueueLaunched = true;
  5812. BABYLON.Tools.QueueNewFrame(function () {
  5813. _this._renderLoop();
  5814. });
  5815. }
  5816. };
  5817. /**
  5818. * Toggle full screen mode.
  5819. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5820. */
  5821. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5822. if (this.isFullscreen) {
  5823. BABYLON.Tools.ExitFullscreen();
  5824. }
  5825. else {
  5826. this._pointerLockRequested = requestPointerLock;
  5827. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5828. }
  5829. };
  5830. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5831. this.applyStates();
  5832. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5833. if (this._depthCullingState.depthMask) {
  5834. this._gl.clearDepth(1.0);
  5835. }
  5836. var mode = 0;
  5837. if (backBuffer)
  5838. mode |= this._gl.COLOR_BUFFER_BIT;
  5839. if (depthStencil && this._depthCullingState.depthMask)
  5840. mode |= this._gl.DEPTH_BUFFER_BIT;
  5841. this._gl.clear(mode);
  5842. };
  5843. /**
  5844. * Set the WebGL's viewport
  5845. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5846. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5847. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5848. */
  5849. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5850. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5851. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5852. var x = viewport.x || 0;
  5853. var y = viewport.y || 0;
  5854. this._cachedViewport = viewport;
  5855. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5856. };
  5857. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5858. this._cachedViewport = null;
  5859. this._gl.viewport(x, y, width, height);
  5860. };
  5861. Engine.prototype.beginFrame = function () {
  5862. this._measureFps();
  5863. };
  5864. Engine.prototype.endFrame = function () {
  5865. //this.flushFramebuffer();
  5866. };
  5867. /**
  5868. * resize the view according to the canvas' size.
  5869. * @example
  5870. * window.addEventListener("resize", function () {
  5871. * engine.resize();
  5872. * });
  5873. */
  5874. Engine.prototype.resize = function () {
  5875. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5876. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5877. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5878. };
  5879. /**
  5880. * force a specific size of the canvas
  5881. * @param {number} width - the new canvas' width
  5882. * @param {number} height - the new canvas' height
  5883. */
  5884. Engine.prototype.setSize = function (width, height) {
  5885. this._renderingCanvas.width = width;
  5886. this._renderingCanvas.height = height;
  5887. for (var index = 0; index < this.scenes.length; index++) {
  5888. var scene = this.scenes[index];
  5889. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5890. var cam = scene.cameras[camIndex];
  5891. cam._currentRenderId = 0;
  5892. }
  5893. }
  5894. };
  5895. Engine.prototype.bindFramebuffer = function (texture) {
  5896. this._currentRenderTarget = texture;
  5897. var gl = this._gl;
  5898. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5899. this._gl.viewport(0, 0, texture._width, texture._height);
  5900. this.wipeCaches();
  5901. };
  5902. Engine.prototype.unBindFramebuffer = function (texture) {
  5903. this._currentRenderTarget = null;
  5904. if (texture.generateMipMaps) {
  5905. var gl = this._gl;
  5906. gl.bindTexture(gl.TEXTURE_2D, texture);
  5907. gl.generateMipmap(gl.TEXTURE_2D);
  5908. gl.bindTexture(gl.TEXTURE_2D, null);
  5909. }
  5910. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5911. };
  5912. Engine.prototype.flushFramebuffer = function () {
  5913. this._gl.flush();
  5914. };
  5915. Engine.prototype.restoreDefaultFramebuffer = function () {
  5916. this._currentRenderTarget = null;
  5917. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5918. this.setViewport(this._cachedViewport);
  5919. this.wipeCaches();
  5920. };
  5921. // VBOs
  5922. Engine.prototype._resetVertexBufferBinding = function () {
  5923. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5924. this._cachedVertexBuffers = null;
  5925. };
  5926. Engine.prototype.createVertexBuffer = function (vertices) {
  5927. var vbo = this._gl.createBuffer();
  5928. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5929. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5930. this._resetVertexBufferBinding();
  5931. vbo.references = 1;
  5932. return vbo;
  5933. };
  5934. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5935. var vbo = this._gl.createBuffer();
  5936. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5937. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5938. this._resetVertexBufferBinding();
  5939. vbo.references = 1;
  5940. return vbo;
  5941. };
  5942. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5943. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5944. if (offset === undefined) {
  5945. offset = 0;
  5946. }
  5947. if (vertices instanceof Float32Array) {
  5948. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5949. }
  5950. else {
  5951. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5952. }
  5953. this._resetVertexBufferBinding();
  5954. };
  5955. Engine.prototype._resetIndexBufferBinding = function () {
  5956. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5957. this._cachedIndexBuffer = null;
  5958. };
  5959. Engine.prototype.createIndexBuffer = function (indices) {
  5960. var vbo = this._gl.createBuffer();
  5961. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5962. // Check for 32 bits indices
  5963. var arrayBuffer;
  5964. var need32Bits = false;
  5965. if (this._caps.uintIndices) {
  5966. for (var index = 0; index < indices.length; index++) {
  5967. if (indices[index] > 65535) {
  5968. need32Bits = true;
  5969. break;
  5970. }
  5971. }
  5972. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5973. }
  5974. else {
  5975. arrayBuffer = new Uint16Array(indices);
  5976. }
  5977. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5978. this._resetIndexBufferBinding();
  5979. vbo.references = 1;
  5980. vbo.is32Bits = need32Bits;
  5981. return vbo;
  5982. };
  5983. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5984. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5985. this._cachedVertexBuffers = vertexBuffer;
  5986. this._cachedEffectForVertexBuffers = effect;
  5987. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5988. var offset = 0;
  5989. for (var index = 0; index < vertexDeclaration.length; index++) {
  5990. var order = effect.getAttributeLocation(index);
  5991. if (order >= 0) {
  5992. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5993. }
  5994. offset += vertexDeclaration[index] * 4;
  5995. }
  5996. }
  5997. if (this._cachedIndexBuffer !== indexBuffer) {
  5998. this._cachedIndexBuffer = indexBuffer;
  5999. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6000. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6001. }
  6002. };
  6003. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6004. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6005. this._cachedVertexBuffers = vertexBuffers;
  6006. this._cachedEffectForVertexBuffers = effect;
  6007. var attributes = effect.getAttributesNames();
  6008. for (var index = 0; index < attributes.length; index++) {
  6009. var order = effect.getAttributeLocation(index);
  6010. if (order >= 0) {
  6011. var vertexBuffer = vertexBuffers[attributes[index]];
  6012. if (!vertexBuffer) {
  6013. continue;
  6014. }
  6015. var stride = vertexBuffer.getStrideSize();
  6016. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6017. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6018. }
  6019. }
  6020. }
  6021. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6022. this._cachedIndexBuffer = indexBuffer;
  6023. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6024. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6025. }
  6026. };
  6027. Engine.prototype._releaseBuffer = function (buffer) {
  6028. buffer.references--;
  6029. if (buffer.references === 0) {
  6030. this._gl.deleteBuffer(buffer);
  6031. return true;
  6032. }
  6033. return false;
  6034. };
  6035. Engine.prototype.createInstancesBuffer = function (capacity) {
  6036. var buffer = this._gl.createBuffer();
  6037. buffer.capacity = capacity;
  6038. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6039. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6040. return buffer;
  6041. };
  6042. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6043. this._gl.deleteBuffer(buffer);
  6044. };
  6045. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6046. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6047. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6048. for (var index = 0; index < 4; index++) {
  6049. var offsetLocation = offsetLocations[index];
  6050. this._gl.enableVertexAttribArray(offsetLocation);
  6051. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6052. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6053. }
  6054. };
  6055. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6056. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6057. for (var index = 0; index < 4; index++) {
  6058. var offsetLocation = offsetLocations[index];
  6059. this._gl.disableVertexAttribArray(offsetLocation);
  6060. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6061. }
  6062. };
  6063. Engine.prototype.applyStates = function () {
  6064. this._depthCullingState.apply(this._gl);
  6065. this._alphaState.apply(this._gl);
  6066. };
  6067. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6068. // Apply states
  6069. this.applyStates();
  6070. this._drawCalls++;
  6071. // Render
  6072. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6073. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6074. if (instancesCount) {
  6075. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6076. return;
  6077. }
  6078. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6079. };
  6080. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6081. // Apply states
  6082. this.applyStates();
  6083. this._drawCalls++;
  6084. if (instancesCount) {
  6085. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6086. return;
  6087. }
  6088. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6089. };
  6090. // Shaders
  6091. Engine.prototype._releaseEffect = function (effect) {
  6092. if (this._compiledEffects[effect._key]) {
  6093. delete this._compiledEffects[effect._key];
  6094. if (effect.getProgram()) {
  6095. this._gl.deleteProgram(effect.getProgram());
  6096. }
  6097. }
  6098. };
  6099. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6100. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6101. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6102. var name = vertex + "+" + fragment + "@" + defines;
  6103. if (this._compiledEffects[name]) {
  6104. return this._compiledEffects[name];
  6105. }
  6106. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6107. effect._key = name;
  6108. this._compiledEffects[name] = effect;
  6109. return effect;
  6110. };
  6111. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6112. if (uniformsNames === void 0) { uniformsNames = []; }
  6113. if (samplers === void 0) { samplers = []; }
  6114. if (defines === void 0) { defines = ""; }
  6115. return this.createEffect({
  6116. vertex: "particles",
  6117. fragmentElement: fragmentName
  6118. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6119. };
  6120. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6121. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6122. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6123. var shaderProgram = this._gl.createProgram();
  6124. this._gl.attachShader(shaderProgram, vertexShader);
  6125. this._gl.attachShader(shaderProgram, fragmentShader);
  6126. this._gl.linkProgram(shaderProgram);
  6127. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6128. if (!linked) {
  6129. var error = this._gl.getProgramInfoLog(shaderProgram);
  6130. if (error) {
  6131. throw new Error(error);
  6132. }
  6133. }
  6134. this._gl.deleteShader(vertexShader);
  6135. this._gl.deleteShader(fragmentShader);
  6136. return shaderProgram;
  6137. };
  6138. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6139. var results = [];
  6140. for (var index = 0; index < uniformsNames.length; index++) {
  6141. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6142. }
  6143. return results;
  6144. };
  6145. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6146. var results = [];
  6147. for (var index = 0; index < attributesNames.length; index++) {
  6148. try {
  6149. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6150. }
  6151. catch (e) {
  6152. results.push(-1);
  6153. }
  6154. }
  6155. return results;
  6156. };
  6157. Engine.prototype.enableEffect = function (effect) {
  6158. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6159. if (effect && effect.onBind) {
  6160. effect.onBind(effect);
  6161. }
  6162. return;
  6163. }
  6164. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6165. // Use program
  6166. this._gl.useProgram(effect.getProgram());
  6167. for (var i in this._vertexAttribArrays) {
  6168. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6169. continue;
  6170. }
  6171. this._vertexAttribArrays[i] = false;
  6172. this._gl.disableVertexAttribArray(i);
  6173. }
  6174. var attributesCount = effect.getAttributesCount();
  6175. for (var index = 0; index < attributesCount; index++) {
  6176. // Attributes
  6177. var order = effect.getAttributeLocation(index);
  6178. if (order >= 0) {
  6179. this._vertexAttribArrays[order] = true;
  6180. this._gl.enableVertexAttribArray(order);
  6181. }
  6182. }
  6183. this._currentEffect = effect;
  6184. if (effect.onBind) {
  6185. effect.onBind(effect);
  6186. }
  6187. };
  6188. Engine.prototype.setArray = function (uniform, array) {
  6189. if (!uniform)
  6190. return;
  6191. this._gl.uniform1fv(uniform, array);
  6192. };
  6193. Engine.prototype.setArray2 = function (uniform, array) {
  6194. if (!uniform || array.length % 2 !== 0)
  6195. return;
  6196. this._gl.uniform2fv(uniform, array);
  6197. };
  6198. Engine.prototype.setArray3 = function (uniform, array) {
  6199. if (!uniform || array.length % 3 !== 0)
  6200. return;
  6201. this._gl.uniform3fv(uniform, array);
  6202. };
  6203. Engine.prototype.setArray4 = function (uniform, array) {
  6204. if (!uniform || array.length % 4 !== 0)
  6205. return;
  6206. this._gl.uniform4fv(uniform, array);
  6207. };
  6208. Engine.prototype.setMatrices = function (uniform, matrices) {
  6209. if (!uniform)
  6210. return;
  6211. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6212. };
  6213. Engine.prototype.setMatrix = function (uniform, matrix) {
  6214. if (!uniform)
  6215. return;
  6216. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6217. };
  6218. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6219. if (!uniform)
  6220. return;
  6221. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6222. };
  6223. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6224. if (!uniform)
  6225. return;
  6226. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6227. };
  6228. Engine.prototype.setFloat = function (uniform, value) {
  6229. if (!uniform)
  6230. return;
  6231. this._gl.uniform1f(uniform, value);
  6232. };
  6233. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6234. if (!uniform)
  6235. return;
  6236. this._gl.uniform2f(uniform, x, y);
  6237. };
  6238. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6239. if (!uniform)
  6240. return;
  6241. this._gl.uniform3f(uniform, x, y, z);
  6242. };
  6243. Engine.prototype.setBool = function (uniform, bool) {
  6244. if (!uniform)
  6245. return;
  6246. this._gl.uniform1i(uniform, bool);
  6247. };
  6248. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6249. if (!uniform)
  6250. return;
  6251. this._gl.uniform4f(uniform, x, y, z, w);
  6252. };
  6253. Engine.prototype.setColor3 = function (uniform, color3) {
  6254. if (!uniform)
  6255. return;
  6256. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6257. };
  6258. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6259. if (!uniform)
  6260. return;
  6261. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6262. };
  6263. // States
  6264. Engine.prototype.setState = function (culling, zOffset, force) {
  6265. if (zOffset === void 0) { zOffset = 0; }
  6266. // Culling
  6267. if (this._depthCullingState.cull !== culling || force) {
  6268. if (culling) {
  6269. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6270. this._depthCullingState.cull = true;
  6271. }
  6272. else {
  6273. this._depthCullingState.cull = false;
  6274. }
  6275. }
  6276. // Z offset
  6277. this._depthCullingState.zOffset = zOffset;
  6278. };
  6279. Engine.prototype.setDepthBuffer = function (enable) {
  6280. this._depthCullingState.depthTest = enable;
  6281. };
  6282. Engine.prototype.getDepthWrite = function () {
  6283. return this._depthCullingState.depthMask;
  6284. };
  6285. Engine.prototype.setDepthWrite = function (enable) {
  6286. this._depthCullingState.depthMask = enable;
  6287. };
  6288. Engine.prototype.setColorWrite = function (enable) {
  6289. this._gl.colorMask(enable, enable, enable, enable);
  6290. };
  6291. Engine.prototype.setAlphaMode = function (mode) {
  6292. if (this._alphaMode == mode) {
  6293. return;
  6294. }
  6295. switch (mode) {
  6296. case Engine.ALPHA_DISABLE:
  6297. this.setDepthWrite(true);
  6298. this._alphaState.alphaBlend = false;
  6299. break;
  6300. case Engine.ALPHA_COMBINE:
  6301. this.setDepthWrite(false);
  6302. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6303. this._alphaState.alphaBlend = true;
  6304. break;
  6305. case Engine.ALPHA_ONEONE:
  6306. this.setDepthWrite(false);
  6307. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6308. this._alphaState.alphaBlend = true;
  6309. break;
  6310. case Engine.ALPHA_ADD:
  6311. this.setDepthWrite(false);
  6312. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6313. this._alphaState.alphaBlend = true;
  6314. break;
  6315. case Engine.ALPHA_SUBTRACT:
  6316. this.setDepthWrite(false);
  6317. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6318. this._alphaState.alphaBlend = true;
  6319. break;
  6320. case Engine.ALPHA_MULTIPLY:
  6321. this.setDepthWrite(false);
  6322. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6323. this._alphaState.alphaBlend = true;
  6324. break;
  6325. case Engine.ALPHA_MAXIMIZED:
  6326. this.setDepthWrite(false);
  6327. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6328. this._alphaState.alphaBlend = true;
  6329. break;
  6330. }
  6331. this._alphaMode = mode;
  6332. };
  6333. Engine.prototype.getAlphaMode = function () {
  6334. return this._alphaMode;
  6335. };
  6336. Engine.prototype.setAlphaTesting = function (enable) {
  6337. this._alphaTest = enable;
  6338. };
  6339. Engine.prototype.getAlphaTesting = function () {
  6340. return this._alphaTest;
  6341. };
  6342. // Textures
  6343. Engine.prototype.wipeCaches = function () {
  6344. this._activeTexturesCache = [];
  6345. this._currentEffect = null;
  6346. this._depthCullingState.reset();
  6347. this._alphaState.reset();
  6348. this._cachedVertexBuffers = null;
  6349. this._cachedIndexBuffer = null;
  6350. this._cachedEffectForVertexBuffers = null;
  6351. };
  6352. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6353. var gl = this._gl;
  6354. gl.bindTexture(gl.TEXTURE_2D, texture);
  6355. var magFilter = gl.NEAREST;
  6356. var minFilter = gl.NEAREST;
  6357. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6358. magFilter = gl.LINEAR;
  6359. minFilter = gl.LINEAR;
  6360. }
  6361. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6362. magFilter = gl.LINEAR;
  6363. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6364. }
  6365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6367. gl.bindTexture(gl.TEXTURE_2D, null);
  6368. texture.samplingMode = samplingMode;
  6369. };
  6370. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6371. var _this = this;
  6372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6373. if (onLoad === void 0) { onLoad = null; }
  6374. if (onError === void 0) { onError = null; }
  6375. if (buffer === void 0) { buffer = null; }
  6376. var texture = this._gl.createTexture();
  6377. var extension;
  6378. var fromData = false;
  6379. if (url.substr(0, 5) === "data:") {
  6380. fromData = true;
  6381. }
  6382. if (!fromData)
  6383. extension = url.substr(url.length - 4, 4).toLowerCase();
  6384. else {
  6385. var oldUrl = url;
  6386. fromData = oldUrl.split(':');
  6387. url = oldUrl;
  6388. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6389. }
  6390. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6391. var isTGA = (extension === ".tga");
  6392. scene._addPendingData(texture);
  6393. texture.url = url;
  6394. texture.noMipmap = noMipmap;
  6395. texture.references = 1;
  6396. texture.samplingMode = samplingMode;
  6397. this._loadedTexturesCache.push(texture);
  6398. var onerror = function () {
  6399. scene._removePendingData(texture);
  6400. if (onError) {
  6401. onError();
  6402. }
  6403. };
  6404. if (isTGA) {
  6405. var callback = function (arrayBuffer) {
  6406. var data = new Uint8Array(arrayBuffer);
  6407. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6408. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6409. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6410. if (onLoad) {
  6411. onLoad();
  6412. }
  6413. }, samplingMode);
  6414. };
  6415. if (!(fromData instanceof Array))
  6416. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6417. callback(arrayBuffer);
  6418. }, onerror, scene.database, true);
  6419. else
  6420. callback(buffer);
  6421. }
  6422. else if (isDDS) {
  6423. callback = function (data) {
  6424. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6425. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6426. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6427. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6428. if (onLoad) {
  6429. onLoad();
  6430. }
  6431. }, samplingMode);
  6432. };
  6433. if (!(fromData instanceof Array))
  6434. BABYLON.Tools.LoadFile(url, function (data) {
  6435. callback(data);
  6436. }, onerror, scene.database, true);
  6437. else
  6438. callback(buffer);
  6439. }
  6440. else {
  6441. var onload = function (img) {
  6442. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6443. var isPot = (img.width === potWidth && img.height === potHeight);
  6444. if (!isPot) {
  6445. _this._prepareWorkingCanvas();
  6446. _this._workingCanvas.width = potWidth;
  6447. _this._workingCanvas.height = potHeight;
  6448. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6449. _this._workingContext.imageSmoothingEnabled = false;
  6450. _this._workingContext.mozImageSmoothingEnabled = false;
  6451. _this._workingContext.oImageSmoothingEnabled = false;
  6452. _this._workingContext.webkitImageSmoothingEnabled = false;
  6453. _this._workingContext.msImageSmoothingEnabled = false;
  6454. }
  6455. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6456. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6457. _this._workingContext.imageSmoothingEnabled = true;
  6458. _this._workingContext.mozImageSmoothingEnabled = true;
  6459. _this._workingContext.oImageSmoothingEnabled = true;
  6460. _this._workingContext.webkitImageSmoothingEnabled = true;
  6461. _this._workingContext.msImageSmoothingEnabled = true;
  6462. }
  6463. }
  6464. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6465. if (onLoad) {
  6466. onLoad();
  6467. }
  6468. }, samplingMode);
  6469. };
  6470. if (!(fromData instanceof Array))
  6471. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6472. else
  6473. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6474. }
  6475. return texture;
  6476. };
  6477. Engine.prototype.updateRawTexture = function (texture, data, format, invertY) {
  6478. var internalFormat = this._gl.RGBA;
  6479. switch (format) {
  6480. case Engine.TEXTUREFORMAT_ALPHA:
  6481. internalFormat = this._gl.ALPHA;
  6482. break;
  6483. case Engine.TEXTUREFORMAT_LUMINANCE:
  6484. internalFormat = this._gl.LUMINANCE;
  6485. break;
  6486. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6487. internalFormat = this._gl.LUMINANCE_ALPHA;
  6488. break;
  6489. case Engine.TEXTUREFORMAT_RGB:
  6490. internalFormat = this._gl.RGB;
  6491. break;
  6492. case Engine.TEXTUREFORMAT_RGBA:
  6493. internalFormat = this._gl.RGBA;
  6494. break;
  6495. }
  6496. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6497. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6498. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6499. if (texture.generateMipMaps) {
  6500. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6501. }
  6502. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6503. this._activeTexturesCache = [];
  6504. texture.isReady = true;
  6505. };
  6506. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6507. var texture = this._gl.createTexture();
  6508. texture._baseWidth = width;
  6509. texture._baseHeight = height;
  6510. texture._width = width;
  6511. texture._height = height;
  6512. texture.references = 1;
  6513. this.updateRawTexture(texture, data, format, invertY);
  6514. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6515. // Filters
  6516. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6517. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6518. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6519. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6520. texture.samplingMode = samplingMode;
  6521. this._loadedTexturesCache.push(texture);
  6522. return texture;
  6523. };
  6524. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6525. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6526. var texture = this._gl.createTexture();
  6527. texture._baseWidth = width;
  6528. texture._baseHeight = height;
  6529. if (forceExponantOfTwo) {
  6530. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6531. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6532. }
  6533. this._activeTexturesCache = [];
  6534. texture._width = width;
  6535. texture._height = height;
  6536. texture.isReady = false;
  6537. texture.generateMipMaps = generateMipMaps;
  6538. texture.references = 1;
  6539. texture.samplingMode = samplingMode;
  6540. this.updateTextureSamplingMode(samplingMode, texture);
  6541. this._loadedTexturesCache.push(texture);
  6542. return texture;
  6543. };
  6544. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6545. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6546. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6547. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6548. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6549. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6550. };
  6551. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6552. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6553. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6554. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6555. if (texture.generateMipMaps) {
  6556. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6557. }
  6558. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6559. this._activeTexturesCache = [];
  6560. texture.isReady = true;
  6561. };
  6562. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6563. if (texture._isDisabled) {
  6564. return;
  6565. }
  6566. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6567. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6568. try {
  6569. // Testing video texture support
  6570. if (this._videoTextureSupported === undefined) {
  6571. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6572. if (this._gl.getError() !== 0) {
  6573. this._videoTextureSupported = false;
  6574. }
  6575. else {
  6576. this._videoTextureSupported = true;
  6577. }
  6578. }
  6579. // Copy video through the current working canvas if video texture is not supported
  6580. if (!this._videoTextureSupported) {
  6581. if (!texture._workingCanvas) {
  6582. texture._workingCanvas = document.createElement("canvas");
  6583. texture._workingContext = texture._workingCanvas.getContext("2d");
  6584. texture._workingCanvas.width = texture._width;
  6585. texture._workingCanvas.height = texture._height;
  6586. }
  6587. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6588. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6589. }
  6590. else {
  6591. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6592. }
  6593. if (texture.generateMipMaps) {
  6594. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6595. }
  6596. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6597. this._activeTexturesCache = [];
  6598. texture.isReady = true;
  6599. }
  6600. catch (ex) {
  6601. // Something unexpected
  6602. // Let's disable the texture
  6603. texture._isDisabled = true;
  6604. }
  6605. };
  6606. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6607. // old version had a "generateMipMaps" arg instead of options.
  6608. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6609. // in the same way, generateDepthBuffer is defaulted to true
  6610. var generateMipMaps = false;
  6611. var generateDepthBuffer = true;
  6612. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6613. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6614. if (options !== undefined) {
  6615. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6616. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6617. type = options.type === undefined ? type : options.type;
  6618. if (options.samplingMode !== undefined) {
  6619. samplingMode = options.samplingMode;
  6620. }
  6621. if (type === Engine.TEXTURETYPE_FLOAT) {
  6622. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6623. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6624. }
  6625. }
  6626. var gl = this._gl;
  6627. var texture = gl.createTexture();
  6628. gl.bindTexture(gl.TEXTURE_2D, texture);
  6629. var width = size.width || size;
  6630. var height = size.height || size;
  6631. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6632. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6633. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6634. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6635. }
  6636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6637. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6638. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6639. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6640. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6641. var depthBuffer;
  6642. // Create the depth buffer
  6643. if (generateDepthBuffer) {
  6644. depthBuffer = gl.createRenderbuffer();
  6645. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6646. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6647. }
  6648. // Create the framebuffer
  6649. var framebuffer = gl.createFramebuffer();
  6650. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6651. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6652. if (generateDepthBuffer) {
  6653. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6654. }
  6655. if (generateMipMaps) {
  6656. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6657. }
  6658. // Unbind
  6659. gl.bindTexture(gl.TEXTURE_2D, null);
  6660. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6661. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6662. texture._framebuffer = framebuffer;
  6663. if (generateDepthBuffer) {
  6664. texture._depthBuffer = depthBuffer;
  6665. }
  6666. texture._width = width;
  6667. texture._height = height;
  6668. texture.isReady = true;
  6669. texture.generateMipMaps = generateMipMaps;
  6670. texture.references = 1;
  6671. texture.samplingMode = samplingMode;
  6672. this._activeTexturesCache = [];
  6673. this._loadedTexturesCache.push(texture);
  6674. return texture;
  6675. };
  6676. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6677. var _this = this;
  6678. var gl = this._gl;
  6679. var texture = gl.createTexture();
  6680. texture.isCube = true;
  6681. texture.url = rootUrl;
  6682. texture.references = 1;
  6683. this._loadedTexturesCache.push(texture);
  6684. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6685. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6686. if (isDDS) {
  6687. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6688. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6689. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6690. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6691. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6692. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6693. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6694. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6695. }
  6696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6700. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6701. _this._activeTexturesCache = [];
  6702. texture._width = info.width;
  6703. texture._height = info.height;
  6704. texture.isReady = true;
  6705. }, null, null, true);
  6706. }
  6707. else {
  6708. cascadeLoad(rootUrl, scene, function (imgs) {
  6709. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6710. var height = width;
  6711. _this._prepareWorkingCanvas();
  6712. _this._workingCanvas.width = width;
  6713. _this._workingCanvas.height = height;
  6714. var faces = [
  6715. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6716. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6717. ];
  6718. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6719. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6720. for (var index = 0; index < faces.length; index++) {
  6721. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6722. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6723. }
  6724. if (!noMipmap) {
  6725. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6726. }
  6727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6731. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6732. _this._activeTexturesCache = [];
  6733. texture._width = width;
  6734. texture._height = height;
  6735. texture.isReady = true;
  6736. }, extensions);
  6737. }
  6738. return texture;
  6739. };
  6740. Engine.prototype._releaseTexture = function (texture) {
  6741. var gl = this._gl;
  6742. if (texture._framebuffer) {
  6743. gl.deleteFramebuffer(texture._framebuffer);
  6744. }
  6745. if (texture._depthBuffer) {
  6746. gl.deleteRenderbuffer(texture._depthBuffer);
  6747. }
  6748. gl.deleteTexture(texture);
  6749. // Unbind channels
  6750. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6751. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6752. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6753. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6754. this._activeTexturesCache[channel] = null;
  6755. }
  6756. var index = this._loadedTexturesCache.indexOf(texture);
  6757. if (index !== -1) {
  6758. this._loadedTexturesCache.splice(index, 1);
  6759. }
  6760. };
  6761. Engine.prototype.bindSamplers = function (effect) {
  6762. this._gl.useProgram(effect.getProgram());
  6763. var samplers = effect.getSamplers();
  6764. for (var index = 0; index < samplers.length; index++) {
  6765. var uniform = effect.getUniform(samplers[index]);
  6766. this._gl.uniform1i(uniform, index);
  6767. }
  6768. this._currentEffect = null;
  6769. };
  6770. Engine.prototype._bindTexture = function (channel, texture) {
  6771. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6772. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6773. this._activeTexturesCache[channel] = null;
  6774. };
  6775. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6776. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6777. };
  6778. Engine.prototype.setTexture = function (channel, texture) {
  6779. if (channel < 0) {
  6780. return;
  6781. }
  6782. // Not ready?
  6783. if (!texture || !texture.isReady()) {
  6784. if (this._activeTexturesCache[channel] != null) {
  6785. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6786. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6787. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6788. this._activeTexturesCache[channel] = null;
  6789. }
  6790. return;
  6791. }
  6792. // Video
  6793. if (texture instanceof BABYLON.VideoTexture) {
  6794. if (texture.update()) {
  6795. this._activeTexturesCache[channel] = null;
  6796. }
  6797. }
  6798. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6799. texture.delayLoad();
  6800. return;
  6801. }
  6802. if (this._activeTexturesCache[channel] === texture) {
  6803. return;
  6804. }
  6805. this._activeTexturesCache[channel] = texture;
  6806. var internalTexture = texture.getInternalTexture();
  6807. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6808. if (internalTexture.isCube) {
  6809. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6810. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6811. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6812. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6813. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6814. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6815. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6816. }
  6817. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6818. }
  6819. else {
  6820. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6821. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6822. internalTexture._cachedWrapU = texture.wrapU;
  6823. switch (texture.wrapU) {
  6824. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6825. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6826. break;
  6827. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6828. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6829. break;
  6830. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6831. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6832. break;
  6833. }
  6834. }
  6835. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6836. internalTexture._cachedWrapV = texture.wrapV;
  6837. switch (texture.wrapV) {
  6838. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6839. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6840. break;
  6841. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6842. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6843. break;
  6844. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6845. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6846. break;
  6847. }
  6848. }
  6849. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6850. }
  6851. };
  6852. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6853. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6854. var value = texture.anisotropicFilteringLevel;
  6855. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6856. value = 1;
  6857. }
  6858. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6859. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6860. texture._cachedAnisotropicFilteringLevel = value;
  6861. }
  6862. };
  6863. Engine.prototype.readPixels = function (x, y, width, height) {
  6864. var data = new Uint8Array(height * width * 4);
  6865. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6866. return data;
  6867. };
  6868. // Dispose
  6869. Engine.prototype.dispose = function () {
  6870. this.hideLoadingUI();
  6871. this.stopRenderLoop();
  6872. // Release scenes
  6873. while (this.scenes.length) {
  6874. this.scenes[0].dispose();
  6875. }
  6876. // Release audio engine
  6877. Engine.audioEngine.dispose();
  6878. // Release effects
  6879. for (var name in this._compiledEffects) {
  6880. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6881. }
  6882. // Unbind
  6883. for (var i in this._vertexAttribArrays) {
  6884. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6885. continue;
  6886. }
  6887. this._gl.disableVertexAttribArray(i);
  6888. }
  6889. this._gl = null;
  6890. // Events
  6891. window.removeEventListener("blur", this._onBlur);
  6892. window.removeEventListener("focus", this._onFocus);
  6893. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6894. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6895. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6896. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6897. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6898. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6899. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6900. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6901. };
  6902. // Loading screen
  6903. Engine.prototype.displayLoadingUI = function () {
  6904. var _this = this;
  6905. this._loadingDiv = document.createElement("div");
  6906. this._loadingDiv.style.opacity = "0";
  6907. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6908. // Loading text
  6909. this._loadingTextDiv = document.createElement("div");
  6910. this._loadingTextDiv.style.position = "absolute";
  6911. this._loadingTextDiv.style.left = "0";
  6912. this._loadingTextDiv.style.top = "50%";
  6913. this._loadingTextDiv.style.marginTop = "80px";
  6914. this._loadingTextDiv.style.width = "100%";
  6915. this._loadingTextDiv.style.height = "20px";
  6916. this._loadingTextDiv.style.fontFamily = "Arial";
  6917. this._loadingTextDiv.style.fontSize = "14px";
  6918. this._loadingTextDiv.style.color = "white";
  6919. this._loadingTextDiv.style.textAlign = "center";
  6920. this._loadingTextDiv.innerHTML = "Loading";
  6921. this._loadingDiv.appendChild(this._loadingTextDiv);
  6922. // Loading img
  6923. var imgBack = new Image();
  6924. 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==";
  6925. imgBack.style.position = "absolute";
  6926. imgBack.style.left = "50%";
  6927. imgBack.style.top = "50%";
  6928. imgBack.style.marginLeft = "-50px";
  6929. imgBack.style.marginTop = "-50px";
  6930. imgBack.style.transition = "transform 1.0s ease";
  6931. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6932. var deg = 360;
  6933. var onTransitionEnd = function () {
  6934. deg += 360;
  6935. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6936. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6937. };
  6938. imgBack.addEventListener("transitionend", onTransitionEnd);
  6939. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6940. this._loadingDiv.appendChild(imgBack);
  6941. // front image
  6942. var imgFront = new Image();
  6943. 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=";
  6944. imgFront.style.position = "absolute";
  6945. imgFront.style.left = "50%";
  6946. imgFront.style.top = "50%";
  6947. imgFront.style.marginLeft = "-50px";
  6948. imgFront.style.marginTop = "-50px";
  6949. this._loadingDiv.appendChild(imgFront);
  6950. // Resize
  6951. this._resizeLoadingUI = function () {
  6952. var canvasRect = _this.getRenderingCanvasClientRect();
  6953. _this._loadingDiv.style.position = "absolute";
  6954. _this._loadingDiv.style.left = canvasRect.left + "px";
  6955. _this._loadingDiv.style.top = canvasRect.top + "px";
  6956. _this._loadingDiv.style.width = canvasRect.width + "px";
  6957. _this._loadingDiv.style.height = canvasRect.height + "px";
  6958. };
  6959. this._resizeLoadingUI();
  6960. window.addEventListener("resize", this._resizeLoadingUI);
  6961. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6962. document.body.appendChild(this._loadingDiv);
  6963. setTimeout(function () {
  6964. _this._loadingDiv.style.opacity = "1";
  6965. imgBack.style.transform = "rotateZ(360deg)";
  6966. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6967. }, 0);
  6968. };
  6969. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6970. set: function (text) {
  6971. if (!this._loadingDiv) {
  6972. return;
  6973. }
  6974. this._loadingTextDiv.innerHTML = text;
  6975. },
  6976. enumerable: true,
  6977. configurable: true
  6978. });
  6979. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6980. get: function () {
  6981. return this._loadingDivBackgroundColor;
  6982. },
  6983. set: function (color) {
  6984. this._loadingDivBackgroundColor = color;
  6985. if (!this._loadingDiv) {
  6986. return;
  6987. }
  6988. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6989. },
  6990. enumerable: true,
  6991. configurable: true
  6992. });
  6993. Engine.prototype.hideLoadingUI = function () {
  6994. var _this = this;
  6995. if (!this._loadingDiv) {
  6996. return;
  6997. }
  6998. var onTransitionEnd = function () {
  6999. if (!_this._loadingDiv) {
  7000. return;
  7001. }
  7002. document.body.removeChild(_this._loadingDiv);
  7003. window.removeEventListener("resize", _this._resizeLoadingUI);
  7004. _this._loadingDiv = null;
  7005. };
  7006. this._loadingDiv.style.opacity = "0";
  7007. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  7008. };
  7009. // FPS
  7010. Engine.prototype.getFps = function () {
  7011. return this.fps;
  7012. };
  7013. Engine.prototype.getDeltaTime = function () {
  7014. return this.deltaTime;
  7015. };
  7016. Engine.prototype._measureFps = function () {
  7017. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7018. var length = this.previousFramesDuration.length;
  7019. if (length >= 2) {
  7020. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7021. }
  7022. if (length >= this.fpsRange) {
  7023. if (length > this.fpsRange) {
  7024. this.previousFramesDuration.splice(0, 1);
  7025. length = this.previousFramesDuration.length;
  7026. }
  7027. var sum = 0;
  7028. for (var id = 0; id < length - 1; id++) {
  7029. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7030. }
  7031. this.fps = 1000.0 / (sum / (length - 1));
  7032. }
  7033. };
  7034. // Statics
  7035. Engine.isSupported = function () {
  7036. try {
  7037. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7038. if (navigator.isCocoonJS) {
  7039. return true;
  7040. }
  7041. var tempcanvas = document.createElement("canvas");
  7042. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7043. return gl != null && !!window.WebGLRenderingContext;
  7044. }
  7045. catch (e) {
  7046. return false;
  7047. }
  7048. };
  7049. // Const statics
  7050. Engine._ALPHA_DISABLE = 0;
  7051. Engine._ALPHA_ADD = 1;
  7052. Engine._ALPHA_COMBINE = 2;
  7053. Engine._ALPHA_SUBTRACT = 3;
  7054. Engine._ALPHA_MULTIPLY = 4;
  7055. Engine._ALPHA_MAXIMIZED = 5;
  7056. Engine._ALPHA_ONEONE = 6;
  7057. Engine._DELAYLOADSTATE_NONE = 0;
  7058. Engine._DELAYLOADSTATE_LOADED = 1;
  7059. Engine._DELAYLOADSTATE_LOADING = 2;
  7060. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7061. Engine._TEXTUREFORMAT_ALPHA = 0;
  7062. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7063. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7064. Engine._TEXTUREFORMAT_RGB = 4;
  7065. Engine._TEXTUREFORMAT_RGBA = 5;
  7066. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7067. Engine._TEXTURETYPE_FLOAT = 1;
  7068. // Updatable statics so stick with vars here
  7069. Engine.Epsilon = 0.001;
  7070. Engine.CollisionsEpsilon = 0.001;
  7071. Engine.CodeRepository = "src/";
  7072. Engine.ShadersRepository = "src/Shaders/";
  7073. return Engine;
  7074. })();
  7075. BABYLON.Engine = Engine;
  7076. })(BABYLON || (BABYLON = {}));
  7077. var BABYLON;
  7078. (function (BABYLON) {
  7079. /**
  7080. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7081. */
  7082. var Node = (function () {
  7083. /**
  7084. * @constructor
  7085. * @param {string} name - the name and id to be given to this node
  7086. * @param {BABYLON.Scene} the scene this node will be added to
  7087. */
  7088. function Node(name, scene) {
  7089. this.state = "";
  7090. this.animations = new Array();
  7091. this._childrenFlag = -1;
  7092. this._isEnabled = true;
  7093. this._isReady = true;
  7094. this._currentRenderId = -1;
  7095. this._parentRenderId = -1;
  7096. this.name = name;
  7097. this.id = name;
  7098. this._scene = scene;
  7099. this._initCache();
  7100. }
  7101. Node.prototype.getScene = function () {
  7102. return this._scene;
  7103. };
  7104. Node.prototype.getEngine = function () {
  7105. return this._scene.getEngine();
  7106. };
  7107. // override it in derived class
  7108. Node.prototype.getWorldMatrix = function () {
  7109. return BABYLON.Matrix.Identity();
  7110. };
  7111. // override it in derived class if you add new variables to the cache
  7112. // and call the parent class method
  7113. Node.prototype._initCache = function () {
  7114. this._cache = {};
  7115. this._cache.parent = undefined;
  7116. };
  7117. Node.prototype.updateCache = function (force) {
  7118. if (!force && this.isSynchronized())
  7119. return;
  7120. this._cache.parent = this.parent;
  7121. this._updateCache();
  7122. };
  7123. // override it in derived class if you add new variables to the cache
  7124. // and call the parent class method if !ignoreParentClass
  7125. Node.prototype._updateCache = function (ignoreParentClass) {
  7126. };
  7127. // override it in derived class if you add new variables to the cache
  7128. Node.prototype._isSynchronized = function () {
  7129. return true;
  7130. };
  7131. Node.prototype._markSyncedWithParent = function () {
  7132. this._parentRenderId = this.parent._currentRenderId;
  7133. };
  7134. Node.prototype.isSynchronizedWithParent = function () {
  7135. if (!this.parent) {
  7136. return true;
  7137. }
  7138. if (this._parentRenderId !== this.parent._currentRenderId) {
  7139. return false;
  7140. }
  7141. return this.parent.isSynchronized();
  7142. };
  7143. Node.prototype.isSynchronized = function (updateCache) {
  7144. var check = this.hasNewParent();
  7145. check = check || !this.isSynchronizedWithParent();
  7146. check = check || !this._isSynchronized();
  7147. if (updateCache)
  7148. this.updateCache(true);
  7149. return !check;
  7150. };
  7151. Node.prototype.hasNewParent = function (update) {
  7152. if (this._cache.parent === this.parent)
  7153. return false;
  7154. if (update)
  7155. this._cache.parent = this.parent;
  7156. return true;
  7157. };
  7158. /**
  7159. * Is this node ready to be used/rendered
  7160. * @return {boolean} is it ready
  7161. */
  7162. Node.prototype.isReady = function () {
  7163. return this._isReady;
  7164. };
  7165. /**
  7166. * Is this node enabled.
  7167. * If the node has a parent and is enabled, the parent will be inspected as well.
  7168. * @return {boolean} whether this node (and its parent) is enabled.
  7169. * @see setEnabled
  7170. */
  7171. Node.prototype.isEnabled = function () {
  7172. if (!this._isEnabled) {
  7173. return false;
  7174. }
  7175. if (this.parent) {
  7176. return this.parent.isEnabled();
  7177. }
  7178. return true;
  7179. };
  7180. /**
  7181. * Set the enabled state of this node.
  7182. * @param {boolean} value - the new enabled state
  7183. * @see isEnabled
  7184. */
  7185. Node.prototype.setEnabled = function (value) {
  7186. this._isEnabled = value;
  7187. };
  7188. /**
  7189. * Is this node a descendant of the given node.
  7190. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7191. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7192. * @see parent
  7193. */
  7194. Node.prototype.isDescendantOf = function (ancestor) {
  7195. if (this.parent) {
  7196. if (this.parent === ancestor) {
  7197. return true;
  7198. }
  7199. return this.parent.isDescendantOf(ancestor);
  7200. }
  7201. return false;
  7202. };
  7203. Node.prototype._getDescendants = function (list, results) {
  7204. for (var index = 0; index < list.length; index++) {
  7205. var item = list[index];
  7206. if (item.isDescendantOf(this)) {
  7207. results.push(item);
  7208. }
  7209. }
  7210. };
  7211. /**
  7212. * Will return all nodes that have this node as parent.
  7213. * @return {BABYLON.Node[]} all children nodes of all types.
  7214. */
  7215. Node.prototype.getDescendants = function () {
  7216. var results = [];
  7217. this._getDescendants(this._scene.meshes, results);
  7218. this._getDescendants(this._scene.lights, results);
  7219. this._getDescendants(this._scene.cameras, results);
  7220. return results;
  7221. };
  7222. Node.prototype._setReady = function (state) {
  7223. if (state == this._isReady) {
  7224. return;
  7225. }
  7226. if (!state) {
  7227. this._isReady = false;
  7228. return;
  7229. }
  7230. this._isReady = true;
  7231. if (this.onReady) {
  7232. this.onReady(this);
  7233. }
  7234. };
  7235. return Node;
  7236. })();
  7237. BABYLON.Node = Node;
  7238. })(BABYLON || (BABYLON = {}));
  7239. var BABYLON;
  7240. (function (BABYLON) {
  7241. var FilesInput = (function () {
  7242. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7243. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7244. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7245. this._engine = p_engine;
  7246. this._canvas = p_canvas;
  7247. this._currentScene = p_scene;
  7248. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7249. this._progressCallback = p_progressCallback;
  7250. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7251. this._textureLoadingCallback = p_textureLoadingCallback;
  7252. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7253. }
  7254. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7255. var _this = this;
  7256. if (p_elementToMonitor) {
  7257. this._elementToMonitor = p_elementToMonitor;
  7258. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7259. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7260. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7261. }
  7262. };
  7263. FilesInput.prototype.renderFunction = function () {
  7264. if (this._additionnalRenderLoopLogicCallback) {
  7265. this._additionnalRenderLoopLogicCallback();
  7266. }
  7267. if (this._currentScene) {
  7268. if (this._textureLoadingCallback) {
  7269. var remaining = this._currentScene.getWaitingItemsCount();
  7270. if (remaining > 0) {
  7271. this._textureLoadingCallback(remaining);
  7272. }
  7273. }
  7274. this._currentScene.render();
  7275. }
  7276. };
  7277. FilesInput.prototype.drag = function (e) {
  7278. e.stopPropagation();
  7279. e.preventDefault();
  7280. };
  7281. FilesInput.prototype.drop = function (eventDrop) {
  7282. eventDrop.stopPropagation();
  7283. eventDrop.preventDefault();
  7284. this.loadFiles(eventDrop);
  7285. };
  7286. FilesInput.prototype.loadFiles = function (event) {
  7287. if (this._startingProcessingFilesCallback)
  7288. this._startingProcessingFilesCallback();
  7289. // Handling data transfer via drag'n'drop
  7290. if (event && event.dataTransfer && event.dataTransfer.files) {
  7291. this._filesToLoad = event.dataTransfer.files;
  7292. }
  7293. // Handling files from input files
  7294. if (event && event.target && event.target.files) {
  7295. this._filesToLoad = event.target.files;
  7296. }
  7297. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7298. for (var i = 0; i < this._filesToLoad.length; i++) {
  7299. switch (this._filesToLoad[i].type) {
  7300. case "image/jpeg":
  7301. case "image/png":
  7302. case "image/bmp":
  7303. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7304. break;
  7305. case "image/targa":
  7306. case "image/vnd.ms-dds":
  7307. case "audio/wav":
  7308. case "audio/x-wav":
  7309. case "audio/mp3":
  7310. case "audio/mpeg":
  7311. case "audio/mpeg3":
  7312. case "audio/x-mpeg-3":
  7313. case "audio/ogg":
  7314. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7315. break;
  7316. default:
  7317. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7318. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7319. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7320. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7321. this._sceneFileToLoad = this._filesToLoad[i];
  7322. }
  7323. break;
  7324. }
  7325. }
  7326. this.reload();
  7327. }
  7328. };
  7329. FilesInput.prototype.reload = function () {
  7330. var _this = this;
  7331. var that = this;
  7332. // If a ".babylon" file has been provided
  7333. if (this._sceneFileToLoad) {
  7334. if (this._currentScene) {
  7335. if (BABYLON.Tools.errorsCount > 0) {
  7336. BABYLON.Tools.ClearLogCache();
  7337. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7338. }
  7339. this._engine.stopRenderLoop();
  7340. this._currentScene.dispose();
  7341. }
  7342. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7343. that._currentScene = newScene;
  7344. // Wait for textures and shaders to be ready
  7345. that._currentScene.executeWhenReady(function () {
  7346. // Attach camera to canvas inputs
  7347. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7348. that._currentScene.createDefaultCameraOrLight();
  7349. }
  7350. that._currentScene.activeCamera.attachControl(that._canvas);
  7351. if (that._sceneLoadedCallback) {
  7352. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7353. }
  7354. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7355. });
  7356. }, function (progress) {
  7357. if (_this._progressCallback) {
  7358. _this._progressCallback(progress);
  7359. }
  7360. });
  7361. }
  7362. else {
  7363. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7364. }
  7365. };
  7366. FilesInput.FilesTextures = new Array();
  7367. FilesInput.FilesToLoad = new Array();
  7368. return FilesInput;
  7369. })();
  7370. BABYLON.FilesInput = FilesInput;
  7371. })(BABYLON || (BABYLON = {}));
  7372. var BABYLON;
  7373. (function (BABYLON) {
  7374. var IntersectionInfo = (function () {
  7375. function IntersectionInfo(bu, bv, distance) {
  7376. this.bu = bu;
  7377. this.bv = bv;
  7378. this.distance = distance;
  7379. this.faceId = 0;
  7380. this.subMeshId = 0;
  7381. }
  7382. return IntersectionInfo;
  7383. })();
  7384. BABYLON.IntersectionInfo = IntersectionInfo;
  7385. var PickingInfo = (function () {
  7386. function PickingInfo() {
  7387. this.hit = false;
  7388. this.distance = 0;
  7389. this.pickedPoint = null;
  7390. this.pickedMesh = null;
  7391. this.bu = 0;
  7392. this.bv = 0;
  7393. this.faceId = -1;
  7394. this.subMeshId = 0;
  7395. }
  7396. // Methods
  7397. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7398. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7399. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7400. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7401. return null;
  7402. }
  7403. var indices = this.pickedMesh.getIndices();
  7404. var result;
  7405. if (useVerticesNormals) {
  7406. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7407. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7408. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7409. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7410. normal0 = normal0.scale(this.bu);
  7411. normal1 = normal1.scale(this.bv);
  7412. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7413. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7414. }
  7415. else {
  7416. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7417. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7418. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7419. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7420. var p1p2 = vertex1.subtract(vertex2);
  7421. var p3p2 = vertex3.subtract(vertex2);
  7422. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7423. }
  7424. if (useWorldCoordinates) {
  7425. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7426. }
  7427. return BABYLON.Vector3.Normalize(result);
  7428. };
  7429. PickingInfo.prototype.getTextureCoordinates = function () {
  7430. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7431. return null;
  7432. }
  7433. var indices = this.pickedMesh.getIndices();
  7434. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7435. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7436. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7437. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7438. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7439. uv1 = uv1.scale(this.bu);
  7440. uv2 = uv2.scale(this.bv);
  7441. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7442. };
  7443. return PickingInfo;
  7444. })();
  7445. BABYLON.PickingInfo = PickingInfo;
  7446. })(BABYLON || (BABYLON = {}));
  7447. var BABYLON;
  7448. (function (BABYLON) {
  7449. var BoundingSphere = (function () {
  7450. function BoundingSphere(minimum, maximum) {
  7451. this.minimum = minimum;
  7452. this.maximum = maximum;
  7453. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7454. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7455. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7456. this.radius = distance * 0.5;
  7457. this.centerWorld = BABYLON.Vector3.Zero();
  7458. this._update(BABYLON.Matrix.Identity());
  7459. }
  7460. // Methods
  7461. BoundingSphere.prototype._update = function (world) {
  7462. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7463. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7464. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7465. };
  7466. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7467. for (var i = 0; i < 6; i++) {
  7468. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7469. return false;
  7470. }
  7471. return true;
  7472. };
  7473. BoundingSphere.prototype.intersectsPoint = function (point) {
  7474. var x = this.centerWorld.x - point.x;
  7475. var y = this.centerWorld.y - point.y;
  7476. var z = this.centerWorld.z - point.z;
  7477. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7478. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7479. return false;
  7480. return true;
  7481. };
  7482. // Statics
  7483. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7484. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7485. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7486. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7487. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7488. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7489. return false;
  7490. return true;
  7491. };
  7492. return BoundingSphere;
  7493. })();
  7494. BABYLON.BoundingSphere = BoundingSphere;
  7495. })(BABYLON || (BABYLON = {}));
  7496. var BABYLON;
  7497. (function (BABYLON) {
  7498. var BoundingBox = (function () {
  7499. function BoundingBox(minimum, maximum) {
  7500. this.minimum = minimum;
  7501. this.maximum = maximum;
  7502. this.vectors = new Array();
  7503. this.vectorsWorld = new Array();
  7504. // Bounding vectors
  7505. this.vectors.push(this.minimum.clone());
  7506. this.vectors.push(this.maximum.clone());
  7507. this.vectors.push(this.minimum.clone());
  7508. this.vectors[2].x = this.maximum.x;
  7509. this.vectors.push(this.minimum.clone());
  7510. this.vectors[3].y = this.maximum.y;
  7511. this.vectors.push(this.minimum.clone());
  7512. this.vectors[4].z = this.maximum.z;
  7513. this.vectors.push(this.maximum.clone());
  7514. this.vectors[5].z = this.minimum.z;
  7515. this.vectors.push(this.maximum.clone());
  7516. this.vectors[6].x = this.minimum.x;
  7517. this.vectors.push(this.maximum.clone());
  7518. this.vectors[7].y = this.minimum.y;
  7519. // OBB
  7520. this.center = this.maximum.add(this.minimum).scale(0.5);
  7521. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7522. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7523. // World
  7524. for (var index = 0; index < this.vectors.length; index++) {
  7525. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7526. }
  7527. this.minimumWorld = BABYLON.Vector3.Zero();
  7528. this.maximumWorld = BABYLON.Vector3.Zero();
  7529. this._update(BABYLON.Matrix.Identity());
  7530. }
  7531. // Methods
  7532. BoundingBox.prototype.getWorldMatrix = function () {
  7533. return this._worldMatrix;
  7534. };
  7535. BoundingBox.prototype._update = function (world) {
  7536. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7537. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7538. for (var index = 0; index < this.vectors.length; index++) {
  7539. var v = this.vectorsWorld[index];
  7540. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7541. if (v.x < this.minimumWorld.x)
  7542. this.minimumWorld.x = v.x;
  7543. if (v.y < this.minimumWorld.y)
  7544. this.minimumWorld.y = v.y;
  7545. if (v.z < this.minimumWorld.z)
  7546. this.minimumWorld.z = v.z;
  7547. if (v.x > this.maximumWorld.x)
  7548. this.maximumWorld.x = v.x;
  7549. if (v.y > this.maximumWorld.y)
  7550. this.maximumWorld.y = v.y;
  7551. if (v.z > this.maximumWorld.z)
  7552. this.maximumWorld.z = v.z;
  7553. }
  7554. // OBB
  7555. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7556. this.center.scaleInPlace(0.5);
  7557. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7558. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7559. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7560. this._worldMatrix = world;
  7561. };
  7562. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7563. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7564. };
  7565. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7566. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7567. };
  7568. BoundingBox.prototype.intersectsPoint = function (point) {
  7569. var delta = -BABYLON.Engine.Epsilon;
  7570. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7571. return false;
  7572. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7573. return false;
  7574. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7575. return false;
  7576. return true;
  7577. };
  7578. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7579. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7580. };
  7581. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7582. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7583. return false;
  7584. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7585. return false;
  7586. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7587. return false;
  7588. return true;
  7589. };
  7590. // Statics
  7591. BoundingBox.Intersects = function (box0, box1) {
  7592. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7593. return false;
  7594. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7595. return false;
  7596. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7597. return false;
  7598. return true;
  7599. };
  7600. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7601. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7602. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7603. return (num <= (sphereRadius * sphereRadius));
  7604. };
  7605. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7606. for (var p = 0; p < 6; p++) {
  7607. for (var i = 0; i < 8; i++) {
  7608. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7609. return false;
  7610. }
  7611. }
  7612. }
  7613. return true;
  7614. };
  7615. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7616. for (var p = 0; p < 6; p++) {
  7617. var inCount = 8;
  7618. for (var i = 0; i < 8; i++) {
  7619. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7620. --inCount;
  7621. }
  7622. else {
  7623. break;
  7624. }
  7625. }
  7626. if (inCount === 0)
  7627. return false;
  7628. }
  7629. return true;
  7630. };
  7631. return BoundingBox;
  7632. })();
  7633. BABYLON.BoundingBox = BoundingBox;
  7634. })(BABYLON || (BABYLON = {}));
  7635. var BABYLON;
  7636. (function (BABYLON) {
  7637. var computeBoxExtents = function (axis, box) {
  7638. var p = BABYLON.Vector3.Dot(box.center, axis);
  7639. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7640. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7641. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7642. var r = r0 + r1 + r2;
  7643. return {
  7644. min: p - r,
  7645. max: p + r
  7646. };
  7647. };
  7648. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7649. var axisOverlap = function (axis, box0, box1) {
  7650. var result0 = computeBoxExtents(axis, box0);
  7651. var result1 = computeBoxExtents(axis, box1);
  7652. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7653. };
  7654. var BoundingInfo = (function () {
  7655. function BoundingInfo(minimum, maximum) {
  7656. this.minimum = minimum;
  7657. this.maximum = maximum;
  7658. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7659. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7660. }
  7661. // Methods
  7662. BoundingInfo.prototype._update = function (world) {
  7663. this.boundingBox._update(world);
  7664. this.boundingSphere._update(world);
  7665. };
  7666. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7667. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7668. return false;
  7669. return this.boundingBox.isInFrustum(frustumPlanes);
  7670. };
  7671. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7672. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7673. };
  7674. BoundingInfo.prototype._checkCollision = function (collider) {
  7675. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7676. };
  7677. BoundingInfo.prototype.intersectsPoint = function (point) {
  7678. if (!this.boundingSphere.centerWorld) {
  7679. return false;
  7680. }
  7681. if (!this.boundingSphere.intersectsPoint(point)) {
  7682. return false;
  7683. }
  7684. if (!this.boundingBox.intersectsPoint(point)) {
  7685. return false;
  7686. }
  7687. return true;
  7688. };
  7689. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7690. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7691. return false;
  7692. }
  7693. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7694. return false;
  7695. }
  7696. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7697. return false;
  7698. }
  7699. if (!precise) {
  7700. return true;
  7701. }
  7702. var box0 = this.boundingBox;
  7703. var box1 = boundingInfo.boundingBox;
  7704. if (!axisOverlap(box0.directions[0], box0, box1))
  7705. return false;
  7706. if (!axisOverlap(box0.directions[1], box0, box1))
  7707. return false;
  7708. if (!axisOverlap(box0.directions[2], box0, box1))
  7709. return false;
  7710. if (!axisOverlap(box1.directions[0], box0, box1))
  7711. return false;
  7712. if (!axisOverlap(box1.directions[1], box0, box1))
  7713. return false;
  7714. if (!axisOverlap(box1.directions[2], box0, box1))
  7715. return false;
  7716. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7717. return false;
  7718. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7719. return false;
  7720. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7721. return false;
  7722. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7723. return false;
  7724. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7725. return false;
  7726. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7727. return false;
  7728. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7729. return false;
  7730. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7731. return false;
  7732. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7733. return false;
  7734. return true;
  7735. };
  7736. return BoundingInfo;
  7737. })();
  7738. BABYLON.BoundingInfo = BoundingInfo;
  7739. })(BABYLON || (BABYLON = {}));
  7740. var BABYLON;
  7741. (function (BABYLON) {
  7742. var AbstractMesh = (function (_super) {
  7743. __extends(AbstractMesh, _super);
  7744. function AbstractMesh(name, scene) {
  7745. var _this = this;
  7746. _super.call(this, name, scene);
  7747. // Properties
  7748. this.definedFacingForward = true; // orientation for POV movement & rotation
  7749. this.position = new BABYLON.Vector3(0, 0, 0);
  7750. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7751. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7752. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7753. this.visibility = 1.0;
  7754. this.alphaIndex = Number.MAX_VALUE;
  7755. this.infiniteDistance = false;
  7756. this.isVisible = true;
  7757. this.isPickable = true;
  7758. this.showBoundingBox = false;
  7759. this.showSubMeshesBoundingBox = false;
  7760. this.onDispose = null;
  7761. this.isBlocker = false;
  7762. this.renderingGroupId = 0;
  7763. this.receiveShadows = false;
  7764. this.renderOutline = false;
  7765. this.outlineColor = BABYLON.Color3.Red();
  7766. this.outlineWidth = 0.02;
  7767. this.renderOverlay = false;
  7768. this.overlayColor = BABYLON.Color3.Red();
  7769. this.overlayAlpha = 0.5;
  7770. this.hasVertexAlpha = false;
  7771. this.useVertexColors = true;
  7772. this.applyFog = true;
  7773. this.computeBonesUsingShaders = true;
  7774. this.useOctreeForRenderingSelection = true;
  7775. this.useOctreeForPicking = true;
  7776. this.useOctreeForCollisions = true;
  7777. this.layerMask = 0x0FFFFFFF;
  7778. this.alwaysSelectAsActiveMesh = false;
  7779. // Physics
  7780. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7781. // Collisions
  7782. this._checkCollisions = false;
  7783. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7784. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7785. this._collider = new BABYLON.Collider();
  7786. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7787. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7788. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7789. // Edges
  7790. this.edgesWidth = 1;
  7791. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7792. // Cache
  7793. this._localScaling = BABYLON.Matrix.Zero();
  7794. this._localRotation = BABYLON.Matrix.Zero();
  7795. this._localTranslation = BABYLON.Matrix.Zero();
  7796. this._localBillboard = BABYLON.Matrix.Zero();
  7797. this._localPivotScaling = BABYLON.Matrix.Zero();
  7798. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7799. this._localWorld = BABYLON.Matrix.Zero();
  7800. this._worldMatrix = BABYLON.Matrix.Zero();
  7801. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7802. this._absolutePosition = BABYLON.Vector3.Zero();
  7803. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7804. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7805. this._isDirty = false;
  7806. this._pivotMatrix = BABYLON.Matrix.Identity();
  7807. this._isDisposed = false;
  7808. this._renderId = 0;
  7809. this._intersectionsInProgress = new Array();
  7810. this._onAfterWorldMatrixUpdate = new Array();
  7811. this._isWorldMatrixFrozen = false;
  7812. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7813. if (collidedMesh === void 0) { collidedMesh = null; }
  7814. //TODO move this to the collision coordinator!
  7815. if (_this.getScene().workerCollisions)
  7816. newPosition.multiplyInPlace(_this._collider.radius);
  7817. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7818. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7819. _this.position.addInPlace(_this._diffPositionForCollisions);
  7820. }
  7821. if (_this.onCollide && collidedMesh) {
  7822. _this.onCollide(collidedMesh);
  7823. }
  7824. };
  7825. scene.addMesh(this);
  7826. }
  7827. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7828. get: function () {
  7829. return AbstractMesh._BILLBOARDMODE_NONE;
  7830. },
  7831. enumerable: true,
  7832. configurable: true
  7833. });
  7834. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7835. get: function () {
  7836. return AbstractMesh._BILLBOARDMODE_X;
  7837. },
  7838. enumerable: true,
  7839. configurable: true
  7840. });
  7841. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7842. get: function () {
  7843. return AbstractMesh._BILLBOARDMODE_Y;
  7844. },
  7845. enumerable: true,
  7846. configurable: true
  7847. });
  7848. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7849. get: function () {
  7850. return AbstractMesh._BILLBOARDMODE_Z;
  7851. },
  7852. enumerable: true,
  7853. configurable: true
  7854. });
  7855. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7856. get: function () {
  7857. return AbstractMesh._BILLBOARDMODE_ALL;
  7858. },
  7859. enumerable: true,
  7860. configurable: true
  7861. });
  7862. // Methods
  7863. AbstractMesh.prototype.disableEdgesRendering = function () {
  7864. if (this._edgesRenderer !== undefined) {
  7865. this._edgesRenderer.dispose();
  7866. this._edgesRenderer = undefined;
  7867. }
  7868. };
  7869. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7870. if (epsilon === void 0) { epsilon = 0.95; }
  7871. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7872. this.disableEdgesRendering();
  7873. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7874. };
  7875. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7876. get: function () {
  7877. return false;
  7878. },
  7879. enumerable: true,
  7880. configurable: true
  7881. });
  7882. AbstractMesh.prototype.getLOD = function (camera) {
  7883. return this;
  7884. };
  7885. AbstractMesh.prototype.getTotalVertices = function () {
  7886. return 0;
  7887. };
  7888. AbstractMesh.prototype.getIndices = function () {
  7889. return null;
  7890. };
  7891. AbstractMesh.prototype.getVerticesData = function (kind) {
  7892. return null;
  7893. };
  7894. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7895. return false;
  7896. };
  7897. AbstractMesh.prototype.getBoundingInfo = function () {
  7898. if (this._masterMesh) {
  7899. return this._masterMesh.getBoundingInfo();
  7900. }
  7901. if (!this._boundingInfo) {
  7902. this._updateBoundingInfo();
  7903. }
  7904. return this._boundingInfo;
  7905. };
  7906. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7907. get: function () {
  7908. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. AbstractMesh.prototype._preActivate = function () {
  7914. };
  7915. AbstractMesh.prototype._activate = function (renderId) {
  7916. this._renderId = renderId;
  7917. };
  7918. AbstractMesh.prototype.getWorldMatrix = function () {
  7919. if (this._masterMesh) {
  7920. return this._masterMesh.getWorldMatrix();
  7921. }
  7922. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7923. this.computeWorldMatrix();
  7924. }
  7925. return this._worldMatrix;
  7926. };
  7927. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7928. get: function () {
  7929. return this._worldMatrix;
  7930. },
  7931. enumerable: true,
  7932. configurable: true
  7933. });
  7934. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7935. get: function () {
  7936. return this._absolutePosition;
  7937. },
  7938. enumerable: true,
  7939. configurable: true
  7940. });
  7941. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7942. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7943. this.computeWorldMatrix(true);
  7944. this._isWorldMatrixFrozen = true;
  7945. };
  7946. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7947. this._isWorldMatrixFrozen = false;
  7948. this.computeWorldMatrix(true);
  7949. };
  7950. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7951. get: function () {
  7952. return this._isWorldMatrixFrozen;
  7953. },
  7954. enumerable: true,
  7955. configurable: true
  7956. });
  7957. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7958. axis.normalize();
  7959. if (!this.rotationQuaternion) {
  7960. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7961. this.rotation = BABYLON.Vector3.Zero();
  7962. }
  7963. if (!space || space === BABYLON.Space.LOCAL) {
  7964. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7965. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7966. }
  7967. else {
  7968. if (this.parent) {
  7969. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7970. invertParentWorldMatrix.invert();
  7971. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7972. }
  7973. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7974. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7975. }
  7976. };
  7977. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7978. var displacementVector = axis.scale(distance);
  7979. if (!space || space === BABYLON.Space.LOCAL) {
  7980. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7981. this.setPositionWithLocalVector(tempV3);
  7982. }
  7983. else {
  7984. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7985. }
  7986. };
  7987. AbstractMesh.prototype.getAbsolutePosition = function () {
  7988. this.computeWorldMatrix();
  7989. return this._absolutePosition;
  7990. };
  7991. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7992. if (!absolutePosition) {
  7993. return;
  7994. }
  7995. var absolutePositionX;
  7996. var absolutePositionY;
  7997. var absolutePositionZ;
  7998. if (absolutePosition.x === undefined) {
  7999. if (arguments.length < 3) {
  8000. return;
  8001. }
  8002. absolutePositionX = arguments[0];
  8003. absolutePositionY = arguments[1];
  8004. absolutePositionZ = arguments[2];
  8005. }
  8006. else {
  8007. absolutePositionX = absolutePosition.x;
  8008. absolutePositionY = absolutePosition.y;
  8009. absolutePositionZ = absolutePosition.z;
  8010. }
  8011. if (this.parent) {
  8012. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8013. invertParentWorldMatrix.invert();
  8014. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8015. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8016. }
  8017. else {
  8018. this.position.x = absolutePositionX;
  8019. this.position.y = absolutePositionY;
  8020. this.position.z = absolutePositionZ;
  8021. }
  8022. };
  8023. // ================================== Point of View Movement =================================
  8024. /**
  8025. * Perform relative position change from the point of view of behind the front of the mesh.
  8026. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8027. * Supports definition of mesh facing forward or backward.
  8028. * @param {number} amountRight
  8029. * @param {number} amountUp
  8030. * @param {number} amountForward
  8031. */
  8032. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8033. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8034. };
  8035. /**
  8036. * Calculate relative position change from the point of view of behind the front of the mesh.
  8037. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8038. * Supports definition of mesh facing forward or backward.
  8039. * @param {number} amountRight
  8040. * @param {number} amountUp
  8041. * @param {number} amountForward
  8042. */
  8043. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8044. var rotMatrix = new BABYLON.Matrix();
  8045. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8046. rotQuaternion.toRotationMatrix(rotMatrix);
  8047. var translationDelta = BABYLON.Vector3.Zero();
  8048. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8049. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8050. return translationDelta;
  8051. };
  8052. // ================================== Point of View Rotation =================================
  8053. /**
  8054. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8055. * Supports definition of mesh facing forward or backward.
  8056. * @param {number} flipBack
  8057. * @param {number} twirlClockwise
  8058. * @param {number} tiltRight
  8059. */
  8060. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8061. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8062. };
  8063. /**
  8064. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8065. * Supports definition of mesh facing forward or backward.
  8066. * @param {number} flipBack
  8067. * @param {number} twirlClockwise
  8068. * @param {number} tiltRight
  8069. */
  8070. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8071. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8072. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8073. };
  8074. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8075. this._pivotMatrix = matrix;
  8076. this._cache.pivotMatrixUpdated = true;
  8077. };
  8078. AbstractMesh.prototype.getPivotMatrix = function () {
  8079. return this._pivotMatrix;
  8080. };
  8081. AbstractMesh.prototype._isSynchronized = function () {
  8082. if (this._isDirty) {
  8083. return false;
  8084. }
  8085. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8086. return false;
  8087. if (this._cache.pivotMatrixUpdated) {
  8088. return false;
  8089. }
  8090. if (this.infiniteDistance) {
  8091. return false;
  8092. }
  8093. if (!this._cache.position.equals(this.position))
  8094. return false;
  8095. if (this.rotationQuaternion) {
  8096. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8097. return false;
  8098. }
  8099. else {
  8100. if (!this._cache.rotation.equals(this.rotation))
  8101. return false;
  8102. }
  8103. if (!this._cache.scaling.equals(this.scaling))
  8104. return false;
  8105. return true;
  8106. };
  8107. AbstractMesh.prototype._initCache = function () {
  8108. _super.prototype._initCache.call(this);
  8109. this._cache.localMatrixUpdated = false;
  8110. this._cache.position = BABYLON.Vector3.Zero();
  8111. this._cache.scaling = BABYLON.Vector3.Zero();
  8112. this._cache.rotation = BABYLON.Vector3.Zero();
  8113. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8114. };
  8115. AbstractMesh.prototype.markAsDirty = function (property) {
  8116. if (property === "rotation") {
  8117. this.rotationQuaternion = null;
  8118. }
  8119. this._currentRenderId = Number.MAX_VALUE;
  8120. this._isDirty = true;
  8121. };
  8122. AbstractMesh.prototype._updateBoundingInfo = function () {
  8123. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8124. this._boundingInfo._update(this.worldMatrixFromCache);
  8125. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8126. };
  8127. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8128. if (!this.subMeshes) {
  8129. return;
  8130. }
  8131. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8132. var subMesh = this.subMeshes[subIndex];
  8133. subMesh.updateBoundingInfo(matrix);
  8134. }
  8135. };
  8136. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8137. if (this._isWorldMatrixFrozen) {
  8138. return this._worldMatrix;
  8139. }
  8140. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8141. return this._worldMatrix;
  8142. }
  8143. this._cache.position.copyFrom(this.position);
  8144. this._cache.scaling.copyFrom(this.scaling);
  8145. this._cache.pivotMatrixUpdated = false;
  8146. this._currentRenderId = this.getScene().getRenderId();
  8147. this._isDirty = false;
  8148. // Scaling
  8149. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8150. // Rotation
  8151. if (this.rotationQuaternion) {
  8152. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8153. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8154. }
  8155. else {
  8156. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8157. this._cache.rotation.copyFrom(this.rotation);
  8158. }
  8159. // Translation
  8160. if (this.infiniteDistance && !this.parent) {
  8161. var camera = this.getScene().activeCamera;
  8162. if (camera) {
  8163. var cameraWorldMatrix = camera.getWorldMatrix();
  8164. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8165. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8166. }
  8167. }
  8168. else {
  8169. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8170. }
  8171. // Composing transformations
  8172. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8173. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8174. // Billboarding
  8175. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8176. var localPosition = this.position.clone();
  8177. var zero = this.getScene().activeCamera.globalPosition.clone();
  8178. if (this.parent && this.parent.position) {
  8179. localPosition.addInPlace(this.parent.position);
  8180. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8181. }
  8182. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  8183. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8184. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8185. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8186. zero.y = localPosition.y + 0.001;
  8187. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8188. zero.z = localPosition.z + 0.001;
  8189. }
  8190. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8191. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8192. this._localBillboard.invert();
  8193. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8194. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8195. }
  8196. // Local world
  8197. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8198. // Parent
  8199. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8200. this._markSyncedWithParent();
  8201. if (this._meshToBoneReferal) {
  8202. if (!this._localMeshReferalTransform) {
  8203. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8204. }
  8205. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8206. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8207. }
  8208. else {
  8209. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8210. }
  8211. }
  8212. else {
  8213. this._worldMatrix.copyFrom(this._localWorld);
  8214. }
  8215. // Bounding info
  8216. this._updateBoundingInfo();
  8217. // Absolute position
  8218. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8219. // Callbacks
  8220. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8221. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8222. }
  8223. return this._worldMatrix;
  8224. };
  8225. /**
  8226. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8227. * @param func: callback function to add
  8228. */
  8229. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8230. this._onAfterWorldMatrixUpdate.push(func);
  8231. };
  8232. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8233. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8234. if (index > -1) {
  8235. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8236. }
  8237. };
  8238. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8239. this.computeWorldMatrix();
  8240. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8241. };
  8242. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8243. this.computeWorldMatrix();
  8244. var invLocalWorldMatrix = this._localWorld.clone();
  8245. invLocalWorldMatrix.invert();
  8246. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8247. };
  8248. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8249. this.computeWorldMatrix(true);
  8250. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8251. };
  8252. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8253. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8254. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8255. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8256. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8257. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8258. /// <returns>Mesh oriented towards targetMesh</returns>
  8259. yawCor = yawCor || 0; // default to zero if undefined
  8260. pitchCor = pitchCor || 0;
  8261. rollCor = rollCor || 0;
  8262. var dv = targetPoint.subtract(this.position);
  8263. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8264. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8265. var pitch = Math.atan2(dv.y, len);
  8266. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8267. };
  8268. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8269. this._meshToBoneReferal = affectedMesh;
  8270. this.parent = bone;
  8271. };
  8272. AbstractMesh.prototype.detachFromBone = function () {
  8273. this._meshToBoneReferal = null;
  8274. this.parent = null;
  8275. };
  8276. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8277. return this._boundingInfo.isInFrustum(frustumPlanes);
  8278. };
  8279. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8280. if (!camera) {
  8281. camera = this.getScene().activeCamera;
  8282. }
  8283. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8284. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8285. return false;
  8286. }
  8287. return true;
  8288. };
  8289. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8290. if (!this._boundingInfo || !mesh._boundingInfo) {
  8291. return false;
  8292. }
  8293. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8294. };
  8295. AbstractMesh.prototype.intersectsPoint = function (point) {
  8296. if (!this._boundingInfo) {
  8297. return false;
  8298. }
  8299. return this._boundingInfo.intersectsPoint(point);
  8300. };
  8301. // Physics
  8302. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8303. var physicsEngine = this.getScene().getPhysicsEngine();
  8304. if (!physicsEngine) {
  8305. return;
  8306. }
  8307. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8308. if (impostor.impostor) {
  8309. // Old API
  8310. options = impostor;
  8311. impostor = impostor.impostor;
  8312. }
  8313. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8314. physicsEngine._unregisterMesh(this);
  8315. return;
  8316. }
  8317. if (!options) {
  8318. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8319. }
  8320. else {
  8321. if (!options.mass && options.mass !== 0)
  8322. options.mass = 0;
  8323. if (!options.friction && options.friction !== 0)
  8324. options.friction = 0.2;
  8325. if (!options.restitution && options.restitution !== 0)
  8326. options.restitution = 0.2;
  8327. }
  8328. this._physicImpostor = impostor;
  8329. this._physicsMass = options.mass;
  8330. this._physicsFriction = options.friction;
  8331. this._physicRestitution = options.restitution;
  8332. return physicsEngine._registerMesh(this, impostor, options);
  8333. };
  8334. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8335. if (!this._physicImpostor) {
  8336. return BABYLON.PhysicsEngine.NoImpostor;
  8337. }
  8338. return this._physicImpostor;
  8339. };
  8340. AbstractMesh.prototype.getPhysicsMass = function () {
  8341. if (!this._physicsMass) {
  8342. return 0;
  8343. }
  8344. return this._physicsMass;
  8345. };
  8346. AbstractMesh.prototype.getPhysicsFriction = function () {
  8347. if (!this._physicsFriction) {
  8348. return 0;
  8349. }
  8350. return this._physicsFriction;
  8351. };
  8352. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8353. if (!this._physicRestitution) {
  8354. return 0;
  8355. }
  8356. return this._physicRestitution;
  8357. };
  8358. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8359. if (!camera) {
  8360. camera = this.getScene().activeCamera;
  8361. }
  8362. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8363. };
  8364. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8365. if (!camera) {
  8366. camera = this.getScene().activeCamera;
  8367. }
  8368. return this.absolutePosition.subtract(camera.position).length();
  8369. };
  8370. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8371. if (!this._physicImpostor) {
  8372. return;
  8373. }
  8374. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8375. };
  8376. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8377. if (!this._physicImpostor) {
  8378. return;
  8379. }
  8380. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8381. };
  8382. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8383. if (!this._physicImpostor) {
  8384. return;
  8385. }
  8386. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8387. };
  8388. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8389. // Collisions
  8390. get: function () {
  8391. return this._checkCollisions;
  8392. },
  8393. set: function (collisionEnabled) {
  8394. this._checkCollisions = collisionEnabled;
  8395. if (this.getScene().workerCollisions) {
  8396. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8397. }
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8403. var globalPosition = this.getAbsolutePosition();
  8404. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8405. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8406. this._collider.radius = this.ellipsoid;
  8407. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8408. };
  8409. // Submeshes octree
  8410. /**
  8411. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8412. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8413. */
  8414. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8415. if (maxCapacity === void 0) { maxCapacity = 64; }
  8416. if (maxDepth === void 0) { maxDepth = 2; }
  8417. if (!this._submeshesOctree) {
  8418. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8419. }
  8420. this.computeWorldMatrix(true);
  8421. // Update octree
  8422. var bbox = this.getBoundingInfo().boundingBox;
  8423. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8424. return this._submeshesOctree;
  8425. };
  8426. // Collisions
  8427. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8428. this._generatePointsArray();
  8429. // Transformation
  8430. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8431. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8432. subMesh._lastColliderWorldVertices = [];
  8433. subMesh._trianglePlanes = [];
  8434. var start = subMesh.verticesStart;
  8435. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8436. for (var i = start; i < end; i++) {
  8437. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8438. }
  8439. }
  8440. // Collide
  8441. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8442. if (collider.collisionFound) {
  8443. collider.collidedMesh = this;
  8444. }
  8445. };
  8446. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8447. var subMeshes;
  8448. var len;
  8449. // Octrees
  8450. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8451. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8452. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8453. len = intersections.length;
  8454. subMeshes = intersections.data;
  8455. }
  8456. else {
  8457. subMeshes = this.subMeshes;
  8458. len = subMeshes.length;
  8459. }
  8460. for (var index = 0; index < len; index++) {
  8461. var subMesh = subMeshes[index];
  8462. // Bounding test
  8463. if (len > 1 && !subMesh._checkCollision(collider))
  8464. continue;
  8465. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8466. }
  8467. };
  8468. AbstractMesh.prototype._checkCollision = function (collider) {
  8469. // Bounding box test
  8470. if (!this._boundingInfo._checkCollision(collider))
  8471. return;
  8472. // Transformation matrix
  8473. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8474. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8475. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8476. };
  8477. // Picking
  8478. AbstractMesh.prototype._generatePointsArray = function () {
  8479. return false;
  8480. };
  8481. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8482. var pickingInfo = new BABYLON.PickingInfo();
  8483. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8484. return pickingInfo;
  8485. }
  8486. if (!this._generatePointsArray()) {
  8487. return pickingInfo;
  8488. }
  8489. var intersectInfo = null;
  8490. // Octrees
  8491. var subMeshes;
  8492. var len;
  8493. if (this._submeshesOctree && this.useOctreeForPicking) {
  8494. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8495. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8496. len = intersections.length;
  8497. subMeshes = intersections.data;
  8498. }
  8499. else {
  8500. subMeshes = this.subMeshes;
  8501. len = subMeshes.length;
  8502. }
  8503. for (var index = 0; index < len; index++) {
  8504. var subMesh = subMeshes[index];
  8505. // Bounding test
  8506. if (len > 1 && !subMesh.canIntersects(ray))
  8507. continue;
  8508. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8509. if (currentIntersectInfo) {
  8510. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8511. intersectInfo = currentIntersectInfo;
  8512. intersectInfo.subMeshId = index;
  8513. if (fastCheck) {
  8514. break;
  8515. }
  8516. }
  8517. }
  8518. }
  8519. if (intersectInfo) {
  8520. // Get picked point
  8521. var world = this.getWorldMatrix();
  8522. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8523. var direction = ray.direction.clone();
  8524. direction = direction.scale(intersectInfo.distance);
  8525. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8526. var pickedPoint = worldOrigin.add(worldDirection);
  8527. // Return result
  8528. pickingInfo.hit = true;
  8529. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8530. pickingInfo.pickedPoint = pickedPoint;
  8531. pickingInfo.pickedMesh = this;
  8532. pickingInfo.bu = intersectInfo.bu;
  8533. pickingInfo.bv = intersectInfo.bv;
  8534. pickingInfo.faceId = intersectInfo.faceId;
  8535. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8536. return pickingInfo;
  8537. }
  8538. return pickingInfo;
  8539. };
  8540. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8541. return null;
  8542. };
  8543. AbstractMesh.prototype.releaseSubMeshes = function () {
  8544. if (this.subMeshes) {
  8545. while (this.subMeshes.length) {
  8546. this.subMeshes[0].dispose();
  8547. }
  8548. }
  8549. else {
  8550. this.subMeshes = new Array();
  8551. }
  8552. };
  8553. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8554. var index;
  8555. // Physics
  8556. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8557. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8558. }
  8559. // Intersections in progress
  8560. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8561. var other = this._intersectionsInProgress[index];
  8562. var pos = other._intersectionsInProgress.indexOf(this);
  8563. other._intersectionsInProgress.splice(pos, 1);
  8564. }
  8565. this._intersectionsInProgress = [];
  8566. // Edges
  8567. if (this._edgesRenderer) {
  8568. this._edgesRenderer.dispose();
  8569. this._edgesRenderer = null;
  8570. }
  8571. // SubMeshes
  8572. this.releaseSubMeshes();
  8573. // Remove from scene
  8574. this.getScene().removeMesh(this);
  8575. if (!doNotRecurse) {
  8576. // Particles
  8577. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8578. if (this.getScene().particleSystems[index].emitter === this) {
  8579. this.getScene().particleSystems[index].dispose();
  8580. index--;
  8581. }
  8582. }
  8583. // Children
  8584. var objects = this.getScene().meshes.slice(0);
  8585. for (index = 0; index < objects.length; index++) {
  8586. if (objects[index].parent === this) {
  8587. objects[index].dispose();
  8588. }
  8589. }
  8590. }
  8591. else {
  8592. for (index = 0; index < this.getScene().meshes.length; index++) {
  8593. var obj = this.getScene().meshes[index];
  8594. if (obj.parent === this) {
  8595. obj.parent = null;
  8596. obj.computeWorldMatrix(true);
  8597. }
  8598. }
  8599. }
  8600. this._onAfterWorldMatrixUpdate = [];
  8601. this._isDisposed = true;
  8602. // Callback
  8603. if (this.onDispose) {
  8604. this.onDispose();
  8605. }
  8606. };
  8607. // Statics
  8608. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8609. AbstractMesh._BILLBOARDMODE_X = 1;
  8610. AbstractMesh._BILLBOARDMODE_Y = 2;
  8611. AbstractMesh._BILLBOARDMODE_Z = 4;
  8612. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8613. return AbstractMesh;
  8614. })(BABYLON.Node);
  8615. BABYLON.AbstractMesh = AbstractMesh;
  8616. })(BABYLON || (BABYLON = {}));
  8617. var BABYLON;
  8618. (function (BABYLON) {
  8619. var Light = (function (_super) {
  8620. __extends(Light, _super);
  8621. function Light(name, scene) {
  8622. _super.call(this, name, scene);
  8623. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8624. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8625. this.intensity = 1.0;
  8626. this.range = Number.MAX_VALUE;
  8627. this.includeOnlyWithLayerMask = 0;
  8628. this.includedOnlyMeshes = new Array();
  8629. this.excludedMeshes = new Array();
  8630. this.excludeWithLayerMask = 0;
  8631. this._excludedMeshesIds = new Array();
  8632. this._includedOnlyMeshesIds = new Array();
  8633. scene.addLight(this);
  8634. }
  8635. Light.prototype.getShadowGenerator = function () {
  8636. return this._shadowGenerator;
  8637. };
  8638. Light.prototype.getAbsolutePosition = function () {
  8639. return BABYLON.Vector3.Zero();
  8640. };
  8641. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8642. };
  8643. Light.prototype._getWorldMatrix = function () {
  8644. return BABYLON.Matrix.Identity();
  8645. };
  8646. Light.prototype.canAffectMesh = function (mesh) {
  8647. if (!mesh) {
  8648. return true;
  8649. }
  8650. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8651. return false;
  8652. }
  8653. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8654. return false;
  8655. }
  8656. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8657. return false;
  8658. }
  8659. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8660. return false;
  8661. }
  8662. return true;
  8663. };
  8664. Light.prototype.getWorldMatrix = function () {
  8665. this._currentRenderId = this.getScene().getRenderId();
  8666. var worldMatrix = this._getWorldMatrix();
  8667. if (this.parent && this.parent.getWorldMatrix) {
  8668. if (!this._parentedWorldMatrix) {
  8669. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8670. }
  8671. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8672. this._markSyncedWithParent();
  8673. return this._parentedWorldMatrix;
  8674. }
  8675. return worldMatrix;
  8676. };
  8677. Light.prototype.dispose = function () {
  8678. if (this._shadowGenerator) {
  8679. this._shadowGenerator.dispose();
  8680. this._shadowGenerator = null;
  8681. }
  8682. // Remove from scene
  8683. this.getScene().removeLight(this);
  8684. };
  8685. return Light;
  8686. })(BABYLON.Node);
  8687. BABYLON.Light = Light;
  8688. })(BABYLON || (BABYLON = {}));
  8689. var BABYLON;
  8690. (function (BABYLON) {
  8691. var PointLight = (function (_super) {
  8692. __extends(PointLight, _super);
  8693. function PointLight(name, position, scene) {
  8694. _super.call(this, name, scene);
  8695. this.position = position;
  8696. }
  8697. PointLight.prototype.getAbsolutePosition = function () {
  8698. return this._transformedPosition ? this._transformedPosition : this.position;
  8699. };
  8700. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8701. if (this.parent && this.parent.getWorldMatrix) {
  8702. if (!this._transformedPosition) {
  8703. this._transformedPosition = BABYLON.Vector3.Zero();
  8704. }
  8705. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8706. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8707. return;
  8708. }
  8709. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8710. };
  8711. PointLight.prototype.getShadowGenerator = function () {
  8712. return null;
  8713. };
  8714. PointLight.prototype._getWorldMatrix = function () {
  8715. if (!this._worldMatrix) {
  8716. this._worldMatrix = BABYLON.Matrix.Identity();
  8717. }
  8718. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8719. return this._worldMatrix;
  8720. };
  8721. return PointLight;
  8722. })(BABYLON.Light);
  8723. BABYLON.PointLight = PointLight;
  8724. })(BABYLON || (BABYLON = {}));
  8725. var BABYLON;
  8726. (function (BABYLON) {
  8727. var SpotLight = (function (_super) {
  8728. __extends(SpotLight, _super);
  8729. function SpotLight(name, position, direction, angle, exponent, scene) {
  8730. _super.call(this, name, scene);
  8731. this.position = position;
  8732. this.direction = direction;
  8733. this.angle = angle;
  8734. this.exponent = exponent;
  8735. }
  8736. SpotLight.prototype.getAbsolutePosition = function () {
  8737. return this.transformedPosition ? this.transformedPosition : this.position;
  8738. };
  8739. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8740. var activeCamera = this.getScene().activeCamera;
  8741. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8742. };
  8743. SpotLight.prototype.supportsVSM = function () {
  8744. return true;
  8745. };
  8746. SpotLight.prototype.needRefreshPerFrame = function () {
  8747. return false;
  8748. };
  8749. SpotLight.prototype.setDirectionToTarget = function (target) {
  8750. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8751. return this.direction;
  8752. };
  8753. SpotLight.prototype.computeTransformedPosition = function () {
  8754. if (this.parent && this.parent.getWorldMatrix) {
  8755. if (!this.transformedPosition) {
  8756. this.transformedPosition = BABYLON.Vector3.Zero();
  8757. }
  8758. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8759. return true;
  8760. }
  8761. return false;
  8762. };
  8763. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8764. var normalizeDirection;
  8765. if (this.parent && this.parent.getWorldMatrix) {
  8766. if (!this._transformedDirection) {
  8767. this._transformedDirection = BABYLON.Vector3.Zero();
  8768. }
  8769. this.computeTransformedPosition();
  8770. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8771. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8772. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8773. }
  8774. else {
  8775. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8776. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8777. }
  8778. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8779. };
  8780. SpotLight.prototype._getWorldMatrix = function () {
  8781. if (!this._worldMatrix) {
  8782. this._worldMatrix = BABYLON.Matrix.Identity();
  8783. }
  8784. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8785. return this._worldMatrix;
  8786. };
  8787. return SpotLight;
  8788. })(BABYLON.Light);
  8789. BABYLON.SpotLight = SpotLight;
  8790. })(BABYLON || (BABYLON = {}));
  8791. var BABYLON;
  8792. (function (BABYLON) {
  8793. var HemisphericLight = (function (_super) {
  8794. __extends(HemisphericLight, _super);
  8795. function HemisphericLight(name, direction, scene) {
  8796. _super.call(this, name, scene);
  8797. this.direction = direction;
  8798. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8799. }
  8800. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8801. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8802. return this.direction;
  8803. };
  8804. HemisphericLight.prototype.getShadowGenerator = function () {
  8805. return null;
  8806. };
  8807. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8808. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8809. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8810. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8811. };
  8812. HemisphericLight.prototype._getWorldMatrix = function () {
  8813. if (!this._worldMatrix) {
  8814. this._worldMatrix = BABYLON.Matrix.Identity();
  8815. }
  8816. return this._worldMatrix;
  8817. };
  8818. return HemisphericLight;
  8819. })(BABYLON.Light);
  8820. BABYLON.HemisphericLight = HemisphericLight;
  8821. })(BABYLON || (BABYLON = {}));
  8822. var BABYLON;
  8823. (function (BABYLON) {
  8824. var DirectionalLight = (function (_super) {
  8825. __extends(DirectionalLight, _super);
  8826. function DirectionalLight(name, direction, scene) {
  8827. _super.call(this, name, scene);
  8828. this.direction = direction;
  8829. this.shadowOrthoScale = 0.5;
  8830. this.position = direction.scale(-1);
  8831. }
  8832. DirectionalLight.prototype.getAbsolutePosition = function () {
  8833. return this.transformedPosition ? this.transformedPosition : this.position;
  8834. };
  8835. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8836. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8837. return this.direction;
  8838. };
  8839. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8840. var orthoLeft = Number.MAX_VALUE;
  8841. var orthoRight = Number.MIN_VALUE;
  8842. var orthoTop = Number.MIN_VALUE;
  8843. var orthoBottom = Number.MAX_VALUE;
  8844. var tempVector3 = BABYLON.Vector3.Zero();
  8845. var activeCamera = this.getScene().activeCamera;
  8846. // Check extends
  8847. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8848. var mesh = renderList[meshIndex];
  8849. if (!mesh) {
  8850. continue;
  8851. }
  8852. var boundingInfo = mesh.getBoundingInfo();
  8853. if (!boundingInfo) {
  8854. continue;
  8855. }
  8856. var boundingBox = boundingInfo.boundingBox;
  8857. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8858. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8859. if (tempVector3.x < orthoLeft)
  8860. orthoLeft = tempVector3.x;
  8861. if (tempVector3.y < orthoBottom)
  8862. orthoBottom = tempVector3.y;
  8863. if (tempVector3.x > orthoRight)
  8864. orthoRight = tempVector3.x;
  8865. if (tempVector3.y > orthoTop)
  8866. orthoTop = tempVector3.y;
  8867. }
  8868. }
  8869. var xOffset = orthoRight - orthoLeft;
  8870. var yOffset = orthoTop - orthoBottom;
  8871. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8872. };
  8873. DirectionalLight.prototype.supportsVSM = function () {
  8874. return true;
  8875. };
  8876. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8877. return true;
  8878. };
  8879. DirectionalLight.prototype.computeTransformedPosition = function () {
  8880. if (this.parent && this.parent.getWorldMatrix) {
  8881. if (!this.transformedPosition) {
  8882. this.transformedPosition = BABYLON.Vector3.Zero();
  8883. }
  8884. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8885. return true;
  8886. }
  8887. return false;
  8888. };
  8889. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8890. if (this.parent && this.parent.getWorldMatrix) {
  8891. if (!this._transformedDirection) {
  8892. this._transformedDirection = BABYLON.Vector3.Zero();
  8893. }
  8894. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8895. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8896. return;
  8897. }
  8898. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8899. };
  8900. DirectionalLight.prototype._getWorldMatrix = function () {
  8901. if (!this._worldMatrix) {
  8902. this._worldMatrix = BABYLON.Matrix.Identity();
  8903. }
  8904. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8905. return this._worldMatrix;
  8906. };
  8907. return DirectionalLight;
  8908. })(BABYLON.Light);
  8909. BABYLON.DirectionalLight = DirectionalLight;
  8910. })(BABYLON || (BABYLON = {}));
  8911. var BABYLON;
  8912. (function (BABYLON) {
  8913. var ShadowGenerator = (function () {
  8914. function ShadowGenerator(mapSize, light) {
  8915. var _this = this;
  8916. // Members
  8917. this._filter = ShadowGenerator.FILTER_NONE;
  8918. this.blurScale = 2;
  8919. this._blurBoxOffset = 0;
  8920. this._bias = 0.00005;
  8921. this._lightDirection = BABYLON.Vector3.Zero();
  8922. this._darkness = 0;
  8923. this._transparencyShadow = false;
  8924. this._viewMatrix = BABYLON.Matrix.Zero();
  8925. this._projectionMatrix = BABYLON.Matrix.Zero();
  8926. this._transformMatrix = BABYLON.Matrix.Zero();
  8927. this._worldViewProjection = BABYLON.Matrix.Zero();
  8928. this._light = light;
  8929. this._scene = light.getScene();
  8930. this._mapSize = mapSize;
  8931. light._shadowGenerator = this;
  8932. // Render target
  8933. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8934. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8935. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8936. this._shadowMap.anisotropicFilteringLevel = 1;
  8937. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8938. this._shadowMap.renderParticles = false;
  8939. this._shadowMap.onAfterUnbind = function () {
  8940. if (!_this.useBlurVarianceShadowMap) {
  8941. return;
  8942. }
  8943. if (!_this._shadowMap2) {
  8944. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8945. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8946. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8947. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8948. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8949. _this._downSamplePostprocess.onApply = function (effect) {
  8950. effect.setTexture("textureSampler", _this._shadowMap);
  8951. };
  8952. _this.blurBoxOffset = 1;
  8953. }
  8954. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8955. };
  8956. // Custom render function
  8957. var renderSubMesh = function (subMesh) {
  8958. var mesh = subMesh.getRenderingMesh();
  8959. var scene = _this._scene;
  8960. var engine = scene.getEngine();
  8961. // Culling
  8962. engine.setState(subMesh.getMaterial().backFaceCulling);
  8963. // Managing instances
  8964. var batch = mesh._getInstancesRenderList(subMesh._id);
  8965. if (batch.mustReturn) {
  8966. return;
  8967. }
  8968. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8969. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8970. engine.enableEffect(_this._effect);
  8971. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8972. var material = subMesh.getMaterial();
  8973. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8974. // Alpha test
  8975. if (material && material.needAlphaTesting()) {
  8976. var alphaTexture = material.getAlphaTestTexture();
  8977. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8978. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8979. }
  8980. // Bones
  8981. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8982. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8983. }
  8984. // Draw
  8985. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8986. }
  8987. else {
  8988. // Need to reset refresh rate of the shadowMap
  8989. _this._shadowMap.resetRefreshCounter();
  8990. }
  8991. };
  8992. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8993. var index;
  8994. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8995. renderSubMesh(opaqueSubMeshes.data[index]);
  8996. }
  8997. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8998. renderSubMesh(alphaTestSubMeshes.data[index]);
  8999. }
  9000. if (_this._transparencyShadow) {
  9001. for (index = 0; index < transparentSubMeshes.length; index++) {
  9002. renderSubMesh(transparentSubMeshes.data[index]);
  9003. }
  9004. }
  9005. };
  9006. this._shadowMap.onClear = function (engine) {
  9007. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9008. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9009. }
  9010. else {
  9011. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9012. }
  9013. };
  9014. }
  9015. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9016. // Static
  9017. get: function () {
  9018. return ShadowGenerator._FILTER_NONE;
  9019. },
  9020. enumerable: true,
  9021. configurable: true
  9022. });
  9023. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9024. get: function () {
  9025. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9026. },
  9027. enumerable: true,
  9028. configurable: true
  9029. });
  9030. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9031. get: function () {
  9032. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9033. },
  9034. enumerable: true,
  9035. configurable: true
  9036. });
  9037. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9038. get: function () {
  9039. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9040. },
  9041. enumerable: true,
  9042. configurable: true
  9043. });
  9044. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9045. get: function () {
  9046. return this._bias;
  9047. },
  9048. set: function (bias) {
  9049. this._bias = bias;
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9055. get: function () {
  9056. return this._blurBoxOffset;
  9057. },
  9058. set: function (value) {
  9059. var _this = this;
  9060. if (this._blurBoxOffset === value) {
  9061. return;
  9062. }
  9063. this._blurBoxOffset = value;
  9064. if (this._boxBlurPostprocess) {
  9065. this._boxBlurPostprocess.dispose();
  9066. }
  9067. 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);
  9068. this._boxBlurPostprocess.onApply = function (effect) {
  9069. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9070. };
  9071. },
  9072. enumerable: true,
  9073. configurable: true
  9074. });
  9075. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9076. get: function () {
  9077. return this._filter;
  9078. },
  9079. set: function (value) {
  9080. if (this._filter === value) {
  9081. return;
  9082. }
  9083. this._filter = value;
  9084. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9085. this._shadowMap.anisotropicFilteringLevel = 16;
  9086. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9087. }
  9088. else {
  9089. this._shadowMap.anisotropicFilteringLevel = 1;
  9090. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9091. }
  9092. },
  9093. enumerable: true,
  9094. configurable: true
  9095. });
  9096. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9097. get: function () {
  9098. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9099. },
  9100. set: function (value) {
  9101. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9102. },
  9103. enumerable: true,
  9104. configurable: true
  9105. });
  9106. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9107. get: function () {
  9108. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9109. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9110. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9111. },
  9112. set: function (value) {
  9113. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9114. },
  9115. enumerable: true,
  9116. configurable: true
  9117. });
  9118. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9119. get: function () {
  9120. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9121. },
  9122. set: function (value) {
  9123. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9124. },
  9125. enumerable: true,
  9126. configurable: true
  9127. });
  9128. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9129. var defines = [];
  9130. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9131. defines.push("#define VSM");
  9132. }
  9133. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9134. var mesh = subMesh.getMesh();
  9135. var material = subMesh.getMaterial();
  9136. // Alpha test
  9137. if (material && material.needAlphaTesting()) {
  9138. defines.push("#define ALPHATEST");
  9139. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9140. attribs.push(BABYLON.VertexBuffer.UVKind);
  9141. defines.push("#define UV1");
  9142. }
  9143. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9144. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9145. defines.push("#define UV2");
  9146. }
  9147. }
  9148. // Bones
  9149. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9150. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9151. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9152. defines.push("#define BONES");
  9153. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9154. }
  9155. // Instances
  9156. if (useInstances) {
  9157. defines.push("#define INSTANCES");
  9158. attribs.push("world0");
  9159. attribs.push("world1");
  9160. attribs.push("world2");
  9161. attribs.push("world3");
  9162. }
  9163. // Get correct effect
  9164. var join = defines.join("\n");
  9165. if (this._cachedDefines !== join) {
  9166. this._cachedDefines = join;
  9167. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9168. }
  9169. return this._effect.isReady();
  9170. };
  9171. ShadowGenerator.prototype.getShadowMap = function () {
  9172. return this._shadowMap;
  9173. };
  9174. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9175. if (this._shadowMap2) {
  9176. return this._shadowMap2;
  9177. }
  9178. return this._shadowMap;
  9179. };
  9180. ShadowGenerator.prototype.getLight = function () {
  9181. return this._light;
  9182. };
  9183. // Methods
  9184. ShadowGenerator.prototype.getTransformMatrix = function () {
  9185. var scene = this._scene;
  9186. if (this._currentRenderID === scene.getRenderId()) {
  9187. return this._transformMatrix;
  9188. }
  9189. this._currentRenderID = scene.getRenderId();
  9190. var lightPosition = this._light.position;
  9191. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9192. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9193. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9194. }
  9195. if (this._light.computeTransformedPosition()) {
  9196. lightPosition = this._light.transformedPosition;
  9197. }
  9198. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9199. this._cachedPosition = lightPosition.clone();
  9200. this._cachedDirection = this._lightDirection.clone();
  9201. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9202. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9203. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9204. }
  9205. return this._transformMatrix;
  9206. };
  9207. ShadowGenerator.prototype.getDarkness = function () {
  9208. return this._darkness;
  9209. };
  9210. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9211. if (darkness >= 1.0)
  9212. this._darkness = 1.0;
  9213. else if (darkness <= 0.0)
  9214. this._darkness = 0.0;
  9215. else
  9216. this._darkness = darkness;
  9217. };
  9218. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9219. this._transparencyShadow = hasShadow;
  9220. };
  9221. ShadowGenerator.prototype._packHalf = function (depth) {
  9222. var scale = depth * 255.0;
  9223. var fract = scale - Math.floor(scale);
  9224. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9225. };
  9226. ShadowGenerator.prototype.dispose = function () {
  9227. this._shadowMap.dispose();
  9228. if (this._shadowMap2) {
  9229. this._shadowMap2.dispose();
  9230. }
  9231. if (this._downSamplePostprocess) {
  9232. this._downSamplePostprocess.dispose();
  9233. }
  9234. if (this._boxBlurPostprocess) {
  9235. this._boxBlurPostprocess.dispose();
  9236. }
  9237. };
  9238. ShadowGenerator._FILTER_NONE = 0;
  9239. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9240. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9241. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9242. return ShadowGenerator;
  9243. })();
  9244. BABYLON.ShadowGenerator = ShadowGenerator;
  9245. })(BABYLON || (BABYLON = {}));
  9246. var BABYLON;
  9247. (function (BABYLON) {
  9248. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9249. if (boxMin.x > sphereCenter.x + sphereRadius)
  9250. return false;
  9251. if (sphereCenter.x - sphereRadius > boxMax.x)
  9252. return false;
  9253. if (boxMin.y > sphereCenter.y + sphereRadius)
  9254. return false;
  9255. if (sphereCenter.y - sphereRadius > boxMax.y)
  9256. return false;
  9257. if (boxMin.z > sphereCenter.z + sphereRadius)
  9258. return false;
  9259. if (sphereCenter.z - sphereRadius > boxMax.z)
  9260. return false;
  9261. return true;
  9262. };
  9263. var getLowestRoot = function (a, b, c, maxR) {
  9264. var determinant = b * b - 4.0 * a * c;
  9265. var result = { root: 0, found: false };
  9266. if (determinant < 0)
  9267. return result;
  9268. var sqrtD = Math.sqrt(determinant);
  9269. var r1 = (-b - sqrtD) / (2.0 * a);
  9270. var r2 = (-b + sqrtD) / (2.0 * a);
  9271. if (r1 > r2) {
  9272. var temp = r2;
  9273. r2 = r1;
  9274. r1 = temp;
  9275. }
  9276. if (r1 > 0 && r1 < maxR) {
  9277. result.root = r1;
  9278. result.found = true;
  9279. return result;
  9280. }
  9281. if (r2 > 0 && r2 < maxR) {
  9282. result.root = r2;
  9283. result.found = true;
  9284. return result;
  9285. }
  9286. return result;
  9287. };
  9288. var Collider = (function () {
  9289. function Collider() {
  9290. this.radius = new BABYLON.Vector3(1, 1, 1);
  9291. this.retry = 0;
  9292. this.basePointWorld = BABYLON.Vector3.Zero();
  9293. this.velocityWorld = BABYLON.Vector3.Zero();
  9294. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9295. this._collisionPoint = BABYLON.Vector3.Zero();
  9296. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9297. this._tempVector = BABYLON.Vector3.Zero();
  9298. this._tempVector2 = BABYLON.Vector3.Zero();
  9299. this._tempVector3 = BABYLON.Vector3.Zero();
  9300. this._tempVector4 = BABYLON.Vector3.Zero();
  9301. this._edge = BABYLON.Vector3.Zero();
  9302. this._baseToVertex = BABYLON.Vector3.Zero();
  9303. this._destinationPoint = BABYLON.Vector3.Zero();
  9304. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9305. this._displacementVector = BABYLON.Vector3.Zero();
  9306. }
  9307. // Methods
  9308. Collider.prototype._initialize = function (source, dir, e) {
  9309. this.velocity = dir;
  9310. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9311. this.basePoint = source;
  9312. source.multiplyToRef(this.radius, this.basePointWorld);
  9313. dir.multiplyToRef(this.radius, this.velocityWorld);
  9314. this.velocityWorldLength = this.velocityWorld.length();
  9315. this.epsilon = e;
  9316. this.collisionFound = false;
  9317. };
  9318. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9319. pa.subtractToRef(point, this._tempVector);
  9320. pb.subtractToRef(point, this._tempVector2);
  9321. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9322. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9323. if (d < 0)
  9324. return false;
  9325. pc.subtractToRef(point, this._tempVector3);
  9326. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9327. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9328. if (d < 0)
  9329. return false;
  9330. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9331. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9332. return d >= 0;
  9333. };
  9334. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9335. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9336. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9337. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9338. return false;
  9339. }
  9340. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9341. return false;
  9342. return true;
  9343. };
  9344. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9345. var t0;
  9346. var embeddedInPlane = false;
  9347. //defensive programming, actually not needed.
  9348. if (!trianglePlaneArray) {
  9349. trianglePlaneArray = [];
  9350. }
  9351. if (!trianglePlaneArray[faceIndex]) {
  9352. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9353. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9354. }
  9355. var trianglePlane = trianglePlaneArray[faceIndex];
  9356. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9357. return;
  9358. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9359. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9360. if (normalDotVelocity == 0) {
  9361. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9362. return;
  9363. embeddedInPlane = true;
  9364. t0 = 0;
  9365. }
  9366. else {
  9367. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9368. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9369. if (t0 > t1) {
  9370. var temp = t1;
  9371. t1 = t0;
  9372. t0 = temp;
  9373. }
  9374. if (t0 > 1.0 || t1 < 0.0)
  9375. return;
  9376. if (t0 < 0)
  9377. t0 = 0;
  9378. if (t0 > 1.0)
  9379. t0 = 1.0;
  9380. }
  9381. this._collisionPoint.copyFromFloats(0, 0, 0);
  9382. var found = false;
  9383. var t = 1.0;
  9384. if (!embeddedInPlane) {
  9385. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9386. this.velocity.scaleToRef(t0, this._tempVector);
  9387. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9388. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9389. found = true;
  9390. t = t0;
  9391. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9392. }
  9393. }
  9394. if (!found) {
  9395. var velocitySquaredLength = this.velocity.lengthSquared();
  9396. var a = velocitySquaredLength;
  9397. this.basePoint.subtractToRef(p1, this._tempVector);
  9398. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9399. var c = this._tempVector.lengthSquared() - 1.0;
  9400. var lowestRoot = getLowestRoot(a, b, c, t);
  9401. if (lowestRoot.found) {
  9402. t = lowestRoot.root;
  9403. found = true;
  9404. this._collisionPoint.copyFrom(p1);
  9405. }
  9406. this.basePoint.subtractToRef(p2, this._tempVector);
  9407. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9408. c = this._tempVector.lengthSquared() - 1.0;
  9409. lowestRoot = getLowestRoot(a, b, c, t);
  9410. if (lowestRoot.found) {
  9411. t = lowestRoot.root;
  9412. found = true;
  9413. this._collisionPoint.copyFrom(p2);
  9414. }
  9415. this.basePoint.subtractToRef(p3, this._tempVector);
  9416. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9417. c = this._tempVector.lengthSquared() - 1.0;
  9418. lowestRoot = getLowestRoot(a, b, c, t);
  9419. if (lowestRoot.found) {
  9420. t = lowestRoot.root;
  9421. found = true;
  9422. this._collisionPoint.copyFrom(p3);
  9423. }
  9424. p2.subtractToRef(p1, this._edge);
  9425. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9426. var edgeSquaredLength = this._edge.lengthSquared();
  9427. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9428. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9429. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9430. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9431. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9432. lowestRoot = getLowestRoot(a, b, c, t);
  9433. if (lowestRoot.found) {
  9434. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9435. if (f >= 0.0 && f <= 1.0) {
  9436. t = lowestRoot.root;
  9437. found = true;
  9438. this._edge.scaleInPlace(f);
  9439. p1.addToRef(this._edge, this._collisionPoint);
  9440. }
  9441. }
  9442. p3.subtractToRef(p2, this._edge);
  9443. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9444. edgeSquaredLength = this._edge.lengthSquared();
  9445. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9446. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9447. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9448. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9449. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9450. lowestRoot = getLowestRoot(a, b, c, t);
  9451. if (lowestRoot.found) {
  9452. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9453. if (f >= 0.0 && f <= 1.0) {
  9454. t = lowestRoot.root;
  9455. found = true;
  9456. this._edge.scaleInPlace(f);
  9457. p2.addToRef(this._edge, this._collisionPoint);
  9458. }
  9459. }
  9460. p1.subtractToRef(p3, this._edge);
  9461. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9462. edgeSquaredLength = this._edge.lengthSquared();
  9463. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9464. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9465. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9466. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9467. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9468. lowestRoot = getLowestRoot(a, b, c, t);
  9469. if (lowestRoot.found) {
  9470. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9471. if (f >= 0.0 && f <= 1.0) {
  9472. t = lowestRoot.root;
  9473. found = true;
  9474. this._edge.scaleInPlace(f);
  9475. p3.addToRef(this._edge, this._collisionPoint);
  9476. }
  9477. }
  9478. }
  9479. if (found) {
  9480. var distToCollision = t * this.velocity.length();
  9481. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9482. if (!this.intersectionPoint) {
  9483. this.intersectionPoint = this._collisionPoint.clone();
  9484. }
  9485. else {
  9486. this.intersectionPoint.copyFrom(this._collisionPoint);
  9487. }
  9488. this.nearestDistance = distToCollision;
  9489. this.collisionFound = true;
  9490. }
  9491. }
  9492. };
  9493. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9494. for (var i = indexStart; i < indexEnd; i += 3) {
  9495. var p1 = pts[indices[i] - decal];
  9496. var p2 = pts[indices[i + 1] - decal];
  9497. var p3 = pts[indices[i + 2] - decal];
  9498. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9499. }
  9500. };
  9501. Collider.prototype._getResponse = function (pos, vel) {
  9502. pos.addToRef(vel, this._destinationPoint);
  9503. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9504. this.basePoint.addToRef(vel, pos);
  9505. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9506. this._slidePlaneNormal.normalize();
  9507. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9508. pos.addInPlace(this._displacementVector);
  9509. this.intersectionPoint.addInPlace(this._displacementVector);
  9510. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9511. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9512. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9513. };
  9514. return Collider;
  9515. })();
  9516. BABYLON.Collider = Collider;
  9517. })(BABYLON || (BABYLON = {}));
  9518. var BABYLON;
  9519. (function (BABYLON) {
  9520. //WebWorker code will be inserted to this variable.
  9521. BABYLON.CollisionWorker = "";
  9522. (function (WorkerTaskType) {
  9523. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9524. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9525. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9526. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9527. var WorkerTaskType = BABYLON.WorkerTaskType;
  9528. (function (WorkerReplyType) {
  9529. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9530. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9531. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9532. var WorkerReplyType = BABYLON.WorkerReplyType;
  9533. var CollisionCoordinatorWorker = (function () {
  9534. function CollisionCoordinatorWorker() {
  9535. var _this = this;
  9536. this._scaledPosition = BABYLON.Vector3.Zero();
  9537. this._scaledVelocity = BABYLON.Vector3.Zero();
  9538. this.onMeshUpdated = function (mesh) {
  9539. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9540. };
  9541. this.onGeometryUpdated = function (geometry) {
  9542. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9543. };
  9544. this._afterRender = function () {
  9545. if (!_this._init)
  9546. return;
  9547. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9548. return;
  9549. }
  9550. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9551. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9552. if (_this._runningUpdated > 4) {
  9553. return;
  9554. }
  9555. ++_this._runningUpdated;
  9556. var payload = {
  9557. updatedMeshes: _this._addUpdateMeshesList,
  9558. updatedGeometries: _this._addUpdateGeometriesList,
  9559. removedGeometries: _this._toRemoveGeometryArray,
  9560. removedMeshes: _this._toRemoveMeshesArray
  9561. };
  9562. var message = {
  9563. payload: payload,
  9564. taskType: WorkerTaskType.UPDATE
  9565. };
  9566. var serializable = [];
  9567. for (var id in payload.updatedGeometries) {
  9568. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9569. //prepare transferables
  9570. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9571. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9572. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9573. }
  9574. }
  9575. _this._worker.postMessage(message, serializable);
  9576. _this._addUpdateMeshesList = {};
  9577. _this._addUpdateGeometriesList = {};
  9578. _this._toRemoveGeometryArray = [];
  9579. _this._toRemoveMeshesArray = [];
  9580. };
  9581. this._onMessageFromWorker = function (e) {
  9582. var returnData = e.data;
  9583. if (returnData.error != WorkerReplyType.SUCCESS) {
  9584. //TODO what errors can be returned from the worker?
  9585. BABYLON.Tools.Warn("error returned from worker!");
  9586. return;
  9587. }
  9588. switch (returnData.taskType) {
  9589. case WorkerTaskType.INIT:
  9590. _this._init = true;
  9591. //Update the worked with ALL of the scene's current state
  9592. _this._scene.meshes.forEach(function (mesh) {
  9593. _this.onMeshAdded(mesh);
  9594. });
  9595. _this._scene.getGeometries().forEach(function (geometry) {
  9596. _this.onGeometryAdded(geometry);
  9597. });
  9598. break;
  9599. case WorkerTaskType.UPDATE:
  9600. _this._runningUpdated--;
  9601. break;
  9602. case WorkerTaskType.COLLIDE:
  9603. _this._runningCollisionTask = false;
  9604. var returnPayload = returnData.payload;
  9605. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9606. return;
  9607. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9608. //cleanup
  9609. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9610. break;
  9611. }
  9612. };
  9613. this._collisionsCallbackArray = [];
  9614. this._init = false;
  9615. this._runningUpdated = 0;
  9616. this._runningCollisionTask = false;
  9617. this._addUpdateMeshesList = {};
  9618. this._addUpdateGeometriesList = {};
  9619. this._toRemoveGeometryArray = [];
  9620. this._toRemoveMeshesArray = [];
  9621. }
  9622. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9623. if (!this._init)
  9624. return;
  9625. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9626. return;
  9627. position.divideToRef(collider.radius, this._scaledPosition);
  9628. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9629. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9630. var payload = {
  9631. collider: {
  9632. position: this._scaledPosition.asArray(),
  9633. velocity: this._scaledVelocity.asArray(),
  9634. radius: collider.radius.asArray()
  9635. },
  9636. collisionId: collisionIndex,
  9637. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9638. maximumRetry: maximumRetry
  9639. };
  9640. var message = {
  9641. payload: payload,
  9642. taskType: WorkerTaskType.COLLIDE
  9643. };
  9644. this._worker.postMessage(message);
  9645. };
  9646. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9647. this._scene = scene;
  9648. this._scene.registerAfterRender(this._afterRender);
  9649. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9650. this._worker = new Worker(workerUrl);
  9651. this._worker.onmessage = this._onMessageFromWorker;
  9652. var message = {
  9653. payload: {},
  9654. taskType: WorkerTaskType.INIT
  9655. };
  9656. this._worker.postMessage(message);
  9657. };
  9658. CollisionCoordinatorWorker.prototype.destroy = function () {
  9659. this._scene.unregisterAfterRender(this._afterRender);
  9660. this._worker.terminate();
  9661. };
  9662. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9663. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9664. this.onMeshUpdated(mesh);
  9665. };
  9666. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9667. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9668. };
  9669. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9670. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9671. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9672. this.onGeometryUpdated(geometry);
  9673. };
  9674. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9675. this._toRemoveGeometryArray.push(geometry.id);
  9676. };
  9677. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9678. var submeshes = [];
  9679. if (mesh.subMeshes) {
  9680. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9681. return {
  9682. position: idx,
  9683. verticesStart: sm.verticesStart,
  9684. verticesCount: sm.verticesCount,
  9685. indexStart: sm.indexStart,
  9686. indexCount: sm.indexCount,
  9687. hasMaterial: !!sm.getMaterial(),
  9688. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9689. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9690. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9691. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9692. };
  9693. });
  9694. }
  9695. var geometryId = null;
  9696. if (mesh instanceof BABYLON.Mesh) {
  9697. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9698. }
  9699. else if (mesh instanceof BABYLON.InstancedMesh) {
  9700. geometryId = mesh.sourceMesh.geometry ? mesh.sourceMesh.geometry.id : null;
  9701. }
  9702. return {
  9703. uniqueId: mesh.uniqueId,
  9704. id: mesh.id,
  9705. name: mesh.name,
  9706. geometryId: geometryId,
  9707. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9708. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9709. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9710. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9711. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9712. subMeshes: submeshes,
  9713. checkCollisions: mesh.checkCollisions
  9714. };
  9715. };
  9716. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9717. return {
  9718. id: geometry.id,
  9719. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9720. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9721. indices: new Int32Array(geometry.getIndices() || []),
  9722. };
  9723. };
  9724. return CollisionCoordinatorWorker;
  9725. })();
  9726. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9727. var CollisionCoordinatorLegacy = (function () {
  9728. function CollisionCoordinatorLegacy() {
  9729. this._scaledPosition = BABYLON.Vector3.Zero();
  9730. this._scaledVelocity = BABYLON.Vector3.Zero();
  9731. this._finalPosition = BABYLON.Vector3.Zero();
  9732. }
  9733. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9734. position.divideToRef(collider.radius, this._scaledPosition);
  9735. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9736. collider.collidedMesh = null;
  9737. collider.retry = 0;
  9738. collider.initialVelocity = this._scaledVelocity;
  9739. collider.initialPosition = this._scaledPosition;
  9740. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9741. this._finalPosition.multiplyInPlace(collider.radius);
  9742. //run the callback
  9743. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9744. };
  9745. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9746. this._scene = scene;
  9747. };
  9748. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9749. //Legacy need no destruction method.
  9750. };
  9751. //No update in legacy mode
  9752. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9753. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9754. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9755. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9756. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9757. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9758. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9759. if (excludedMesh === void 0) { excludedMesh = null; }
  9760. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9761. if (collider.retry >= maximumRetry) {
  9762. finalPosition.copyFrom(position);
  9763. return;
  9764. }
  9765. collider._initialize(position, velocity, closeDistance);
  9766. // Check all meshes
  9767. for (var index = 0; index < this._scene.meshes.length; index++) {
  9768. var mesh = this._scene.meshes[index];
  9769. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9770. mesh._checkCollision(collider);
  9771. }
  9772. }
  9773. if (!collider.collisionFound) {
  9774. position.addToRef(velocity, finalPosition);
  9775. return;
  9776. }
  9777. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9778. collider._getResponse(position, velocity);
  9779. }
  9780. if (velocity.length() <= closeDistance) {
  9781. finalPosition.copyFrom(position);
  9782. return;
  9783. }
  9784. collider.retry++;
  9785. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9786. };
  9787. return CollisionCoordinatorLegacy;
  9788. })();
  9789. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9790. })(BABYLON || (BABYLON = {}));
  9791. var BABYLON;
  9792. (function (BABYLON) {
  9793. var VRCameraMetrics = (function () {
  9794. function VRCameraMetrics() {
  9795. this.compensateDistorsion = true;
  9796. }
  9797. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9798. get: function () {
  9799. return this.hResolution / (2 * this.vResolution);
  9800. },
  9801. enumerable: true,
  9802. configurable: true
  9803. });
  9804. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9805. get: function () {
  9806. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9807. },
  9808. enumerable: true,
  9809. configurable: true
  9810. });
  9811. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9812. get: function () {
  9813. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9814. var h = (4 * meters) / this.hScreenSize;
  9815. return BABYLON.Matrix.Translation(h, 0, 0);
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9821. get: function () {
  9822. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9823. var h = (4 * meters) / this.hScreenSize;
  9824. return BABYLON.Matrix.Translation(-h, 0, 0);
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9830. get: function () {
  9831. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9832. },
  9833. enumerable: true,
  9834. configurable: true
  9835. });
  9836. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9837. get: function () {
  9838. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. VRCameraMetrics.GetDefault = function () {
  9844. var result = new VRCameraMetrics();
  9845. result.hResolution = 1280;
  9846. result.vResolution = 800;
  9847. result.hScreenSize = 0.149759993;
  9848. result.vScreenSize = 0.0935999975;
  9849. result.vScreenCenter = 0.0467999987,
  9850. result.eyeToScreenDistance = 0.0410000011;
  9851. result.lensSeparationDistance = 0.0635000020;
  9852. result.interpupillaryDistance = 0.0640000030;
  9853. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9854. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9855. result.postProcessScaleFactor = 1.714605507808412;
  9856. result.lensCenterOffset = 0.151976421;
  9857. return result;
  9858. };
  9859. return VRCameraMetrics;
  9860. })();
  9861. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9862. var Camera = (function (_super) {
  9863. __extends(Camera, _super);
  9864. function Camera(name, position, scene) {
  9865. _super.call(this, name, scene);
  9866. this.position = position;
  9867. // Members
  9868. this.upVector = BABYLON.Vector3.Up();
  9869. this.orthoLeft = null;
  9870. this.orthoRight = null;
  9871. this.orthoBottom = null;
  9872. this.orthoTop = null;
  9873. this.fov = 0.8;
  9874. this.minZ = 1.0;
  9875. this.maxZ = 10000.0;
  9876. this.inertia = 0.9;
  9877. this.mode = Camera.PERSPECTIVE_CAMERA;
  9878. this.isIntermediate = false;
  9879. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9880. this.layerMask = 0x0FFFFFFF;
  9881. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9882. // Camera rig members
  9883. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9884. this._rigCameras = new Array();
  9885. // Cache
  9886. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9887. this._projectionMatrix = new BABYLON.Matrix();
  9888. this._postProcesses = new Array();
  9889. this._postProcessesTakenIndices = [];
  9890. this._activeMeshes = new BABYLON.SmartArray(256);
  9891. this._globalPosition = BABYLON.Vector3.Zero();
  9892. scene.addCamera(this);
  9893. if (!scene.activeCamera) {
  9894. scene.activeCamera = this;
  9895. }
  9896. }
  9897. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9898. get: function () {
  9899. return Camera._PERSPECTIVE_CAMERA;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9905. get: function () {
  9906. return Camera._ORTHOGRAPHIC_CAMERA;
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9912. get: function () {
  9913. return Camera._FOVMODE_VERTICAL_FIXED;
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9919. get: function () {
  9920. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9926. get: function () {
  9927. return Camera._RIG_MODE_NONE;
  9928. },
  9929. enumerable: true,
  9930. configurable: true
  9931. });
  9932. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9933. get: function () {
  9934. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9940. get: function () {
  9941. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9947. get: function () {
  9948. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9954. get: function () {
  9955. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9961. get: function () {
  9962. return Camera._RIG_MODE_VR;
  9963. },
  9964. enumerable: true,
  9965. configurable: true
  9966. });
  9967. Object.defineProperty(Camera.prototype, "globalPosition", {
  9968. get: function () {
  9969. return this._globalPosition;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Camera.prototype.getActiveMeshes = function () {
  9975. return this._activeMeshes;
  9976. };
  9977. Camera.prototype.isActiveMesh = function (mesh) {
  9978. return (this._activeMeshes.indexOf(mesh) !== -1);
  9979. };
  9980. //Cache
  9981. Camera.prototype._initCache = function () {
  9982. _super.prototype._initCache.call(this);
  9983. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9984. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9985. this._cache.mode = undefined;
  9986. this._cache.minZ = undefined;
  9987. this._cache.maxZ = undefined;
  9988. this._cache.fov = undefined;
  9989. this._cache.aspectRatio = undefined;
  9990. this._cache.orthoLeft = undefined;
  9991. this._cache.orthoRight = undefined;
  9992. this._cache.orthoBottom = undefined;
  9993. this._cache.orthoTop = undefined;
  9994. this._cache.renderWidth = undefined;
  9995. this._cache.renderHeight = undefined;
  9996. };
  9997. Camera.prototype._updateCache = function (ignoreParentClass) {
  9998. if (!ignoreParentClass) {
  9999. _super.prototype._updateCache.call(this);
  10000. }
  10001. var engine = this.getEngine();
  10002. this._cache.position.copyFrom(this.position);
  10003. this._cache.upVector.copyFrom(this.upVector);
  10004. this._cache.mode = this.mode;
  10005. this._cache.minZ = this.minZ;
  10006. this._cache.maxZ = this.maxZ;
  10007. this._cache.fov = this.fov;
  10008. this._cache.aspectRatio = engine.getAspectRatio(this);
  10009. this._cache.orthoLeft = this.orthoLeft;
  10010. this._cache.orthoRight = this.orthoRight;
  10011. this._cache.orthoBottom = this.orthoBottom;
  10012. this._cache.orthoTop = this.orthoTop;
  10013. this._cache.renderWidth = engine.getRenderWidth();
  10014. this._cache.renderHeight = engine.getRenderHeight();
  10015. };
  10016. Camera.prototype._updateFromScene = function () {
  10017. this.updateCache();
  10018. this._update();
  10019. };
  10020. // Synchronized
  10021. Camera.prototype._isSynchronized = function () {
  10022. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10023. };
  10024. Camera.prototype._isSynchronizedViewMatrix = function () {
  10025. if (!_super.prototype._isSynchronized.call(this))
  10026. return false;
  10027. return this._cache.position.equals(this.position)
  10028. && this._cache.upVector.equals(this.upVector)
  10029. && this.isSynchronizedWithParent();
  10030. };
  10031. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10032. var check = this._cache.mode === this.mode
  10033. && this._cache.minZ === this.minZ
  10034. && this._cache.maxZ === this.maxZ;
  10035. if (!check) {
  10036. return false;
  10037. }
  10038. var engine = this.getEngine();
  10039. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10040. check = this._cache.fov === this.fov
  10041. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10042. }
  10043. else {
  10044. check = this._cache.orthoLeft === this.orthoLeft
  10045. && this._cache.orthoRight === this.orthoRight
  10046. && this._cache.orthoBottom === this.orthoBottom
  10047. && this._cache.orthoTop === this.orthoTop
  10048. && this._cache.renderWidth === engine.getRenderWidth()
  10049. && this._cache.renderHeight === engine.getRenderHeight();
  10050. }
  10051. return check;
  10052. };
  10053. // Controls
  10054. Camera.prototype.attachControl = function (element) {
  10055. };
  10056. Camera.prototype.detachControl = function (element) {
  10057. };
  10058. Camera.prototype._update = function () {
  10059. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10060. this._updateRigCameras();
  10061. }
  10062. this._checkInputs();
  10063. };
  10064. Camera.prototype._checkInputs = function () {
  10065. };
  10066. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10067. if (insertAt === void 0) { insertAt = null; }
  10068. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10069. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10070. return 0;
  10071. }
  10072. if (insertAt == null || insertAt < 0) {
  10073. this._postProcesses.push(postProcess);
  10074. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10075. return this._postProcesses.length - 1;
  10076. }
  10077. var add = 0;
  10078. if (this._postProcesses[insertAt]) {
  10079. var start = this._postProcesses.length - 1;
  10080. for (var i = start; i >= insertAt + 1; --i) {
  10081. this._postProcesses[i + 1] = this._postProcesses[i];
  10082. }
  10083. add = 1;
  10084. }
  10085. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10086. if (this._postProcessesTakenIndices[i] < insertAt) {
  10087. continue;
  10088. }
  10089. start = this._postProcessesTakenIndices.length - 1;
  10090. for (var j = start; j >= i; --j) {
  10091. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10092. }
  10093. this._postProcessesTakenIndices[i] = insertAt;
  10094. break;
  10095. }
  10096. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  10097. this._postProcessesTakenIndices.push(insertAt);
  10098. }
  10099. var result = insertAt + add;
  10100. this._postProcesses[result] = postProcess;
  10101. return result;
  10102. };
  10103. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10104. if (atIndices === void 0) { atIndices = null; }
  10105. var result = [];
  10106. if (!atIndices) {
  10107. var length = this._postProcesses.length;
  10108. for (var i = 0; i < length; i++) {
  10109. if (this._postProcesses[i] !== postProcess) {
  10110. continue;
  10111. }
  10112. delete this._postProcesses[i];
  10113. var index = this._postProcessesTakenIndices.indexOf(i);
  10114. this._postProcessesTakenIndices.splice(index, 1);
  10115. }
  10116. }
  10117. else {
  10118. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10119. for (i = 0; i < atIndices.length; i++) {
  10120. var foundPostProcess = this._postProcesses[atIndices[i]];
  10121. if (foundPostProcess !== postProcess) {
  10122. result.push(i);
  10123. continue;
  10124. }
  10125. delete this._postProcesses[atIndices[i]];
  10126. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10127. this._postProcessesTakenIndices.splice(index, 1);
  10128. }
  10129. }
  10130. return result;
  10131. };
  10132. Camera.prototype.getWorldMatrix = function () {
  10133. if (!this._worldMatrix) {
  10134. this._worldMatrix = BABYLON.Matrix.Identity();
  10135. }
  10136. var viewMatrix = this.getViewMatrix();
  10137. viewMatrix.invertToRef(this._worldMatrix);
  10138. return this._worldMatrix;
  10139. };
  10140. Camera.prototype._getViewMatrix = function () {
  10141. return BABYLON.Matrix.Identity();
  10142. };
  10143. Camera.prototype.getViewMatrix = function (force) {
  10144. this._computedViewMatrix = this._computeViewMatrix(force);
  10145. if (!force && this._isSynchronizedViewMatrix()) {
  10146. return this._computedViewMatrix;
  10147. }
  10148. if (!this.parent || !this.parent.getWorldMatrix) {
  10149. this._globalPosition.copyFrom(this.position);
  10150. }
  10151. else {
  10152. if (!this._worldMatrix) {
  10153. this._worldMatrix = BABYLON.Matrix.Identity();
  10154. }
  10155. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10156. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10157. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10158. this._computedViewMatrix.invert();
  10159. this._markSyncedWithParent();
  10160. }
  10161. this._currentRenderId = this.getScene().getRenderId();
  10162. return this._computedViewMatrix;
  10163. };
  10164. Camera.prototype._computeViewMatrix = function (force) {
  10165. if (!force && this._isSynchronizedViewMatrix()) {
  10166. return this._computedViewMatrix;
  10167. }
  10168. this._computedViewMatrix = this._getViewMatrix();
  10169. this._currentRenderId = this.getScene().getRenderId();
  10170. return this._computedViewMatrix;
  10171. };
  10172. Camera.prototype.getProjectionMatrix = function (force) {
  10173. if (!force && this._isSynchronizedProjectionMatrix()) {
  10174. return this._projectionMatrix;
  10175. }
  10176. var engine = this.getEngine();
  10177. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10178. if (this.minZ <= 0) {
  10179. this.minZ = 0.1;
  10180. }
  10181. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10182. return this._projectionMatrix;
  10183. }
  10184. var halfWidth = engine.getRenderWidth() / 2.0;
  10185. var halfHeight = engine.getRenderHeight() / 2.0;
  10186. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10187. return this._projectionMatrix;
  10188. };
  10189. Camera.prototype.dispose = function () {
  10190. // Remove from scene
  10191. this.getScene().removeCamera(this);
  10192. while (this._rigCameras.length > 0) {
  10193. this._rigCameras.pop().dispose();
  10194. }
  10195. // Postprocesses
  10196. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10197. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10198. }
  10199. };
  10200. // ---- Camera rigs section ----
  10201. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10202. while (this._rigCameras.length > 0) {
  10203. this._rigCameras.pop().dispose();
  10204. }
  10205. this.cameraRigMode = mode;
  10206. this._cameraRigParams = {};
  10207. switch (this.cameraRigMode) {
  10208. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10209. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10210. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10211. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10212. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10213. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10214. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10215. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10216. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10217. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10218. break;
  10219. }
  10220. var postProcesses = new Array();
  10221. switch (this.cameraRigMode) {
  10222. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10223. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10224. this._rigCameras[0].isIntermediate = true;
  10225. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10226. postProcesses[1].onApply = function (effect) {
  10227. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10228. };
  10229. break;
  10230. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10231. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10232. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10233. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10234. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10235. var secondCamIndex = 1 - firstCamIndex;
  10236. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10237. this._rigCameras[firstCamIndex].isIntermediate = true;
  10238. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10239. break;
  10240. case Camera.RIG_MODE_VR:
  10241. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10242. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10243. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10244. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10245. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10246. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10247. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10248. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10249. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10250. if (metrics.compensateDistorsion) {
  10251. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10252. }
  10253. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10254. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10255. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10256. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10257. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10258. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10259. if (metrics.compensateDistorsion) {
  10260. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10261. }
  10262. break;
  10263. }
  10264. this._update();
  10265. };
  10266. Camera.prototype._getVRProjectionMatrix = function () {
  10267. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10268. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10269. return this._projectionMatrix;
  10270. };
  10271. Camera.prototype.setCameraRigParameter = function (name, value) {
  10272. this._cameraRigParams[name] = value;
  10273. //provisionnally:
  10274. if (name === "interaxialDistance") {
  10275. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10276. }
  10277. };
  10278. /**
  10279. * May needs to be overridden by children so sub has required properties to be copied
  10280. */
  10281. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10282. return null;
  10283. };
  10284. /**
  10285. * May needs to be overridden by children
  10286. */
  10287. Camera.prototype._updateRigCameras = function () {
  10288. for (var i = 0; i < this._rigCameras.length; i++) {
  10289. this._rigCameras[i].minZ = this.minZ;
  10290. this._rigCameras[i].maxZ = this.maxZ;
  10291. this._rigCameras[i].fov = this.fov;
  10292. }
  10293. // only update viewport when ANAGLYPH
  10294. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10295. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10296. }
  10297. };
  10298. // Statics
  10299. Camera._PERSPECTIVE_CAMERA = 0;
  10300. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10301. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10302. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10303. Camera._RIG_MODE_NONE = 0;
  10304. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10305. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10306. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10307. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10308. Camera._RIG_MODE_VR = 20;
  10309. return Camera;
  10310. })(BABYLON.Node);
  10311. BABYLON.Camera = Camera;
  10312. })(BABYLON || (BABYLON = {}));
  10313. var BABYLON;
  10314. (function (BABYLON) {
  10315. var TargetCamera = (function (_super) {
  10316. __extends(TargetCamera, _super);
  10317. function TargetCamera(name, position, scene) {
  10318. _super.call(this, name, position, scene);
  10319. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10320. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10321. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10322. this.speed = 2.0;
  10323. this.noRotationConstraint = false;
  10324. this.lockedTarget = null;
  10325. this._currentTarget = BABYLON.Vector3.Zero();
  10326. this._viewMatrix = BABYLON.Matrix.Zero();
  10327. this._camMatrix = BABYLON.Matrix.Zero();
  10328. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10329. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10330. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10331. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10332. this._lookAtTemp = BABYLON.Matrix.Zero();
  10333. this._tempMatrix = BABYLON.Matrix.Zero();
  10334. }
  10335. TargetCamera.prototype.getFrontPosition = function (distance) {
  10336. var direction = this.getTarget().subtract(this.position);
  10337. direction.normalize();
  10338. direction.scaleInPlace(distance);
  10339. return this.globalPosition.add(direction);
  10340. };
  10341. TargetCamera.prototype._getLockedTargetPosition = function () {
  10342. if (!this.lockedTarget) {
  10343. return null;
  10344. }
  10345. return this.lockedTarget.position || this.lockedTarget;
  10346. };
  10347. // Cache
  10348. TargetCamera.prototype._initCache = function () {
  10349. _super.prototype._initCache.call(this);
  10350. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10351. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10352. };
  10353. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10354. if (!ignoreParentClass) {
  10355. _super.prototype._updateCache.call(this);
  10356. }
  10357. var lockedTargetPosition = this._getLockedTargetPosition();
  10358. if (!lockedTargetPosition) {
  10359. this._cache.lockedTarget = null;
  10360. }
  10361. else {
  10362. if (!this._cache.lockedTarget) {
  10363. this._cache.lockedTarget = lockedTargetPosition.clone();
  10364. }
  10365. else {
  10366. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10367. }
  10368. }
  10369. this._cache.rotation.copyFrom(this.rotation);
  10370. };
  10371. // Synchronized
  10372. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10373. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10374. return false;
  10375. }
  10376. var lockedTargetPosition = this._getLockedTargetPosition();
  10377. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10378. && this._cache.rotation.equals(this.rotation);
  10379. };
  10380. // Methods
  10381. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10382. var engine = this.getEngine();
  10383. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10384. };
  10385. // Target
  10386. TargetCamera.prototype.setTarget = function (target) {
  10387. this.upVector.normalize();
  10388. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10389. this._camMatrix.invert();
  10390. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10391. var vDir = target.subtract(this.position);
  10392. if (vDir.x >= 0.0) {
  10393. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10394. }
  10395. else {
  10396. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10397. }
  10398. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10399. if (isNaN(this.rotation.x)) {
  10400. this.rotation.x = 0;
  10401. }
  10402. if (isNaN(this.rotation.y)) {
  10403. this.rotation.y = 0;
  10404. }
  10405. if (isNaN(this.rotation.z)) {
  10406. this.rotation.z = 0;
  10407. }
  10408. };
  10409. TargetCamera.prototype.getTarget = function () {
  10410. return this._currentTarget;
  10411. };
  10412. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10413. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10414. };
  10415. TargetCamera.prototype._updatePosition = function () {
  10416. this.position.addInPlace(this.cameraDirection);
  10417. };
  10418. TargetCamera.prototype._checkInputs = function () {
  10419. var needToMove = this._decideIfNeedsToMove();
  10420. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10421. // Move
  10422. if (needToMove) {
  10423. this._updatePosition();
  10424. }
  10425. // Rotate
  10426. if (needToRotate) {
  10427. this.rotation.x += this.cameraRotation.x;
  10428. this.rotation.y += this.cameraRotation.y;
  10429. if (!this.noRotationConstraint) {
  10430. var limit = (Math.PI / 2) * 0.95;
  10431. if (this.rotation.x > limit)
  10432. this.rotation.x = limit;
  10433. if (this.rotation.x < -limit)
  10434. this.rotation.x = -limit;
  10435. }
  10436. }
  10437. // Inertia
  10438. if (needToMove) {
  10439. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10440. this.cameraDirection.x = 0;
  10441. }
  10442. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10443. this.cameraDirection.y = 0;
  10444. }
  10445. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10446. this.cameraDirection.z = 0;
  10447. }
  10448. this.cameraDirection.scaleInPlace(this.inertia);
  10449. }
  10450. if (needToRotate) {
  10451. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10452. this.cameraRotation.x = 0;
  10453. }
  10454. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10455. this.cameraRotation.y = 0;
  10456. }
  10457. this.cameraRotation.scaleInPlace(this.inertia);
  10458. }
  10459. _super.prototype._checkInputs.call(this);
  10460. };
  10461. TargetCamera.prototype._getViewMatrix = function () {
  10462. if (!this.lockedTarget) {
  10463. // Compute
  10464. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10465. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10466. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10467. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10468. this._lookAtTemp.invert();
  10469. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10470. }
  10471. else {
  10472. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10473. }
  10474. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10475. // Computing target and final matrix
  10476. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10477. }
  10478. else {
  10479. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10480. }
  10481. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10482. return this._viewMatrix;
  10483. };
  10484. TargetCamera.prototype._getVRViewMatrix = function () {
  10485. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10486. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10487. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10488. // Computing target and final matrix
  10489. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10490. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10491. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10492. return this._viewMatrix;
  10493. };
  10494. /**
  10495. * @override
  10496. * Override Camera.createRigCamera
  10497. */
  10498. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10499. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10500. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10501. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10502. rigCamera._cameraRigParams = {};
  10503. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10504. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10505. }
  10506. return rigCamera;
  10507. }
  10508. return null;
  10509. };
  10510. /**
  10511. * @override
  10512. * Override Camera._updateRigCameras
  10513. */
  10514. TargetCamera.prototype._updateRigCameras = function () {
  10515. switch (this.cameraRigMode) {
  10516. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10517. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10518. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10519. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10520. case BABYLON.Camera.RIG_MODE_VR:
  10521. var camLeft = this._rigCameras[0];
  10522. var camRight = this._rigCameras[1];
  10523. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10524. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10525. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10526. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10527. camLeft.position.copyFrom(this.position);
  10528. camRight.position.copyFrom(this.position);
  10529. }
  10530. else {
  10531. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10532. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10533. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10534. camLeft.setTarget(this.getTarget());
  10535. camRight.setTarget(this.getTarget());
  10536. }
  10537. break;
  10538. }
  10539. _super.prototype._updateRigCameras.call(this);
  10540. };
  10541. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10542. if (!this._rigCamTransformMatrix) {
  10543. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10544. }
  10545. var target = this.getTarget();
  10546. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10547. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10548. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10549. };
  10550. return TargetCamera;
  10551. })(BABYLON.Camera);
  10552. BABYLON.TargetCamera = TargetCamera;
  10553. })(BABYLON || (BABYLON = {}));
  10554. var BABYLON;
  10555. (function (BABYLON) {
  10556. var FreeCamera = (function (_super) {
  10557. __extends(FreeCamera, _super);
  10558. function FreeCamera(name, position, scene) {
  10559. var _this = this;
  10560. _super.call(this, name, position, scene);
  10561. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10562. this.keysUp = [38];
  10563. this.keysDown = [40];
  10564. this.keysLeft = [37];
  10565. this.keysRight = [39];
  10566. this.checkCollisions = false;
  10567. this.applyGravity = false;
  10568. this.angularSensibility = 2000.0;
  10569. this._keys = [];
  10570. this._collider = new BABYLON.Collider();
  10571. this._needMoveForGravity = false;
  10572. this._oldPosition = BABYLON.Vector3.Zero();
  10573. this._diffPosition = BABYLON.Vector3.Zero();
  10574. this._newPosition = BABYLON.Vector3.Zero();
  10575. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10576. if (collidedMesh === void 0) { collidedMesh = null; }
  10577. //TODO move this to the collision coordinator!
  10578. if (_this.getScene().workerCollisions)
  10579. newPosition.multiplyInPlace(_this._collider.radius);
  10580. var updatePosition = function (newPos) {
  10581. _this._newPosition.copyFrom(newPos);
  10582. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10583. var oldPosition = _this.position.clone();
  10584. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10585. _this.position.addInPlace(_this._diffPosition);
  10586. if (_this.onCollide && collidedMesh) {
  10587. _this.onCollide(collidedMesh);
  10588. }
  10589. }
  10590. };
  10591. updatePosition(newPosition);
  10592. };
  10593. }
  10594. // Controls
  10595. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10596. var _this = this;
  10597. var previousPosition;
  10598. var engine = this.getEngine();
  10599. if (this._attachedElement) {
  10600. return;
  10601. }
  10602. this._attachedElement = element;
  10603. if (this._onMouseDown === undefined) {
  10604. this._onMouseDown = function (evt) {
  10605. previousPosition = {
  10606. x: evt.clientX,
  10607. y: evt.clientY
  10608. };
  10609. if (!noPreventDefault) {
  10610. evt.preventDefault();
  10611. }
  10612. };
  10613. this._onMouseUp = function (evt) {
  10614. previousPosition = null;
  10615. if (!noPreventDefault) {
  10616. evt.preventDefault();
  10617. }
  10618. };
  10619. this._onMouseOut = function (evt) {
  10620. previousPosition = null;
  10621. _this._keys = [];
  10622. if (!noPreventDefault) {
  10623. evt.preventDefault();
  10624. }
  10625. };
  10626. this._onMouseMove = function (evt) {
  10627. if (!previousPosition && !engine.isPointerLock) {
  10628. return;
  10629. }
  10630. var offsetX;
  10631. var offsetY;
  10632. if (!engine.isPointerLock) {
  10633. offsetX = evt.clientX - previousPosition.x;
  10634. offsetY = evt.clientY - previousPosition.y;
  10635. }
  10636. else {
  10637. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10638. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10639. }
  10640. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10641. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10642. previousPosition = {
  10643. x: evt.clientX,
  10644. y: evt.clientY
  10645. };
  10646. if (!noPreventDefault) {
  10647. evt.preventDefault();
  10648. }
  10649. };
  10650. this._onKeyDown = function (evt) {
  10651. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10652. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10653. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10654. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10655. var index = _this._keys.indexOf(evt.keyCode);
  10656. if (index === -1) {
  10657. _this._keys.push(evt.keyCode);
  10658. }
  10659. if (!noPreventDefault) {
  10660. evt.preventDefault();
  10661. }
  10662. }
  10663. };
  10664. this._onKeyUp = function (evt) {
  10665. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10666. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10667. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10668. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10669. var index = _this._keys.indexOf(evt.keyCode);
  10670. if (index >= 0) {
  10671. _this._keys.splice(index, 1);
  10672. }
  10673. if (!noPreventDefault) {
  10674. evt.preventDefault();
  10675. }
  10676. }
  10677. };
  10678. this._onLostFocus = function () {
  10679. _this._keys = [];
  10680. };
  10681. this._reset = function () {
  10682. _this._keys = [];
  10683. previousPosition = null;
  10684. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10685. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10686. };
  10687. }
  10688. element.addEventListener("mousedown", this._onMouseDown, false);
  10689. element.addEventListener("mouseup", this._onMouseUp, false);
  10690. element.addEventListener("mouseout", this._onMouseOut, false);
  10691. element.addEventListener("mousemove", this._onMouseMove, false);
  10692. BABYLON.Tools.RegisterTopRootEvents([
  10693. { name: "keydown", handler: this._onKeyDown },
  10694. { name: "keyup", handler: this._onKeyUp },
  10695. { name: "blur", handler: this._onLostFocus }
  10696. ]);
  10697. };
  10698. FreeCamera.prototype.detachControl = function (element) {
  10699. if (this._attachedElement != element) {
  10700. return;
  10701. }
  10702. element.removeEventListener("mousedown", this._onMouseDown);
  10703. element.removeEventListener("mouseup", this._onMouseUp);
  10704. element.removeEventListener("mouseout", this._onMouseOut);
  10705. element.removeEventListener("mousemove", this._onMouseMove);
  10706. BABYLON.Tools.UnregisterTopRootEvents([
  10707. { name: "keydown", handler: this._onKeyDown },
  10708. { name: "keyup", handler: this._onKeyUp },
  10709. { name: "blur", handler: this._onLostFocus }
  10710. ]);
  10711. this._attachedElement = null;
  10712. if (this._reset) {
  10713. this._reset();
  10714. }
  10715. };
  10716. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10717. var globalPosition;
  10718. if (this.parent) {
  10719. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10720. }
  10721. else {
  10722. globalPosition = this.position;
  10723. }
  10724. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10725. this._collider.radius = this.ellipsoid;
  10726. //add gravity to the velocity to prevent the dual-collision checking
  10727. if (this.applyGravity) {
  10728. velocity.addInPlace(this.getScene().gravity);
  10729. }
  10730. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10731. };
  10732. FreeCamera.prototype._checkInputs = function () {
  10733. if (!this._localDirection) {
  10734. this._localDirection = BABYLON.Vector3.Zero();
  10735. this._transformedDirection = BABYLON.Vector3.Zero();
  10736. }
  10737. // Keyboard
  10738. for (var index = 0; index < this._keys.length; index++) {
  10739. var keyCode = this._keys[index];
  10740. var speed = this._computeLocalCameraSpeed();
  10741. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10742. this._localDirection.copyFromFloats(-speed, 0, 0);
  10743. }
  10744. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10745. this._localDirection.copyFromFloats(0, 0, speed);
  10746. }
  10747. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10748. this._localDirection.copyFromFloats(speed, 0, 0);
  10749. }
  10750. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10751. this._localDirection.copyFromFloats(0, 0, -speed);
  10752. }
  10753. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10754. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10755. this.cameraDirection.addInPlace(this._transformedDirection);
  10756. }
  10757. _super.prototype._checkInputs.call(this);
  10758. };
  10759. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10760. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10761. };
  10762. FreeCamera.prototype._updatePosition = function () {
  10763. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10764. this._collideWithWorld(this.cameraDirection);
  10765. }
  10766. else {
  10767. this.position.addInPlace(this.cameraDirection);
  10768. }
  10769. };
  10770. return FreeCamera;
  10771. })(BABYLON.TargetCamera);
  10772. BABYLON.FreeCamera = FreeCamera;
  10773. })(BABYLON || (BABYLON = {}));
  10774. var BABYLON;
  10775. (function (BABYLON) {
  10776. var FollowCamera = (function (_super) {
  10777. __extends(FollowCamera, _super);
  10778. function FollowCamera(name, position, scene) {
  10779. _super.call(this, name, position, scene);
  10780. this.radius = 12;
  10781. this.rotationOffset = 0;
  10782. this.heightOffset = 4;
  10783. this.cameraAcceleration = 0.05;
  10784. this.maxCameraSpeed = 20;
  10785. }
  10786. FollowCamera.prototype.getRadians = function (degrees) {
  10787. return degrees * Math.PI / 180;
  10788. };
  10789. FollowCamera.prototype.follow = function (cameraTarget) {
  10790. if (!cameraTarget)
  10791. return;
  10792. var yRotation;
  10793. if (cameraTarget.rotationQuaternion) {
  10794. var rotMatrix = new BABYLON.Matrix();
  10795. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10796. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10797. }
  10798. else {
  10799. yRotation = cameraTarget.rotation.y;
  10800. }
  10801. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10802. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10803. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10804. var dx = targetX - this.position.x;
  10805. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10806. var dz = (targetZ) - this.position.z;
  10807. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10808. var vy = dy * this.cameraAcceleration;
  10809. var vz = dz * this.cameraAcceleration * 2;
  10810. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10811. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10812. }
  10813. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10814. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10815. }
  10816. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10817. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10818. }
  10819. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10820. this.setTarget(cameraTarget.position);
  10821. };
  10822. FollowCamera.prototype._checkInputs = function () {
  10823. _super.prototype._checkInputs.call(this);
  10824. this.follow(this.target);
  10825. };
  10826. return FollowCamera;
  10827. })(BABYLON.TargetCamera);
  10828. BABYLON.FollowCamera = FollowCamera;
  10829. var ArcFollowCamera = (function (_super) {
  10830. __extends(ArcFollowCamera, _super);
  10831. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10832. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10833. this.alpha = alpha;
  10834. this.beta = beta;
  10835. this.radius = radius;
  10836. this.target = target;
  10837. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10838. this.follow();
  10839. }
  10840. ArcFollowCamera.prototype.follow = function () {
  10841. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10842. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10843. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10844. this.position = this.target.position.add(this._cartesianCoordinates);
  10845. this.setTarget(this.target.position);
  10846. };
  10847. ArcFollowCamera.prototype._checkInputs = function () {
  10848. _super.prototype._checkInputs.call(this);
  10849. this.follow();
  10850. };
  10851. return ArcFollowCamera;
  10852. })(BABYLON.TargetCamera);
  10853. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10854. })(BABYLON || (BABYLON = {}));
  10855. var BABYLON;
  10856. (function (BABYLON) {
  10857. // We're mainly based on the logic defined into the FreeCamera code
  10858. var TouchCamera = (function (_super) {
  10859. __extends(TouchCamera, _super);
  10860. function TouchCamera(name, position, scene) {
  10861. _super.call(this, name, position, scene);
  10862. this._offsetX = null;
  10863. this._offsetY = null;
  10864. this._pointerCount = 0;
  10865. this._pointerPressed = [];
  10866. this.angularSensibility = 200000.0;
  10867. this.moveSensibility = 500.0;
  10868. }
  10869. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10870. var _this = this;
  10871. var previousPosition;
  10872. if (this._attachedCanvas) {
  10873. return;
  10874. }
  10875. this._attachedCanvas = canvas;
  10876. if (this._onPointerDown === undefined) {
  10877. this._onPointerDown = function (evt) {
  10878. if (!noPreventDefault) {
  10879. evt.preventDefault();
  10880. }
  10881. _this._pointerPressed.push(evt.pointerId);
  10882. if (_this._pointerPressed.length !== 1) {
  10883. return;
  10884. }
  10885. previousPosition = {
  10886. x: evt.clientX,
  10887. y: evt.clientY
  10888. };
  10889. };
  10890. this._onPointerUp = function (evt) {
  10891. if (!noPreventDefault) {
  10892. evt.preventDefault();
  10893. }
  10894. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10895. if (index === -1) {
  10896. return;
  10897. }
  10898. _this._pointerPressed.splice(index, 1);
  10899. if (index != 0) {
  10900. return;
  10901. }
  10902. previousPosition = null;
  10903. _this._offsetX = null;
  10904. _this._offsetY = null;
  10905. };
  10906. this._onPointerMove = function (evt) {
  10907. if (!noPreventDefault) {
  10908. evt.preventDefault();
  10909. }
  10910. if (!previousPosition) {
  10911. return;
  10912. }
  10913. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10914. if (index != 0) {
  10915. return;
  10916. }
  10917. _this._offsetX = evt.clientX - previousPosition.x;
  10918. _this._offsetY = -(evt.clientY - previousPosition.y);
  10919. };
  10920. this._onLostFocus = function () {
  10921. _this._offsetX = null;
  10922. _this._offsetY = null;
  10923. };
  10924. }
  10925. canvas.addEventListener("pointerdown", this._onPointerDown);
  10926. canvas.addEventListener("pointerup", this._onPointerUp);
  10927. canvas.addEventListener("pointerout", this._onPointerUp);
  10928. canvas.addEventListener("pointermove", this._onPointerMove);
  10929. BABYLON.Tools.RegisterTopRootEvents([
  10930. { name: "blur", handler: this._onLostFocus }
  10931. ]);
  10932. };
  10933. TouchCamera.prototype.detachControl = function (canvas) {
  10934. if (this._attachedCanvas != canvas) {
  10935. return;
  10936. }
  10937. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10938. canvas.removeEventListener("pointerup", this._onPointerUp);
  10939. canvas.removeEventListener("pointerout", this._onPointerUp);
  10940. canvas.removeEventListener("pointermove", this._onPointerMove);
  10941. BABYLON.Tools.UnregisterTopRootEvents([
  10942. { name: "blur", handler: this._onLostFocus }
  10943. ]);
  10944. this._attachedCanvas = null;
  10945. };
  10946. TouchCamera.prototype._checkInputs = function () {
  10947. if (this._offsetX) {
  10948. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10949. if (this._pointerPressed.length > 1) {
  10950. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10951. }
  10952. else {
  10953. var speed = this._computeLocalCameraSpeed();
  10954. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10955. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10956. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10957. }
  10958. }
  10959. _super.prototype._checkInputs.call(this);
  10960. };
  10961. return TouchCamera;
  10962. })(BABYLON.FreeCamera);
  10963. BABYLON.TouchCamera = TouchCamera;
  10964. })(BABYLON || (BABYLON = {}));
  10965. var BABYLON;
  10966. (function (BABYLON) {
  10967. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10968. var ArcRotateCamera = (function (_super) {
  10969. __extends(ArcRotateCamera, _super);
  10970. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10971. var _this = this;
  10972. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10973. this.alpha = alpha;
  10974. this.beta = beta;
  10975. this.radius = radius;
  10976. this.target = target;
  10977. this.inertialAlphaOffset = 0;
  10978. this.inertialBetaOffset = 0;
  10979. this.inertialRadiusOffset = 0;
  10980. this.lowerAlphaLimit = null;
  10981. this.upperAlphaLimit = null;
  10982. this.lowerBetaLimit = 0.01;
  10983. this.upperBetaLimit = Math.PI;
  10984. this.lowerRadiusLimit = null;
  10985. this.upperRadiusLimit = null;
  10986. this.angularSensibilityX = 1000.0;
  10987. this.angularSensibilityY = 1000.0;
  10988. this.wheelPrecision = 3.0;
  10989. this.pinchPrecision = 2.0;
  10990. this.panningSensibility = 50.0;
  10991. this.inertialPanningX = 0;
  10992. this.inertialPanningY = 0;
  10993. this.keysUp = [38];
  10994. this.keysDown = [40];
  10995. this.keysLeft = [37];
  10996. this.keysRight = [39];
  10997. this.zoomOnFactor = 1;
  10998. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10999. this.pinchInwards = true;
  11000. this.allowUpsideDown = true;
  11001. this._keys = [];
  11002. this._viewMatrix = new BABYLON.Matrix();
  11003. this._isRightClick = false;
  11004. this._isCtrlPushed = false;
  11005. this.checkCollisions = false;
  11006. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11007. this._collider = new BABYLON.Collider();
  11008. this._previousPosition = BABYLON.Vector3.Zero();
  11009. this._collisionVelocity = BABYLON.Vector3.Zero();
  11010. this._newPosition = BABYLON.Vector3.Zero();
  11011. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11012. if (collidedMesh === void 0) { collidedMesh = null; }
  11013. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11014. newPosition.multiplyInPlace(_this._collider.radius);
  11015. }
  11016. if (!collidedMesh) {
  11017. _this._previousPosition.copyFrom(_this.position);
  11018. }
  11019. else {
  11020. _this.setPosition(_this.position);
  11021. if (_this.onCollide) {
  11022. _this.onCollide(collidedMesh);
  11023. }
  11024. }
  11025. // Recompute because of constraints
  11026. var cosa = Math.cos(_this.alpha);
  11027. var sina = Math.sin(_this.alpha);
  11028. var cosb = Math.cos(_this.beta);
  11029. var sinb = Math.sin(_this.beta);
  11030. var target = _this._getTargetPosition();
  11031. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11032. _this.position.copyFrom(_this._newPosition);
  11033. var up = _this.upVector;
  11034. if (_this.allowUpsideDown && _this.beta < 0) {
  11035. var up = up.clone();
  11036. up = up.negate();
  11037. }
  11038. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11039. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11040. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11041. _this._collisionTriggered = false;
  11042. };
  11043. if (!this.target) {
  11044. this.target = BABYLON.Vector3.Zero();
  11045. }
  11046. this.getViewMatrix();
  11047. }
  11048. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11049. //deprecated angularSensibility support
  11050. get: function () {
  11051. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11052. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11053. },
  11054. //deprecated angularSensibility support
  11055. set: function (value) {
  11056. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11057. this.angularSensibilityX = value;
  11058. this.angularSensibilityY = value;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. ArcRotateCamera.prototype._getTargetPosition = function () {
  11064. return this.target.position || this.target;
  11065. };
  11066. // Cache
  11067. ArcRotateCamera.prototype._initCache = function () {
  11068. _super.prototype._initCache.call(this);
  11069. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11070. this._cache.alpha = undefined;
  11071. this._cache.beta = undefined;
  11072. this._cache.radius = undefined;
  11073. this._cache.targetScreenOffset = undefined;
  11074. };
  11075. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11076. if (!ignoreParentClass) {
  11077. _super.prototype._updateCache.call(this);
  11078. }
  11079. this._cache.target.copyFrom(this._getTargetPosition());
  11080. this._cache.alpha = this.alpha;
  11081. this._cache.beta = this.beta;
  11082. this._cache.radius = this.radius;
  11083. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11084. };
  11085. // Synchronized
  11086. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11087. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11088. return false;
  11089. return this._cache.target.equals(this._getTargetPosition())
  11090. && this._cache.alpha === this.alpha
  11091. && this._cache.beta === this.beta
  11092. && this._cache.radius === this.radius
  11093. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11094. };
  11095. // Methods
  11096. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11097. var _this = this;
  11098. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11099. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11100. var previousPinchDistance = 0;
  11101. var pointers = new BABYLON.SmartCollection();
  11102. if (this._attachedElement) {
  11103. return;
  11104. }
  11105. this._attachedElement = element;
  11106. var engine = this.getEngine();
  11107. if (this._onPointerDown === undefined) {
  11108. this._onPointerDown = function (evt) {
  11109. // Manage panning with right click
  11110. _this._isRightClick = evt.button === 2 ? true : false;
  11111. // manage pointers
  11112. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11113. cacheSoloPointer = pointers.item(evt.pointerId);
  11114. if (!noPreventDefault) {
  11115. evt.preventDefault();
  11116. }
  11117. };
  11118. this._onPointerUp = function (evt) {
  11119. cacheSoloPointer = null;
  11120. previousPinchDistance = 0;
  11121. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11122. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11123. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11124. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11125. pointers.empty();
  11126. if (!noPreventDefault) {
  11127. evt.preventDefault();
  11128. }
  11129. };
  11130. this._onContextMenu = function (evt) {
  11131. evt.preventDefault();
  11132. };
  11133. this._onPointerMove = function (evt) {
  11134. if (!noPreventDefault) {
  11135. evt.preventDefault();
  11136. }
  11137. switch (pointers.count) {
  11138. case 1:
  11139. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11140. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11141. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11142. }
  11143. else {
  11144. var offsetX = evt.clientX - cacheSoloPointer.x;
  11145. var offsetY = evt.clientY - cacheSoloPointer.y;
  11146. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11147. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11148. }
  11149. cacheSoloPointer.x = evt.clientX;
  11150. cacheSoloPointer.y = evt.clientY;
  11151. break;
  11152. case 2:
  11153. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11154. pointers.item(evt.pointerId).x = evt.clientX;
  11155. pointers.item(evt.pointerId).y = evt.clientY;
  11156. var direction = _this.pinchInwards ? 1 : -1;
  11157. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11158. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11159. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11160. if (previousPinchDistance === 0) {
  11161. previousPinchDistance = pinchSquaredDistance;
  11162. return;
  11163. }
  11164. if (pinchSquaredDistance !== previousPinchDistance) {
  11165. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11166. previousPinchDistance = pinchSquaredDistance;
  11167. }
  11168. break;
  11169. default:
  11170. if (pointers.item(evt.pointerId)) {
  11171. pointers.item(evt.pointerId).x = evt.clientX;
  11172. pointers.item(evt.pointerId).y = evt.clientY;
  11173. }
  11174. }
  11175. };
  11176. this._onMouseMove = function (evt) {
  11177. if (!engine.isPointerLock) {
  11178. return;
  11179. }
  11180. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11181. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11182. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11183. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11184. if (!noPreventDefault) {
  11185. evt.preventDefault();
  11186. }
  11187. };
  11188. this._wheel = function (event) {
  11189. var delta = 0;
  11190. if (event.wheelDelta) {
  11191. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11192. }
  11193. else if (event.detail) {
  11194. delta = -event.detail / _this.wheelPrecision;
  11195. }
  11196. if (delta)
  11197. _this.inertialRadiusOffset += delta;
  11198. if (event.preventDefault) {
  11199. if (!noPreventDefault) {
  11200. event.preventDefault();
  11201. }
  11202. }
  11203. };
  11204. this._onKeyDown = function (evt) {
  11205. _this._isCtrlPushed = evt.ctrlKey;
  11206. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11207. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11208. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11209. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11210. var index = _this._keys.indexOf(evt.keyCode);
  11211. if (index === -1) {
  11212. _this._keys.push(evt.keyCode);
  11213. }
  11214. if (evt.preventDefault) {
  11215. if (!noPreventDefault) {
  11216. evt.preventDefault();
  11217. }
  11218. }
  11219. }
  11220. };
  11221. this._onKeyUp = function (evt) {
  11222. _this._isCtrlPushed = evt.ctrlKey;
  11223. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11224. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11225. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11226. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11227. var index = _this._keys.indexOf(evt.keyCode);
  11228. if (index >= 0) {
  11229. _this._keys.splice(index, 1);
  11230. }
  11231. if (evt.preventDefault) {
  11232. if (!noPreventDefault) {
  11233. evt.preventDefault();
  11234. }
  11235. }
  11236. }
  11237. };
  11238. this._onLostFocus = function () {
  11239. _this._keys = [];
  11240. pointers.empty();
  11241. previousPinchDistance = 0;
  11242. cacheSoloPointer = null;
  11243. };
  11244. this._onGestureStart = function (e) {
  11245. if (window.MSGesture === undefined) {
  11246. return;
  11247. }
  11248. if (!_this._MSGestureHandler) {
  11249. _this._MSGestureHandler = new MSGesture();
  11250. _this._MSGestureHandler.target = element;
  11251. }
  11252. _this._MSGestureHandler.addPointer(e.pointerId);
  11253. };
  11254. this._onGesture = function (e) {
  11255. _this.radius *= e.scale;
  11256. if (e.preventDefault) {
  11257. if (!noPreventDefault) {
  11258. e.stopPropagation();
  11259. e.preventDefault();
  11260. }
  11261. }
  11262. };
  11263. this._reset = function () {
  11264. _this._keys = [];
  11265. _this.inertialAlphaOffset = 0;
  11266. _this.inertialBetaOffset = 0;
  11267. _this.inertialRadiusOffset = 0;
  11268. pointers.empty();
  11269. previousPinchDistance = 0;
  11270. cacheSoloPointer = null;
  11271. };
  11272. }
  11273. if (!useCtrlForPanning) {
  11274. element.addEventListener("contextmenu", this._onContextMenu, false);
  11275. }
  11276. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11277. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11278. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11279. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11280. element.addEventListener("mousemove", this._onMouseMove, false);
  11281. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11282. element.addEventListener("MSGestureChange", this._onGesture, false);
  11283. element.addEventListener('mousewheel', this._wheel, false);
  11284. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11285. BABYLON.Tools.RegisterTopRootEvents([
  11286. { name: "keydown", handler: this._onKeyDown },
  11287. { name: "keyup", handler: this._onKeyUp },
  11288. { name: "blur", handler: this._onLostFocus }
  11289. ]);
  11290. };
  11291. ArcRotateCamera.prototype.detachControl = function (element) {
  11292. if (this._attachedElement !== element) {
  11293. return;
  11294. }
  11295. element.removeEventListener("contextmenu", this._onContextMenu);
  11296. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11297. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11298. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11299. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11300. element.removeEventListener("mousemove", this._onMouseMove);
  11301. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11302. element.removeEventListener("MSGestureChange", this._onGesture);
  11303. element.removeEventListener('mousewheel', this._wheel);
  11304. element.removeEventListener('DOMMouseScroll', this._wheel);
  11305. BABYLON.Tools.UnregisterTopRootEvents([
  11306. { name: "keydown", handler: this._onKeyDown },
  11307. { name: "keyup", handler: this._onKeyUp },
  11308. { name: "blur", handler: this._onLostFocus }
  11309. ]);
  11310. this._MSGestureHandler = null;
  11311. this._attachedElement = null;
  11312. if (this._reset) {
  11313. this._reset();
  11314. }
  11315. };
  11316. ArcRotateCamera.prototype._checkInputs = function () {
  11317. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11318. if (this._collisionTriggered) {
  11319. return;
  11320. }
  11321. // Keyboard
  11322. for (var index = 0; index < this._keys.length; index++) {
  11323. var keyCode = this._keys[index];
  11324. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11325. this.inertialAlphaOffset -= 0.01;
  11326. }
  11327. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11328. this.inertialBetaOffset -= 0.01;
  11329. }
  11330. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11331. this.inertialAlphaOffset += 0.01;
  11332. }
  11333. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11334. this.inertialBetaOffset += 0.01;
  11335. }
  11336. }
  11337. // Inertia
  11338. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11339. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11340. this.beta += this.inertialBetaOffset;
  11341. this.radius -= this.inertialRadiusOffset;
  11342. this.inertialAlphaOffset *= this.inertia;
  11343. this.inertialBetaOffset *= this.inertia;
  11344. this.inertialRadiusOffset *= this.inertia;
  11345. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11346. this.inertialAlphaOffset = 0;
  11347. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11348. this.inertialBetaOffset = 0;
  11349. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11350. this.inertialRadiusOffset = 0;
  11351. }
  11352. // Panning inertia
  11353. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11354. if (!this._localDirection) {
  11355. this._localDirection = BABYLON.Vector3.Zero();
  11356. this._transformedDirection = BABYLON.Vector3.Zero();
  11357. }
  11358. this.inertialPanningX *= this.inertia;
  11359. this.inertialPanningY *= this.inertia;
  11360. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11361. this.inertialPanningX = 0;
  11362. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11363. this.inertialPanningY = 0;
  11364. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11365. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11366. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11367. this.target.addInPlace(this._transformedDirection);
  11368. }
  11369. // Limits
  11370. this._checkLimits();
  11371. _super.prototype._checkInputs.call(this);
  11372. };
  11373. ArcRotateCamera.prototype._checkLimits = function () {
  11374. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11375. if (this.allowUpsideDown && this.beta > Math.PI) {
  11376. this.beta = this.beta - (2 * Math.PI);
  11377. }
  11378. }
  11379. else {
  11380. if (this.beta < this.lowerBetaLimit) {
  11381. this.beta = this.lowerBetaLimit;
  11382. }
  11383. }
  11384. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11385. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11386. this.beta = this.beta + (2 * Math.PI);
  11387. }
  11388. }
  11389. else {
  11390. if (this.beta > this.upperBetaLimit) {
  11391. this.beta = this.upperBetaLimit;
  11392. }
  11393. }
  11394. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11395. this.alpha = this.lowerAlphaLimit;
  11396. }
  11397. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11398. this.alpha = this.upperAlphaLimit;
  11399. }
  11400. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11401. this.radius = this.lowerRadiusLimit;
  11402. }
  11403. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11404. this.radius = this.upperRadiusLimit;
  11405. }
  11406. };
  11407. ArcRotateCamera.prototype.setPosition = function (position) {
  11408. var radiusv3 = position.subtract(this._getTargetPosition());
  11409. this.radius = radiusv3.length();
  11410. // Alpha
  11411. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11412. if (radiusv3.z < 0) {
  11413. this.alpha = 2 * Math.PI - this.alpha;
  11414. }
  11415. // Beta
  11416. this.beta = Math.acos(radiusv3.y / this.radius);
  11417. this._checkLimits();
  11418. };
  11419. ArcRotateCamera.prototype._getViewMatrix = function () {
  11420. // Compute
  11421. var cosa = Math.cos(this.alpha);
  11422. var sina = Math.sin(this.alpha);
  11423. var cosb = Math.cos(this.beta);
  11424. var sinb = Math.sin(this.beta);
  11425. var target = this._getTargetPosition();
  11426. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11427. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11428. this._collider.radius = this.collisionRadius;
  11429. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11430. this._collisionTriggered = true;
  11431. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11432. }
  11433. else {
  11434. this.position.copyFrom(this._newPosition);
  11435. var up = this.upVector;
  11436. if (this.allowUpsideDown && this.beta < 0) {
  11437. var up = up.clone();
  11438. up = up.negate();
  11439. }
  11440. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11441. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11442. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11443. }
  11444. return this._viewMatrix;
  11445. };
  11446. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11447. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11448. meshes = meshes || this.getScene().meshes;
  11449. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11450. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11451. this.radius = distance * this.zoomOnFactor;
  11452. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11453. };
  11454. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11455. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11456. var meshesOrMinMaxVector;
  11457. var distance;
  11458. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11459. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11460. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11461. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11462. }
  11463. else {
  11464. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11465. distance = meshesOrMinMaxVectorAndDistance.distance;
  11466. }
  11467. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11468. if (!doNotUpdateMaxZ) {
  11469. this.maxZ = distance * 2;
  11470. }
  11471. };
  11472. /**
  11473. * @override
  11474. * Override Camera.createRigCamera
  11475. */
  11476. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11477. switch (this.cameraRigMode) {
  11478. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11479. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11480. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11481. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11482. case BABYLON.Camera.RIG_MODE_VR:
  11483. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11484. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11485. }
  11486. };
  11487. /**
  11488. * @override
  11489. * Override Camera._updateRigCameras
  11490. */
  11491. ArcRotateCamera.prototype._updateRigCameras = function () {
  11492. switch (this.cameraRigMode) {
  11493. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11494. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11495. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11496. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11497. case BABYLON.Camera.RIG_MODE_VR:
  11498. var camLeft = this._rigCameras[0];
  11499. var camRight = this._rigCameras[1];
  11500. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11501. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11502. camLeft.beta = camRight.beta = this.beta;
  11503. camLeft.radius = camRight.radius = this.radius;
  11504. break;
  11505. }
  11506. _super.prototype._updateRigCameras.call(this);
  11507. };
  11508. return ArcRotateCamera;
  11509. })(BABYLON.TargetCamera);
  11510. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11511. })(BABYLON || (BABYLON = {}));
  11512. var BABYLON;
  11513. (function (BABYLON) {
  11514. // We're mainly based on the logic defined into the FreeCamera code
  11515. var DeviceOrientationCamera = (function (_super) {
  11516. __extends(DeviceOrientationCamera, _super);
  11517. function DeviceOrientationCamera(name, position, scene) {
  11518. var _this = this;
  11519. _super.call(this, name, position, scene);
  11520. this._offsetX = null;
  11521. this._offsetY = null;
  11522. this._orientationGamma = 0;
  11523. this._orientationBeta = 0;
  11524. this._initialOrientationGamma = 0;
  11525. this._initialOrientationBeta = 0;
  11526. this.angularSensibility = 10000.0;
  11527. this.moveSensibility = 50.0;
  11528. window.addEventListener("resize", function () {
  11529. _this._initialOrientationGamma = null;
  11530. }, false);
  11531. }
  11532. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11533. var _this = this;
  11534. if (this._attachedCanvas) {
  11535. return;
  11536. }
  11537. this._attachedCanvas = canvas;
  11538. if (!this._orientationChanged) {
  11539. this._orientationChanged = function (evt) {
  11540. if (!_this._initialOrientationGamma) {
  11541. _this._initialOrientationGamma = evt.gamma;
  11542. _this._initialOrientationBeta = evt.beta;
  11543. }
  11544. _this._orientationGamma = evt.gamma;
  11545. _this._orientationBeta = evt.beta;
  11546. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11547. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11548. };
  11549. }
  11550. window.addEventListener("deviceorientation", this._orientationChanged);
  11551. };
  11552. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11553. if (this._attachedCanvas != canvas) {
  11554. return;
  11555. }
  11556. window.removeEventListener("deviceorientation", this._orientationChanged);
  11557. this._attachedCanvas = null;
  11558. this._orientationGamma = 0;
  11559. this._orientationBeta = 0;
  11560. this._initialOrientationGamma = 0;
  11561. this._initialOrientationBeta = 0;
  11562. };
  11563. DeviceOrientationCamera.prototype._checkInputs = function () {
  11564. if (!this._offsetX) {
  11565. return;
  11566. }
  11567. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11568. var speed = this._computeLocalCameraSpeed();
  11569. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11570. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11571. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11572. _super.prototype._checkInputs.call(this);
  11573. };
  11574. return DeviceOrientationCamera;
  11575. })(BABYLON.FreeCamera);
  11576. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11577. })(BABYLON || (BABYLON = {}));
  11578. var BABYLON;
  11579. (function (BABYLON) {
  11580. var Gamepads = (function () {
  11581. function Gamepads(ongamedpadconnected) {
  11582. var _this = this;
  11583. this.babylonGamepads = [];
  11584. this.oneGamepadConnected = false;
  11585. this.isMonitoring = false;
  11586. this.gamepadEventSupported = 'GamepadEvent' in window;
  11587. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11588. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11589. 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=";
  11590. this._callbackGamepadConnected = ongamedpadconnected;
  11591. if (this.gamepadSupportAvailable) {
  11592. // Checking if the gamepad connected event is supported (like in Firefox)
  11593. if (this.gamepadEventSupported) {
  11594. window.addEventListener('gamepadconnected', function (evt) {
  11595. _this._onGamepadConnected(evt);
  11596. }, false);
  11597. window.addEventListener('gamepaddisconnected', function (evt) {
  11598. _this._onGamepadDisconnected(evt);
  11599. }, false);
  11600. }
  11601. else {
  11602. this._startMonitoringGamepads();
  11603. }
  11604. if (!this.oneGamepadConnected) {
  11605. this._insertGamepadDOMInstructions();
  11606. }
  11607. }
  11608. else {
  11609. this._insertGamepadDOMNotSupported();
  11610. }
  11611. }
  11612. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11613. Gamepads.gamepadDOMInfo = document.createElement("div");
  11614. var buttonAImage = document.createElement("img");
  11615. buttonAImage.src = this.buttonADataURL;
  11616. var spanMessage = document.createElement("span");
  11617. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11618. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11619. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11620. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11621. Gamepads.gamepadDOMInfo.style.width = "100%";
  11622. Gamepads.gamepadDOMInfo.style.height = "48px";
  11623. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11624. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11625. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11626. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11627. buttonAImage.style.position = "relative";
  11628. buttonAImage.style.bottom = "8px";
  11629. spanMessage.style.position = "relative";
  11630. spanMessage.style.fontSize = "32px";
  11631. spanMessage.style.bottom = "32px";
  11632. spanMessage.style.color = "green";
  11633. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11634. };
  11635. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11636. Gamepads.gamepadDOMInfo = document.createElement("div");
  11637. var spanMessage = document.createElement("span");
  11638. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11639. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11640. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11641. Gamepads.gamepadDOMInfo.style.width = "100%";
  11642. Gamepads.gamepadDOMInfo.style.height = "40px";
  11643. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11644. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11645. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11646. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11647. spanMessage.style.position = "relative";
  11648. spanMessage.style.fontSize = "32px";
  11649. spanMessage.style.color = "red";
  11650. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11651. };
  11652. Gamepads.prototype.dispose = function () {
  11653. if (Gamepads.gamepadDOMInfo) {
  11654. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11655. }
  11656. };
  11657. Gamepads.prototype._onGamepadConnected = function (evt) {
  11658. var newGamepad = this._addNewGamepad(evt.gamepad);
  11659. if (this._callbackGamepadConnected)
  11660. this._callbackGamepadConnected(newGamepad);
  11661. this._startMonitoringGamepads();
  11662. };
  11663. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11664. if (!this.oneGamepadConnected) {
  11665. this.oneGamepadConnected = true;
  11666. if (Gamepads.gamepadDOMInfo) {
  11667. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11668. Gamepads.gamepadDOMInfo = null;
  11669. }
  11670. }
  11671. var newGamepad;
  11672. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11673. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11674. }
  11675. else {
  11676. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11677. }
  11678. this.babylonGamepads.push(newGamepad);
  11679. return newGamepad;
  11680. };
  11681. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11682. // Remove the gamepad from the list of gamepads to monitor.
  11683. for (var i in this.babylonGamepads) {
  11684. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11685. this.babylonGamepads.splice(i, 1);
  11686. break;
  11687. }
  11688. }
  11689. // If no gamepads are left, stop the polling loop.
  11690. if (this.babylonGamepads.length == 0) {
  11691. this._stopMonitoringGamepads();
  11692. }
  11693. };
  11694. Gamepads.prototype._startMonitoringGamepads = function () {
  11695. if (!this.isMonitoring) {
  11696. this.isMonitoring = true;
  11697. this._checkGamepadsStatus();
  11698. }
  11699. };
  11700. Gamepads.prototype._stopMonitoringGamepads = function () {
  11701. this.isMonitoring = false;
  11702. };
  11703. Gamepads.prototype._checkGamepadsStatus = function () {
  11704. var _this = this;
  11705. // updating gamepad objects
  11706. this._updateGamepadObjects();
  11707. for (var i in this.babylonGamepads) {
  11708. this.babylonGamepads[i].update();
  11709. }
  11710. if (this.isMonitoring) {
  11711. if (window.requestAnimationFrame) {
  11712. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11713. }
  11714. else if (window.mozRequestAnimationFrame) {
  11715. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11716. }
  11717. else if (window.webkitRequestAnimationFrame) {
  11718. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11719. }
  11720. }
  11721. };
  11722. // This function is called only on Chrome, which does not yet support
  11723. // connection/disconnection events, but requires you to monitor
  11724. // an array for changes.
  11725. Gamepads.prototype._updateGamepadObjects = function () {
  11726. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11727. for (var i = 0; i < gamepads.length; i++) {
  11728. if (gamepads[i]) {
  11729. if (!(gamepads[i].index in this.babylonGamepads)) {
  11730. var newGamepad = this._addNewGamepad(gamepads[i]);
  11731. if (this._callbackGamepadConnected) {
  11732. this._callbackGamepadConnected(newGamepad);
  11733. }
  11734. }
  11735. else {
  11736. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11737. }
  11738. }
  11739. }
  11740. };
  11741. return Gamepads;
  11742. })();
  11743. BABYLON.Gamepads = Gamepads;
  11744. var StickValues = (function () {
  11745. function StickValues(x, y) {
  11746. this.x = x;
  11747. this.y = y;
  11748. }
  11749. return StickValues;
  11750. })();
  11751. BABYLON.StickValues = StickValues;
  11752. var Gamepad = (function () {
  11753. function Gamepad(id, index, browserGamepad) {
  11754. this.id = id;
  11755. this.index = index;
  11756. this.browserGamepad = browserGamepad;
  11757. if (this.browserGamepad.axes.length >= 2) {
  11758. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11759. }
  11760. if (this.browserGamepad.axes.length >= 4) {
  11761. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11762. }
  11763. }
  11764. Gamepad.prototype.onleftstickchanged = function (callback) {
  11765. this._onleftstickchanged = callback;
  11766. };
  11767. Gamepad.prototype.onrightstickchanged = function (callback) {
  11768. this._onrightstickchanged = callback;
  11769. };
  11770. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11771. get: function () {
  11772. return this._leftStick;
  11773. },
  11774. set: function (newValues) {
  11775. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11776. this._onleftstickchanged(newValues);
  11777. }
  11778. this._leftStick = newValues;
  11779. },
  11780. enumerable: true,
  11781. configurable: true
  11782. });
  11783. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11784. get: function () {
  11785. return this._rightStick;
  11786. },
  11787. set: function (newValues) {
  11788. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11789. this._onrightstickchanged(newValues);
  11790. }
  11791. this._rightStick = newValues;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Gamepad.prototype.update = function () {
  11797. if (this._leftStick) {
  11798. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11799. }
  11800. if (this._rightStick) {
  11801. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11802. }
  11803. };
  11804. return Gamepad;
  11805. })();
  11806. BABYLON.Gamepad = Gamepad;
  11807. var GenericPad = (function (_super) {
  11808. __extends(GenericPad, _super);
  11809. function GenericPad(id, index, gamepad) {
  11810. _super.call(this, id, index, gamepad);
  11811. this.id = id;
  11812. this.index = index;
  11813. this.gamepad = gamepad;
  11814. this._buttons = new Array(gamepad.buttons.length);
  11815. }
  11816. GenericPad.prototype.onbuttondown = function (callback) {
  11817. this._onbuttondown = callback;
  11818. };
  11819. GenericPad.prototype.onbuttonup = function (callback) {
  11820. this._onbuttonup = callback;
  11821. };
  11822. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11823. if (newValue !== currentValue) {
  11824. if (this._onbuttondown && newValue === 1) {
  11825. this._onbuttondown(buttonIndex);
  11826. }
  11827. if (this._onbuttonup && newValue === 0) {
  11828. this._onbuttonup(buttonIndex);
  11829. }
  11830. }
  11831. return newValue;
  11832. };
  11833. GenericPad.prototype.update = function () {
  11834. _super.prototype.update.call(this);
  11835. for (var index = 0; index < this._buttons.length; index++) {
  11836. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11837. }
  11838. };
  11839. return GenericPad;
  11840. })(Gamepad);
  11841. BABYLON.GenericPad = GenericPad;
  11842. (function (Xbox360Button) {
  11843. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11844. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11845. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11846. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11847. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11848. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11849. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11850. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11851. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11852. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11853. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11854. var Xbox360Button = BABYLON.Xbox360Button;
  11855. (function (Xbox360Dpad) {
  11856. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11857. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11858. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11859. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11860. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11861. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11862. var Xbox360Pad = (function (_super) {
  11863. __extends(Xbox360Pad, _super);
  11864. function Xbox360Pad() {
  11865. _super.apply(this, arguments);
  11866. this._leftTrigger = 0;
  11867. this._rightTrigger = 0;
  11868. this._buttonA = 0;
  11869. this._buttonB = 0;
  11870. this._buttonX = 0;
  11871. this._buttonY = 0;
  11872. this._buttonBack = 0;
  11873. this._buttonStart = 0;
  11874. this._buttonLB = 0;
  11875. this._buttonRB = 0;
  11876. this._buttonLeftStick = 0;
  11877. this._buttonRightStick = 0;
  11878. this._dPadUp = 0;
  11879. this._dPadDown = 0;
  11880. this._dPadLeft = 0;
  11881. this._dPadRight = 0;
  11882. }
  11883. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11884. this._onlefttriggerchanged = callback;
  11885. };
  11886. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11887. this._onrighttriggerchanged = callback;
  11888. };
  11889. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11890. get: function () {
  11891. return this._leftTrigger;
  11892. },
  11893. set: function (newValue) {
  11894. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11895. this._onlefttriggerchanged(newValue);
  11896. }
  11897. this._leftTrigger = newValue;
  11898. },
  11899. enumerable: true,
  11900. configurable: true
  11901. });
  11902. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11903. get: function () {
  11904. return this._rightTrigger;
  11905. },
  11906. set: function (newValue) {
  11907. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11908. this._onrighttriggerchanged(newValue);
  11909. }
  11910. this._rightTrigger = newValue;
  11911. },
  11912. enumerable: true,
  11913. configurable: true
  11914. });
  11915. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11916. this._onbuttondown = callback;
  11917. };
  11918. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11919. this._onbuttonup = callback;
  11920. };
  11921. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11922. this._ondpaddown = callback;
  11923. };
  11924. Xbox360Pad.prototype.ondpadup = function (callback) {
  11925. this._ondpadup = callback;
  11926. };
  11927. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11928. if (newValue !== currentValue) {
  11929. if (this._onbuttondown && newValue === 1) {
  11930. this._onbuttondown(buttonType);
  11931. }
  11932. if (this._onbuttonup && newValue === 0) {
  11933. this._onbuttonup(buttonType);
  11934. }
  11935. }
  11936. return newValue;
  11937. };
  11938. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11939. if (newValue !== currentValue) {
  11940. if (this._ondpaddown && newValue === 1) {
  11941. this._ondpaddown(buttonType);
  11942. }
  11943. if (this._ondpadup && newValue === 0) {
  11944. this._ondpadup(buttonType);
  11945. }
  11946. }
  11947. return newValue;
  11948. };
  11949. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11950. get: function () {
  11951. return this._buttonA;
  11952. },
  11953. set: function (value) {
  11954. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11955. },
  11956. enumerable: true,
  11957. configurable: true
  11958. });
  11959. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11960. get: function () {
  11961. return this._buttonB;
  11962. },
  11963. set: function (value) {
  11964. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11970. get: function () {
  11971. return this._buttonX;
  11972. },
  11973. set: function (value) {
  11974. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11980. get: function () {
  11981. return this._buttonY;
  11982. },
  11983. set: function (value) {
  11984. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11990. get: function () {
  11991. return this._buttonStart;
  11992. },
  11993. set: function (value) {
  11994. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  12000. get: function () {
  12001. return this._buttonBack;
  12002. },
  12003. set: function (value) {
  12004. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  12010. get: function () {
  12011. return this._buttonLB;
  12012. },
  12013. set: function (value) {
  12014. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12020. get: function () {
  12021. return this._buttonRB;
  12022. },
  12023. set: function (value) {
  12024. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12030. get: function () {
  12031. return this._buttonLeftStick;
  12032. },
  12033. set: function (value) {
  12034. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12040. get: function () {
  12041. return this._buttonRightStick;
  12042. },
  12043. set: function (value) {
  12044. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12050. get: function () {
  12051. return this._dPadUp;
  12052. },
  12053. set: function (value) {
  12054. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12060. get: function () {
  12061. return this._dPadDown;
  12062. },
  12063. set: function (value) {
  12064. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12070. get: function () {
  12071. return this._dPadLeft;
  12072. },
  12073. set: function (value) {
  12074. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12075. },
  12076. enumerable: true,
  12077. configurable: true
  12078. });
  12079. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12080. get: function () {
  12081. return this._dPadRight;
  12082. },
  12083. set: function (value) {
  12084. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12085. },
  12086. enumerable: true,
  12087. configurable: true
  12088. });
  12089. Xbox360Pad.prototype.update = function () {
  12090. _super.prototype.update.call(this);
  12091. this.buttonA = this.browserGamepad.buttons[0].value;
  12092. this.buttonB = this.browserGamepad.buttons[1].value;
  12093. this.buttonX = this.browserGamepad.buttons[2].value;
  12094. this.buttonY = this.browserGamepad.buttons[3].value;
  12095. this.buttonLB = this.browserGamepad.buttons[4].value;
  12096. this.buttonRB = this.browserGamepad.buttons[5].value;
  12097. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12098. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12099. this.buttonBack = this.browserGamepad.buttons[8].value;
  12100. this.buttonStart = this.browserGamepad.buttons[9].value;
  12101. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12102. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12103. this.dPadUp = this.browserGamepad.buttons[12].value;
  12104. this.dPadDown = this.browserGamepad.buttons[13].value;
  12105. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12106. this.dPadRight = this.browserGamepad.buttons[15].value;
  12107. };
  12108. return Xbox360Pad;
  12109. })(Gamepad);
  12110. BABYLON.Xbox360Pad = Xbox360Pad;
  12111. })(BABYLON || (BABYLON = {}));
  12112. var BABYLON;
  12113. (function (BABYLON) {
  12114. // We're mainly based on the logic defined into the FreeCamera code
  12115. var GamepadCamera = (function (_super) {
  12116. __extends(GamepadCamera, _super);
  12117. function GamepadCamera(name, position, scene) {
  12118. var _this = this;
  12119. _super.call(this, name, position, scene);
  12120. this.angularSensibility = 200;
  12121. this.moveSensibility = 75;
  12122. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12123. }
  12124. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12125. // Only the first gamepad can control the camera
  12126. if (gamepad.index === 0) {
  12127. this._gamepad = gamepad;
  12128. }
  12129. };
  12130. GamepadCamera.prototype._checkInputs = function () {
  12131. if (this._gamepad) {
  12132. var LSValues = this._gamepad.leftStick;
  12133. var normalizedLX = LSValues.x / this.moveSensibility;
  12134. var normalizedLY = LSValues.y / this.moveSensibility;
  12135. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12136. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12137. var RSValues = this._gamepad.rightStick;
  12138. var normalizedRX = RSValues.x / this.angularSensibility;
  12139. var normalizedRY = RSValues.y / this.angularSensibility;
  12140. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12141. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12142. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12143. var speed = this._computeLocalCameraSpeed() * 50.0;
  12144. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12145. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12146. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12147. }
  12148. _super.prototype._checkInputs.call(this);
  12149. };
  12150. GamepadCamera.prototype.dispose = function () {
  12151. this._gamepads.dispose();
  12152. _super.prototype.dispose.call(this);
  12153. };
  12154. return GamepadCamera;
  12155. })(BABYLON.FreeCamera);
  12156. BABYLON.GamepadCamera = GamepadCamera;
  12157. })(BABYLON || (BABYLON = {}));
  12158. var BABYLON;
  12159. (function (BABYLON) {
  12160. var RenderingManager = (function () {
  12161. function RenderingManager(scene) {
  12162. this._renderingGroups = new Array();
  12163. this._scene = scene;
  12164. }
  12165. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12166. if (this._scene._activeParticleSystems.length === 0) {
  12167. return;
  12168. }
  12169. // Particles
  12170. var beforeParticlesDate = BABYLON.Tools.Now;
  12171. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12172. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12173. if (particleSystem.renderingGroupId !== index) {
  12174. continue;
  12175. }
  12176. this._clearDepthBuffer();
  12177. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12178. this._scene._activeParticles += particleSystem.render();
  12179. }
  12180. }
  12181. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12182. };
  12183. RenderingManager.prototype._renderSprites = function (index) {
  12184. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12185. return;
  12186. }
  12187. // Sprites
  12188. var beforeSpritessDate = BABYLON.Tools.Now;
  12189. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12190. var spriteManager = this._scene.spriteManagers[id];
  12191. if (spriteManager.renderingGroupId === index) {
  12192. this._clearDepthBuffer();
  12193. spriteManager.render();
  12194. }
  12195. }
  12196. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12197. };
  12198. RenderingManager.prototype._clearDepthBuffer = function () {
  12199. if (this._depthBufferAlreadyCleaned) {
  12200. return;
  12201. }
  12202. this._scene.getEngine().clear(0, false, true);
  12203. this._depthBufferAlreadyCleaned = true;
  12204. };
  12205. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12206. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12207. this._depthBufferAlreadyCleaned = false;
  12208. var renderingGroup = this._renderingGroups[index];
  12209. var needToStepBack = false;
  12210. if (renderingGroup) {
  12211. this._clearDepthBuffer();
  12212. if (!renderingGroup.render(customRenderFunction)) {
  12213. this._renderingGroups.splice(index, 1);
  12214. needToStepBack = true;
  12215. }
  12216. }
  12217. if (renderSprites) {
  12218. this._renderSprites(index);
  12219. }
  12220. if (renderParticles) {
  12221. this._renderParticles(index, activeMeshes);
  12222. }
  12223. if (needToStepBack) {
  12224. index--;
  12225. }
  12226. }
  12227. };
  12228. RenderingManager.prototype.reset = function () {
  12229. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12230. if (renderingGroup) {
  12231. renderingGroup.prepare();
  12232. }
  12233. });
  12234. };
  12235. RenderingManager.prototype.dispatch = function (subMesh) {
  12236. var mesh = subMesh.getMesh();
  12237. var renderingGroupId = mesh.renderingGroupId || 0;
  12238. if (!this._renderingGroups[renderingGroupId]) {
  12239. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12240. }
  12241. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12242. };
  12243. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12244. return RenderingManager;
  12245. })();
  12246. BABYLON.RenderingManager = RenderingManager;
  12247. })(BABYLON || (BABYLON = {}));
  12248. var BABYLON;
  12249. (function (BABYLON) {
  12250. var RenderingGroup = (function () {
  12251. function RenderingGroup(index, scene) {
  12252. this.index = index;
  12253. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12254. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12255. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12256. this._scene = scene;
  12257. }
  12258. RenderingGroup.prototype.render = function (customRenderFunction) {
  12259. if (customRenderFunction) {
  12260. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12261. return true;
  12262. }
  12263. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12264. return false;
  12265. }
  12266. var engine = this._scene.getEngine();
  12267. // Opaque
  12268. var subIndex;
  12269. var submesh;
  12270. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12271. submesh = this._opaqueSubMeshes.data[subIndex];
  12272. submesh.render(false);
  12273. }
  12274. // Alpha test
  12275. engine.setAlphaTesting(true);
  12276. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12277. submesh = this._alphaTestSubMeshes.data[subIndex];
  12278. submesh.render(false);
  12279. }
  12280. engine.setAlphaTesting(false);
  12281. // Transparent
  12282. if (this._transparentSubMeshes.length) {
  12283. // Sorting
  12284. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12285. submesh = this._transparentSubMeshes.data[subIndex];
  12286. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12287. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12288. }
  12289. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12290. sortedArray.sort(function (a, b) {
  12291. // Alpha index first
  12292. if (a._alphaIndex > b._alphaIndex) {
  12293. return 1;
  12294. }
  12295. if (a._alphaIndex < b._alphaIndex) {
  12296. return -1;
  12297. }
  12298. // Then distance to camera
  12299. if (a._distanceToCamera < b._distanceToCamera) {
  12300. return 1;
  12301. }
  12302. if (a._distanceToCamera > b._distanceToCamera) {
  12303. return -1;
  12304. }
  12305. return 0;
  12306. });
  12307. // Rendering
  12308. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12309. submesh = sortedArray[subIndex];
  12310. submesh.render(true);
  12311. }
  12312. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12313. }
  12314. return true;
  12315. };
  12316. RenderingGroup.prototype.prepare = function () {
  12317. this._opaqueSubMeshes.reset();
  12318. this._transparentSubMeshes.reset();
  12319. this._alphaTestSubMeshes.reset();
  12320. };
  12321. RenderingGroup.prototype.dispatch = function (subMesh) {
  12322. var material = subMesh.getMaterial();
  12323. var mesh = subMesh.getMesh();
  12324. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12325. this._transparentSubMeshes.push(subMesh);
  12326. }
  12327. else if (material.needAlphaTesting()) {
  12328. this._alphaTestSubMeshes.push(subMesh);
  12329. }
  12330. else {
  12331. this._opaqueSubMeshes.push(subMesh); // Opaque
  12332. }
  12333. };
  12334. return RenderingGroup;
  12335. })();
  12336. BABYLON.RenderingGroup = RenderingGroup;
  12337. })(BABYLON || (BABYLON = {}));
  12338. var BABYLON;
  12339. (function (BABYLON) {
  12340. /**
  12341. * Represents a scene to be rendered by the engine.
  12342. * @see http://doc.babylonjs.com/page.php?p=21911
  12343. */
  12344. var Scene = (function () {
  12345. /**
  12346. * @constructor
  12347. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12348. */
  12349. function Scene(engine) {
  12350. // Members
  12351. this.autoClear = true;
  12352. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12353. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12354. this.forceWireframe = false;
  12355. this.forcePointsCloud = false;
  12356. this.forceShowBoundingBoxes = false;
  12357. this.animationsEnabled = true;
  12358. 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
  12359. // Fog
  12360. /**
  12361. * is fog enabled on this scene.
  12362. * @type {boolean}
  12363. */
  12364. this.fogEnabled = true;
  12365. this.fogMode = Scene.FOGMODE_NONE;
  12366. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12367. this.fogDensity = 0.1;
  12368. this.fogStart = 0;
  12369. this.fogEnd = 1000.0;
  12370. // Lights
  12371. /**
  12372. * is shadow enabled on this scene.
  12373. * @type {boolean}
  12374. */
  12375. this.shadowsEnabled = true;
  12376. /**
  12377. * is light enabled on this scene.
  12378. * @type {boolean}
  12379. */
  12380. this.lightsEnabled = true;
  12381. /**
  12382. * All of the lights added to this scene.
  12383. * @see BABYLON.Light
  12384. * @type {BABYLON.Light[]}
  12385. */
  12386. this.lights = new Array();
  12387. // Cameras
  12388. /**
  12389. * All of the cameras added to this scene.
  12390. * @see BABYLON.Camera
  12391. * @type {BABYLON.Camera[]}
  12392. */
  12393. this.cameras = new Array();
  12394. this.activeCameras = new Array();
  12395. // Meshes
  12396. /**
  12397. * All of the (abstract) meshes added to this scene.
  12398. * @see BABYLON.AbstractMesh
  12399. * @type {BABYLON.AbstractMesh[]}
  12400. */
  12401. this.meshes = new Array();
  12402. // Geometries
  12403. this._geometries = new Array();
  12404. this.materials = new Array();
  12405. this.multiMaterials = new Array();
  12406. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12407. // Textures
  12408. this.texturesEnabled = true;
  12409. this.textures = new Array();
  12410. // Particles
  12411. this.particlesEnabled = true;
  12412. this.particleSystems = new Array();
  12413. // Sprites
  12414. this.spritesEnabled = true;
  12415. this.spriteManagers = new Array();
  12416. // Layers
  12417. this.layers = new Array();
  12418. // Skeletons
  12419. this.skeletonsEnabled = true;
  12420. this.skeletons = new Array();
  12421. // Lens flares
  12422. this.lensFlaresEnabled = true;
  12423. this.lensFlareSystems = new Array();
  12424. // Collisions
  12425. this.collisionsEnabled = true;
  12426. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12427. // Postprocesses
  12428. this.postProcessesEnabled = true;
  12429. // Customs render targets
  12430. this.renderTargetsEnabled = true;
  12431. this.dumpNextRenderTargets = false;
  12432. this.customRenderTargets = new Array();
  12433. // Imported meshes
  12434. this.importedMeshesFiles = new Array();
  12435. this._actionManagers = new Array();
  12436. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12437. // Procedural textures
  12438. this.proceduralTexturesEnabled = true;
  12439. this._proceduralTextures = new Array();
  12440. this.soundTracks = new Array();
  12441. this._audioEnabled = true;
  12442. this._headphone = false;
  12443. this._totalVertices = 0;
  12444. this._activeIndices = 0;
  12445. this._activeParticles = 0;
  12446. this._lastFrameDuration = 0;
  12447. this._evaluateActiveMeshesDuration = 0;
  12448. this._renderTargetsDuration = 0;
  12449. this._particlesDuration = 0;
  12450. this._renderDuration = 0;
  12451. this._spritesDuration = 0;
  12452. this._animationRatio = 0;
  12453. this._renderId = 0;
  12454. this._executeWhenReadyTimeoutId = -1;
  12455. this._toBeDisposed = new BABYLON.SmartArray(256);
  12456. this._onReadyCallbacks = new Array();
  12457. this._pendingData = []; //ANY
  12458. this._onBeforeRenderCallbacks = new Array();
  12459. this._onAfterRenderCallbacks = new Array();
  12460. this._activeMeshes = new BABYLON.SmartArray(256);
  12461. this._processedMaterials = new BABYLON.SmartArray(256);
  12462. this._renderTargets = new BABYLON.SmartArray(256);
  12463. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12464. this._activeSkeletons = new BABYLON.SmartArray(32);
  12465. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12466. this._activeBones = 0;
  12467. this._activeAnimatables = new Array();
  12468. this._transformMatrix = BABYLON.Matrix.Zero();
  12469. this._edgesRenderers = new BABYLON.SmartArray(16);
  12470. this._uniqueIdCounter = 0;
  12471. this._engine = engine;
  12472. engine.scenes.push(this);
  12473. this._renderingManager = new BABYLON.RenderingManager(this);
  12474. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12475. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12476. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12477. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12478. this.attachControl();
  12479. this._debugLayer = new BABYLON.DebugLayer(this);
  12480. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12481. //simplification queue
  12482. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12483. //collision coordinator initialization. For now legacy per default.
  12484. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12485. }
  12486. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12487. get: function () {
  12488. return Scene._FOGMODE_NONE;
  12489. },
  12490. enumerable: true,
  12491. configurable: true
  12492. });
  12493. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12494. get: function () {
  12495. return Scene._FOGMODE_EXP;
  12496. },
  12497. enumerable: true,
  12498. configurable: true
  12499. });
  12500. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12501. get: function () {
  12502. return Scene._FOGMODE_EXP2;
  12503. },
  12504. enumerable: true,
  12505. configurable: true
  12506. });
  12507. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12508. get: function () {
  12509. return Scene._FOGMODE_LINEAR;
  12510. },
  12511. enumerable: true,
  12512. configurable: true
  12513. });
  12514. Object.defineProperty(Scene.prototype, "debugLayer", {
  12515. // Properties
  12516. get: function () {
  12517. return this._debugLayer;
  12518. },
  12519. enumerable: true,
  12520. configurable: true
  12521. });
  12522. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12523. get: function () {
  12524. return this._workerCollisions;
  12525. },
  12526. set: function (enabled) {
  12527. enabled = (enabled && !!Worker);
  12528. this._workerCollisions = enabled;
  12529. if (this.collisionCoordinator) {
  12530. this.collisionCoordinator.destroy();
  12531. }
  12532. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12533. this.collisionCoordinator.init(this);
  12534. },
  12535. enumerable: true,
  12536. configurable: true
  12537. });
  12538. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12539. get: function () {
  12540. return this._selectionOctree;
  12541. },
  12542. enumerable: true,
  12543. configurable: true
  12544. });
  12545. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12546. /**
  12547. * The mesh that is currently under the pointer.
  12548. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12549. */
  12550. get: function () {
  12551. return this._meshUnderPointer;
  12552. },
  12553. enumerable: true,
  12554. configurable: true
  12555. });
  12556. Object.defineProperty(Scene.prototype, "pointerX", {
  12557. /**
  12558. * Current on-screen X position of the pointer
  12559. * @return {number} X position of the pointer
  12560. */
  12561. get: function () {
  12562. return this._pointerX;
  12563. },
  12564. enumerable: true,
  12565. configurable: true
  12566. });
  12567. Object.defineProperty(Scene.prototype, "pointerY", {
  12568. /**
  12569. * Current on-screen Y position of the pointer
  12570. * @return {number} Y position of the pointer
  12571. */
  12572. get: function () {
  12573. return this._pointerY;
  12574. },
  12575. enumerable: true,
  12576. configurable: true
  12577. });
  12578. Scene.prototype.getCachedMaterial = function () {
  12579. return this._cachedMaterial;
  12580. };
  12581. Scene.prototype.getBoundingBoxRenderer = function () {
  12582. return this._boundingBoxRenderer;
  12583. };
  12584. Scene.prototype.getOutlineRenderer = function () {
  12585. return this._outlineRenderer;
  12586. };
  12587. Scene.prototype.getEngine = function () {
  12588. return this._engine;
  12589. };
  12590. Scene.prototype.getTotalVertices = function () {
  12591. return this._totalVertices;
  12592. };
  12593. Scene.prototype.getActiveIndices = function () {
  12594. return this._activeIndices;
  12595. };
  12596. Scene.prototype.getActiveParticles = function () {
  12597. return this._activeParticles;
  12598. };
  12599. Scene.prototype.getActiveBones = function () {
  12600. return this._activeBones;
  12601. };
  12602. // Stats
  12603. Scene.prototype.getLastFrameDuration = function () {
  12604. return this._lastFrameDuration;
  12605. };
  12606. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12607. return this._evaluateActiveMeshesDuration;
  12608. };
  12609. Scene.prototype.getActiveMeshes = function () {
  12610. return this._activeMeshes;
  12611. };
  12612. Scene.prototype.getRenderTargetsDuration = function () {
  12613. return this._renderTargetsDuration;
  12614. };
  12615. Scene.prototype.getRenderDuration = function () {
  12616. return this._renderDuration;
  12617. };
  12618. Scene.prototype.getParticlesDuration = function () {
  12619. return this._particlesDuration;
  12620. };
  12621. Scene.prototype.getSpritesDuration = function () {
  12622. return this._spritesDuration;
  12623. };
  12624. Scene.prototype.getAnimationRatio = function () {
  12625. return this._animationRatio;
  12626. };
  12627. Scene.prototype.getRenderId = function () {
  12628. return this._renderId;
  12629. };
  12630. Scene.prototype.incrementRenderId = function () {
  12631. this._renderId++;
  12632. };
  12633. Scene.prototype._updatePointerPosition = function (evt) {
  12634. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12635. this._pointerX = evt.clientX - canvasRect.left;
  12636. this._pointerY = evt.clientY - canvasRect.top;
  12637. if (this.cameraToUseForPointers) {
  12638. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12639. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12640. }
  12641. };
  12642. // Pointers handling
  12643. Scene.prototype.attachControl = function () {
  12644. var _this = this;
  12645. this._onPointerMove = function (evt) {
  12646. var canvas = _this._engine.getRenderingCanvas();
  12647. _this._updatePointerPosition(evt);
  12648. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12649. if (pickResult.hit) {
  12650. _this._meshUnderPointer = pickResult.pickedMesh;
  12651. _this.setPointerOverMesh(pickResult.pickedMesh);
  12652. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12653. canvas.style.cursor = "pointer";
  12654. }
  12655. else {
  12656. canvas.style.cursor = "";
  12657. }
  12658. }
  12659. else {
  12660. _this.setPointerOverMesh(null);
  12661. canvas.style.cursor = "";
  12662. _this._meshUnderPointer = null;
  12663. }
  12664. };
  12665. this._onPointerDown = function (evt) {
  12666. var predicate = null;
  12667. if (!_this.onPointerDown) {
  12668. predicate = function (mesh) {
  12669. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12670. };
  12671. }
  12672. _this._updatePointerPosition(evt);
  12673. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12674. if (pickResult.hit) {
  12675. if (pickResult.pickedMesh.actionManager) {
  12676. switch (evt.button) {
  12677. case 0:
  12678. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12679. break;
  12680. case 1:
  12681. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12682. break;
  12683. case 2:
  12684. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12685. break;
  12686. }
  12687. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12688. }
  12689. }
  12690. if (_this.onPointerDown) {
  12691. _this.onPointerDown(evt, pickResult);
  12692. }
  12693. };
  12694. this._onPointerUp = function (evt) {
  12695. var predicate = null;
  12696. if (!_this.onPointerUp) {
  12697. predicate = function (mesh) {
  12698. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12699. };
  12700. }
  12701. _this._updatePointerPosition(evt);
  12702. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12703. if (pickResult.hit) {
  12704. if (pickResult.pickedMesh.actionManager) {
  12705. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12706. }
  12707. }
  12708. if (_this.onPointerUp) {
  12709. _this.onPointerUp(evt, pickResult);
  12710. }
  12711. };
  12712. this._onKeyDown = function (evt) {
  12713. if (_this.actionManager) {
  12714. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12715. }
  12716. };
  12717. this._onKeyUp = function (evt) {
  12718. if (_this.actionManager) {
  12719. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12720. }
  12721. };
  12722. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12723. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12724. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12725. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12726. // Wheel
  12727. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12728. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12729. BABYLON.Tools.RegisterTopRootEvents([
  12730. { name: "keydown", handler: this._onKeyDown },
  12731. { name: "keyup", handler: this._onKeyUp }
  12732. ]);
  12733. };
  12734. Scene.prototype.detachControl = function () {
  12735. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12736. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12737. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12738. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12739. // Wheel
  12740. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12741. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12742. BABYLON.Tools.UnregisterTopRootEvents([
  12743. { name: "keydown", handler: this._onKeyDown },
  12744. { name: "keyup", handler: this._onKeyUp }
  12745. ]);
  12746. };
  12747. // Ready
  12748. Scene.prototype.isReady = function () {
  12749. if (this._pendingData.length > 0) {
  12750. return false;
  12751. }
  12752. var index;
  12753. for (index = 0; index < this._geometries.length; index++) {
  12754. var geometry = this._geometries[index];
  12755. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12756. return false;
  12757. }
  12758. }
  12759. for (index = 0; index < this.meshes.length; index++) {
  12760. var mesh = this.meshes[index];
  12761. if (!mesh.isReady()) {
  12762. return false;
  12763. }
  12764. var mat = mesh.material;
  12765. if (mat) {
  12766. if (!mat.isReady(mesh)) {
  12767. return false;
  12768. }
  12769. }
  12770. }
  12771. return true;
  12772. };
  12773. Scene.prototype.resetCachedMaterial = function () {
  12774. this._cachedMaterial = null;
  12775. };
  12776. Scene.prototype.registerBeforeRender = function (func) {
  12777. this._onBeforeRenderCallbacks.push(func);
  12778. };
  12779. Scene.prototype.unregisterBeforeRender = function (func) {
  12780. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12781. if (index > -1) {
  12782. this._onBeforeRenderCallbacks.splice(index, 1);
  12783. }
  12784. };
  12785. Scene.prototype.registerAfterRender = function (func) {
  12786. this._onAfterRenderCallbacks.push(func);
  12787. };
  12788. Scene.prototype.unregisterAfterRender = function (func) {
  12789. var index = this._onAfterRenderCallbacks.indexOf(func);
  12790. if (index > -1) {
  12791. this._onAfterRenderCallbacks.splice(index, 1);
  12792. }
  12793. };
  12794. Scene.prototype._addPendingData = function (data) {
  12795. this._pendingData.push(data);
  12796. };
  12797. Scene.prototype._removePendingData = function (data) {
  12798. var index = this._pendingData.indexOf(data);
  12799. if (index !== -1) {
  12800. this._pendingData.splice(index, 1);
  12801. }
  12802. };
  12803. Scene.prototype.getWaitingItemsCount = function () {
  12804. return this._pendingData.length;
  12805. };
  12806. /**
  12807. * Registers a function to be executed when the scene is ready.
  12808. * @param {Function} func - the function to be executed.
  12809. */
  12810. Scene.prototype.executeWhenReady = function (func) {
  12811. var _this = this;
  12812. this._onReadyCallbacks.push(func);
  12813. if (this._executeWhenReadyTimeoutId !== -1) {
  12814. return;
  12815. }
  12816. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12817. _this._checkIsReady();
  12818. }, 150);
  12819. };
  12820. Scene.prototype._checkIsReady = function () {
  12821. var _this = this;
  12822. if (this.isReady()) {
  12823. this._onReadyCallbacks.forEach(function (func) {
  12824. func();
  12825. });
  12826. this._onReadyCallbacks = [];
  12827. this._executeWhenReadyTimeoutId = -1;
  12828. return;
  12829. }
  12830. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12831. _this._checkIsReady();
  12832. }, 150);
  12833. };
  12834. // Animations
  12835. /**
  12836. * Will start the animation sequence of a given target
  12837. * @param target - the target
  12838. * @param {number} from - from which frame should animation start
  12839. * @param {number} to - till which frame should animation run.
  12840. * @param {boolean} [loop] - should the animation loop
  12841. * @param {number} [speedRatio] - the speed in which to run the animation
  12842. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12843. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12844. * @return {BABYLON.Animatable} the animatable object created for this animation
  12845. * @see BABYLON.Animatable
  12846. * @see http://doc.babylonjs.com/page.php?p=22081
  12847. */
  12848. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12849. if (speedRatio === undefined) {
  12850. speedRatio = 1.0;
  12851. }
  12852. this.stopAnimation(target);
  12853. if (!animatable) {
  12854. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12855. }
  12856. // Local animations
  12857. if (target.animations) {
  12858. animatable.appendAnimations(target, target.animations);
  12859. }
  12860. // Children animations
  12861. if (target.getAnimatables) {
  12862. var animatables = target.getAnimatables();
  12863. for (var index = 0; index < animatables.length; index++) {
  12864. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12865. }
  12866. }
  12867. return animatable;
  12868. };
  12869. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12870. if (speedRatio === undefined) {
  12871. speedRatio = 1.0;
  12872. }
  12873. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12874. return animatable;
  12875. };
  12876. Scene.prototype.getAnimatableByTarget = function (target) {
  12877. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12878. if (this._activeAnimatables[index].target === target) {
  12879. return this._activeAnimatables[index];
  12880. }
  12881. }
  12882. return null;
  12883. };
  12884. /**
  12885. * Will stop the animation of the given target
  12886. * @param target - the target
  12887. * @see beginAnimation
  12888. */
  12889. Scene.prototype.stopAnimation = function (target) {
  12890. var animatable = this.getAnimatableByTarget(target);
  12891. if (animatable) {
  12892. animatable.stop();
  12893. }
  12894. };
  12895. Scene.prototype._animate = function () {
  12896. if (!this.animationsEnabled) {
  12897. return;
  12898. }
  12899. if (!this._animationStartDate) {
  12900. this._animationStartDate = BABYLON.Tools.Now;
  12901. }
  12902. // Getting time
  12903. var now = BABYLON.Tools.Now;
  12904. var delay = now - this._animationStartDate;
  12905. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12906. this._activeAnimatables[index]._animate(delay);
  12907. }
  12908. };
  12909. // Matrix
  12910. Scene.prototype.getViewMatrix = function () {
  12911. return this._viewMatrix;
  12912. };
  12913. Scene.prototype.getProjectionMatrix = function () {
  12914. return this._projectionMatrix;
  12915. };
  12916. Scene.prototype.getTransformMatrix = function () {
  12917. return this._transformMatrix;
  12918. };
  12919. Scene.prototype.setTransformMatrix = function (view, projection) {
  12920. this._viewMatrix = view;
  12921. this._projectionMatrix = projection;
  12922. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12923. };
  12924. // Methods
  12925. Scene.prototype.addMesh = function (newMesh) {
  12926. newMesh.uniqueId = this._uniqueIdCounter++;
  12927. var position = this.meshes.push(newMesh);
  12928. //notify the collision coordinator
  12929. this.collisionCoordinator.onMeshAdded(newMesh);
  12930. if (this.onNewMeshAdded) {
  12931. this.onNewMeshAdded(newMesh, position, this);
  12932. }
  12933. };
  12934. Scene.prototype.removeMesh = function (toRemove) {
  12935. var index = this.meshes.indexOf(toRemove);
  12936. if (index !== -1) {
  12937. // Remove from the scene if mesh found
  12938. this.meshes.splice(index, 1);
  12939. }
  12940. //notify the collision coordinator
  12941. this.collisionCoordinator.onMeshRemoved(toRemove);
  12942. if (this.onMeshRemoved) {
  12943. this.onMeshRemoved(toRemove);
  12944. }
  12945. return index;
  12946. };
  12947. Scene.prototype.removeLight = function (toRemove) {
  12948. var index = this.lights.indexOf(toRemove);
  12949. if (index !== -1) {
  12950. // Remove from the scene if mesh found
  12951. this.lights.splice(index, 1);
  12952. }
  12953. if (this.onLightRemoved) {
  12954. this.onLightRemoved(toRemove);
  12955. }
  12956. return index;
  12957. };
  12958. Scene.prototype.removeCamera = function (toRemove) {
  12959. var index = this.cameras.indexOf(toRemove);
  12960. if (index !== -1) {
  12961. // Remove from the scene if mesh found
  12962. this.cameras.splice(index, 1);
  12963. }
  12964. // Remove from activeCameras
  12965. var index2 = this.activeCameras.indexOf(toRemove);
  12966. if (index2 !== -1) {
  12967. // Remove from the scene if mesh found
  12968. this.activeCameras.splice(index2, 1);
  12969. }
  12970. // Reset the activeCamera
  12971. if (this.activeCamera === toRemove) {
  12972. if (this.cameras.length > 0) {
  12973. this.activeCamera = this.cameras[0];
  12974. }
  12975. else {
  12976. this.activeCamera = null;
  12977. }
  12978. }
  12979. if (this.onCameraRemoved) {
  12980. this.onCameraRemoved(toRemove);
  12981. }
  12982. return index;
  12983. };
  12984. Scene.prototype.addLight = function (newLight) {
  12985. newLight.uniqueId = this._uniqueIdCounter++;
  12986. var position = this.lights.push(newLight);
  12987. if (this.onNewLightAdded) {
  12988. this.onNewLightAdded(newLight, position, this);
  12989. }
  12990. };
  12991. Scene.prototype.addCamera = function (newCamera) {
  12992. newCamera.uniqueId = this._uniqueIdCounter++;
  12993. var position = this.cameras.push(newCamera);
  12994. if (this.onNewCameraAdded) {
  12995. this.onNewCameraAdded(newCamera, position, this);
  12996. }
  12997. };
  12998. /**
  12999. * sets the active camera of the scene using its ID
  13000. * @param {string} id - the camera's ID
  13001. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13002. * @see activeCamera
  13003. */
  13004. Scene.prototype.setActiveCameraByID = function (id) {
  13005. var camera = this.getCameraByID(id);
  13006. if (camera) {
  13007. this.activeCamera = camera;
  13008. return camera;
  13009. }
  13010. return null;
  13011. };
  13012. /**
  13013. * sets the active camera of the scene using its name
  13014. * @param {string} name - the camera's name
  13015. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13016. * @see activeCamera
  13017. */
  13018. Scene.prototype.setActiveCameraByName = function (name) {
  13019. var camera = this.getCameraByName(name);
  13020. if (camera) {
  13021. this.activeCamera = camera;
  13022. return camera;
  13023. }
  13024. return null;
  13025. };
  13026. /**
  13027. * get a material using its id
  13028. * @param {string} the material's ID
  13029. * @return {BABYLON.Material|null} the material or null if none found.
  13030. */
  13031. Scene.prototype.getMaterialByID = function (id) {
  13032. for (var index = 0; index < this.materials.length; index++) {
  13033. if (this.materials[index].id === id) {
  13034. return this.materials[index];
  13035. }
  13036. }
  13037. return null;
  13038. };
  13039. /**
  13040. * get a material using its name
  13041. * @param {string} the material's name
  13042. * @return {BABYLON.Material|null} the material or null if none found.
  13043. */
  13044. Scene.prototype.getMaterialByName = function (name) {
  13045. for (var index = 0; index < this.materials.length; index++) {
  13046. if (this.materials[index].name === name) {
  13047. return this.materials[index];
  13048. }
  13049. }
  13050. return null;
  13051. };
  13052. Scene.prototype.getLensFlareSystemByName = function (name) {
  13053. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13054. if (this.lensFlareSystems[index].name === name) {
  13055. return this.lensFlareSystems[index];
  13056. }
  13057. }
  13058. return null;
  13059. };
  13060. Scene.prototype.getCameraByID = function (id) {
  13061. for (var index = 0; index < this.cameras.length; index++) {
  13062. if (this.cameras[index].id === id) {
  13063. return this.cameras[index];
  13064. }
  13065. }
  13066. return null;
  13067. };
  13068. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13069. for (var index = 0; index < this.cameras.length; index++) {
  13070. if (this.cameras[index].uniqueId === uniqueId) {
  13071. return this.cameras[index];
  13072. }
  13073. }
  13074. return null;
  13075. };
  13076. /**
  13077. * get a camera using its name
  13078. * @param {string} the camera's name
  13079. * @return {BABYLON.Camera|null} the camera or null if none found.
  13080. */
  13081. Scene.prototype.getCameraByName = function (name) {
  13082. for (var index = 0; index < this.cameras.length; index++) {
  13083. if (this.cameras[index].name === name) {
  13084. return this.cameras[index];
  13085. }
  13086. }
  13087. return null;
  13088. };
  13089. /**
  13090. * get a light node using its name
  13091. * @param {string} the light's name
  13092. * @return {BABYLON.Light|null} the light or null if none found.
  13093. */
  13094. Scene.prototype.getLightByName = function (name) {
  13095. for (var index = 0; index < this.lights.length; index++) {
  13096. if (this.lights[index].name === name) {
  13097. return this.lights[index];
  13098. }
  13099. }
  13100. return null;
  13101. };
  13102. /**
  13103. * get a light node using its ID
  13104. * @param {string} the light's id
  13105. * @return {BABYLON.Light|null} the light or null if none found.
  13106. */
  13107. Scene.prototype.getLightByID = function (id) {
  13108. for (var index = 0; index < this.lights.length; index++) {
  13109. if (this.lights[index].id === id) {
  13110. return this.lights[index];
  13111. }
  13112. }
  13113. return null;
  13114. };
  13115. /**
  13116. * get a light node using its scene-generated unique ID
  13117. * @param {number} the light's unique id
  13118. * @return {BABYLON.Light|null} the light or null if none found.
  13119. */
  13120. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13121. for (var index = 0; index < this.lights.length; index++) {
  13122. if (this.lights[index].uniqueId === uniqueId) {
  13123. return this.lights[index];
  13124. }
  13125. }
  13126. return null;
  13127. };
  13128. /**
  13129. * get a geometry using its ID
  13130. * @param {string} the geometry's id
  13131. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13132. */
  13133. Scene.prototype.getGeometryByID = function (id) {
  13134. for (var index = 0; index < this._geometries.length; index++) {
  13135. if (this._geometries[index].id === id) {
  13136. return this._geometries[index];
  13137. }
  13138. }
  13139. return null;
  13140. };
  13141. /**
  13142. * add a new geometry to this scene.
  13143. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13144. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13145. * @return {boolean} was the geometry added or not
  13146. */
  13147. Scene.prototype.pushGeometry = function (geometry, force) {
  13148. if (!force && this.getGeometryByID(geometry.id)) {
  13149. return false;
  13150. }
  13151. this._geometries.push(geometry);
  13152. //notify the collision coordinator
  13153. this.collisionCoordinator.onGeometryAdded(geometry);
  13154. if (this.onGeometryAdded) {
  13155. this.onGeometryAdded(geometry);
  13156. }
  13157. return true;
  13158. };
  13159. /**
  13160. * Removes an existing geometry
  13161. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13162. * @return {boolean} was the geometry removed or not
  13163. */
  13164. Scene.prototype.removeGeometry = function (geometry) {
  13165. var index = this._geometries.indexOf(geometry);
  13166. if (index > -1) {
  13167. this._geometries.splice(index, 1);
  13168. //notify the collision coordinator
  13169. this.collisionCoordinator.onGeometryDeleted(geometry);
  13170. if (this.onGeometryRemoved) {
  13171. this.onGeometryRemoved(geometry);
  13172. }
  13173. return true;
  13174. }
  13175. return false;
  13176. };
  13177. Scene.prototype.getGeometries = function () {
  13178. return this._geometries;
  13179. };
  13180. /**
  13181. * Get the first added mesh found of a given ID
  13182. * @param {string} id - the id to search for
  13183. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13184. */
  13185. Scene.prototype.getMeshByID = function (id) {
  13186. for (var index = 0; index < this.meshes.length; index++) {
  13187. if (this.meshes[index].id === id) {
  13188. return this.meshes[index];
  13189. }
  13190. }
  13191. return null;
  13192. };
  13193. /**
  13194. * Get a mesh with its auto-generated unique id
  13195. * @param {number} uniqueId - the unique id to search for
  13196. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13197. */
  13198. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13199. for (var index = 0; index < this.meshes.length; index++) {
  13200. if (this.meshes[index].uniqueId === uniqueId) {
  13201. return this.meshes[index];
  13202. }
  13203. }
  13204. return null;
  13205. };
  13206. /**
  13207. * Get a the last added mesh found of a given ID
  13208. * @param {string} id - the id to search for
  13209. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13210. */
  13211. Scene.prototype.getLastMeshByID = function (id) {
  13212. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13213. if (this.meshes[index].id === id) {
  13214. return this.meshes[index];
  13215. }
  13216. }
  13217. return null;
  13218. };
  13219. /**
  13220. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13221. * @param {string} id - the id to search for
  13222. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13223. */
  13224. Scene.prototype.getLastEntryByID = function (id) {
  13225. var index;
  13226. for (index = this.meshes.length - 1; index >= 0; index--) {
  13227. if (this.meshes[index].id === id) {
  13228. return this.meshes[index];
  13229. }
  13230. }
  13231. for (index = this.cameras.length - 1; index >= 0; index--) {
  13232. if (this.cameras[index].id === id) {
  13233. return this.cameras[index];
  13234. }
  13235. }
  13236. for (index = this.lights.length - 1; index >= 0; index--) {
  13237. if (this.lights[index].id === id) {
  13238. return this.lights[index];
  13239. }
  13240. }
  13241. return null;
  13242. };
  13243. Scene.prototype.getNodeByID = function (id) {
  13244. var mesh = this.getMeshByID(id);
  13245. if (mesh) {
  13246. return mesh;
  13247. }
  13248. var light = this.getLightByID(id);
  13249. if (light) {
  13250. return light;
  13251. }
  13252. return this.getCameraByID(id);
  13253. };
  13254. Scene.prototype.getNodeByName = function (name) {
  13255. var mesh = this.getMeshByName(name);
  13256. if (mesh) {
  13257. return mesh;
  13258. }
  13259. var light = this.getLightByName(name);
  13260. if (light) {
  13261. return light;
  13262. }
  13263. return this.getCameraByName(name);
  13264. };
  13265. Scene.prototype.getMeshByName = function (name) {
  13266. for (var index = 0; index < this.meshes.length; index++) {
  13267. if (this.meshes[index].name === name) {
  13268. return this.meshes[index];
  13269. }
  13270. }
  13271. return null;
  13272. };
  13273. Scene.prototype.getSoundByName = function (name) {
  13274. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13275. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13276. return this.mainSoundTrack.soundCollection[index];
  13277. }
  13278. }
  13279. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13280. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13281. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13282. return this.soundTracks[sdIndex].soundCollection[index];
  13283. }
  13284. }
  13285. }
  13286. return null;
  13287. };
  13288. Scene.prototype.getLastSkeletonByID = function (id) {
  13289. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13290. if (this.skeletons[index].id === id) {
  13291. return this.skeletons[index];
  13292. }
  13293. }
  13294. return null;
  13295. };
  13296. Scene.prototype.getSkeletonById = function (id) {
  13297. for (var index = 0; index < this.skeletons.length; index++) {
  13298. if (this.skeletons[index].id === id) {
  13299. return this.skeletons[index];
  13300. }
  13301. }
  13302. return null;
  13303. };
  13304. Scene.prototype.getSkeletonByName = function (name) {
  13305. for (var index = 0; index < this.skeletons.length; index++) {
  13306. if (this.skeletons[index].name === name) {
  13307. return this.skeletons[index];
  13308. }
  13309. }
  13310. return null;
  13311. };
  13312. Scene.prototype.isActiveMesh = function (mesh) {
  13313. return (this._activeMeshes.indexOf(mesh) !== -1);
  13314. };
  13315. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13316. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13317. var material = subMesh.getMaterial();
  13318. if (mesh.showSubMeshesBoundingBox) {
  13319. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13320. }
  13321. if (material) {
  13322. // Render targets
  13323. if (material.getRenderTargetTextures) {
  13324. if (this._processedMaterials.indexOf(material) === -1) {
  13325. this._processedMaterials.push(material);
  13326. this._renderTargets.concat(material.getRenderTargetTextures());
  13327. }
  13328. }
  13329. // Dispatch
  13330. this._activeIndices += subMesh.indexCount;
  13331. this._renderingManager.dispatch(subMesh);
  13332. }
  13333. }
  13334. };
  13335. Scene.prototype._evaluateActiveMeshes = function () {
  13336. this.activeCamera._activeMeshes.reset();
  13337. this._activeMeshes.reset();
  13338. this._renderingManager.reset();
  13339. this._processedMaterials.reset();
  13340. this._activeParticleSystems.reset();
  13341. this._activeSkeletons.reset();
  13342. this._softwareSkinnedMeshes.reset();
  13343. this._boundingBoxRenderer.reset();
  13344. this._edgesRenderers.reset();
  13345. if (!this._frustumPlanes) {
  13346. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13347. }
  13348. else {
  13349. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13350. }
  13351. // Meshes
  13352. var meshes;
  13353. var len;
  13354. if (this._selectionOctree) {
  13355. var selection = this._selectionOctree.select(this._frustumPlanes);
  13356. meshes = selection.data;
  13357. len = selection.length;
  13358. }
  13359. else {
  13360. len = this.meshes.length;
  13361. meshes = this.meshes;
  13362. }
  13363. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13364. var mesh = meshes[meshIndex];
  13365. if (mesh.isBlocked) {
  13366. continue;
  13367. }
  13368. this._totalVertices += mesh.getTotalVertices();
  13369. if (!mesh.isReady() || !mesh.isEnabled()) {
  13370. continue;
  13371. }
  13372. mesh.computeWorldMatrix();
  13373. // Intersections
  13374. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13375. this._meshesForIntersections.pushNoDuplicate(mesh);
  13376. }
  13377. // Switch to current LOD
  13378. var meshLOD = mesh.getLOD(this.activeCamera);
  13379. if (!meshLOD) {
  13380. continue;
  13381. }
  13382. mesh._preActivate();
  13383. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13384. this._activeMeshes.push(mesh);
  13385. this.activeCamera._activeMeshes.push(mesh);
  13386. mesh._activate(this._renderId);
  13387. this._activeMesh(meshLOD);
  13388. }
  13389. }
  13390. // Particle systems
  13391. var beforeParticlesDate = BABYLON.Tools.Now;
  13392. if (this.particlesEnabled) {
  13393. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13394. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13395. var particleSystem = this.particleSystems[particleIndex];
  13396. if (!particleSystem.isStarted()) {
  13397. continue;
  13398. }
  13399. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13400. this._activeParticleSystems.push(particleSystem);
  13401. particleSystem.animate();
  13402. }
  13403. }
  13404. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13405. }
  13406. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13407. };
  13408. Scene.prototype._activeMesh = function (mesh) {
  13409. if (mesh.skeleton && this.skeletonsEnabled) {
  13410. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13411. if (!mesh.computeBonesUsingShaders) {
  13412. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13413. }
  13414. }
  13415. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13416. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13417. }
  13418. if (mesh._edgesRenderer) {
  13419. this._edgesRenderers.push(mesh._edgesRenderer);
  13420. }
  13421. if (mesh && mesh.subMeshes) {
  13422. // Submeshes Octrees
  13423. var len;
  13424. var subMeshes;
  13425. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13426. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13427. len = intersections.length;
  13428. subMeshes = intersections.data;
  13429. }
  13430. else {
  13431. subMeshes = mesh.subMeshes;
  13432. len = subMeshes.length;
  13433. }
  13434. for (var subIndex = 0; subIndex < len; subIndex++) {
  13435. var subMesh = subMeshes[subIndex];
  13436. this._evaluateSubMesh(subMesh, mesh);
  13437. }
  13438. }
  13439. };
  13440. Scene.prototype.updateTransformMatrix = function (force) {
  13441. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13442. };
  13443. Scene.prototype._renderForCamera = function (camera) {
  13444. var engine = this._engine;
  13445. this.activeCamera = camera;
  13446. if (!this.activeCamera)
  13447. throw new Error("Active camera not set");
  13448. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13449. // Viewport
  13450. engine.setViewport(this.activeCamera.viewport);
  13451. // Camera
  13452. this.resetCachedMaterial();
  13453. this._renderId++;
  13454. this.updateTransformMatrix();
  13455. if (this.beforeCameraRender) {
  13456. this.beforeCameraRender(this.activeCamera);
  13457. }
  13458. // Meshes
  13459. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13460. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13461. this._evaluateActiveMeshes();
  13462. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13463. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13464. // Skeletons
  13465. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13466. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13467. skeleton.prepare();
  13468. }
  13469. // Software skinning
  13470. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13471. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13472. mesh.applySkeleton(mesh.skeleton);
  13473. }
  13474. // Render targets
  13475. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13476. if (this.renderTargetsEnabled) {
  13477. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13478. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13479. var renderTarget = this._renderTargets.data[renderIndex];
  13480. if (renderTarget._shouldRender()) {
  13481. this._renderId++;
  13482. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13483. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13484. }
  13485. }
  13486. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13487. this._renderId++;
  13488. }
  13489. if (this._renderTargets.length > 0) {
  13490. engine.restoreDefaultFramebuffer();
  13491. }
  13492. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13493. // Prepare Frame
  13494. this.postProcessManager._prepareFrame();
  13495. var beforeRenderDate = BABYLON.Tools.Now;
  13496. // Backgrounds
  13497. var layerIndex;
  13498. if (this.layers.length) {
  13499. engine.setDepthBuffer(false);
  13500. var layer;
  13501. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13502. layer = this.layers[layerIndex];
  13503. if (layer.isBackground) {
  13504. layer.render();
  13505. }
  13506. }
  13507. engine.setDepthBuffer(true);
  13508. }
  13509. // Render
  13510. BABYLON.Tools.StartPerformanceCounter("Main render");
  13511. this._renderingManager.render(null, null, true, true);
  13512. BABYLON.Tools.EndPerformanceCounter("Main render");
  13513. // Bounding boxes
  13514. this._boundingBoxRenderer.render();
  13515. // Edges
  13516. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13517. this._edgesRenderers.data[edgesRendererIndex].render();
  13518. }
  13519. // Lens flares
  13520. if (this.lensFlaresEnabled) {
  13521. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13522. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13523. this.lensFlareSystems[lensFlareSystemIndex].render();
  13524. }
  13525. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13526. }
  13527. // Foregrounds
  13528. if (this.layers.length) {
  13529. engine.setDepthBuffer(false);
  13530. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13531. layer = this.layers[layerIndex];
  13532. if (!layer.isBackground) {
  13533. layer.render();
  13534. }
  13535. }
  13536. engine.setDepthBuffer(true);
  13537. }
  13538. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13539. // Finalize frame
  13540. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13541. // Update camera
  13542. this.activeCamera._updateFromScene();
  13543. // Reset some special arrays
  13544. this._renderTargets.reset();
  13545. if (this.afterCameraRender) {
  13546. this.afterCameraRender(this.activeCamera);
  13547. }
  13548. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13549. };
  13550. Scene.prototype._processSubCameras = function (camera) {
  13551. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13552. this._renderForCamera(camera);
  13553. return;
  13554. }
  13555. // rig cameras
  13556. for (var index = 0; index < camera._rigCameras.length; index++) {
  13557. this._renderForCamera(camera._rigCameras[index]);
  13558. }
  13559. this.activeCamera = camera;
  13560. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13561. // Update camera
  13562. this.activeCamera._updateFromScene();
  13563. };
  13564. Scene.prototype._checkIntersections = function () {
  13565. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13566. var sourceMesh = this._meshesForIntersections.data[index];
  13567. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13568. var action = sourceMesh.actionManager.actions[actionIndex];
  13569. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13570. var parameters = action.getTriggerParameter();
  13571. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13572. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13573. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13574. if (areIntersecting && currentIntersectionInProgress === -1) {
  13575. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13576. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13577. sourceMesh._intersectionsInProgress.push(otherMesh);
  13578. }
  13579. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13580. sourceMesh._intersectionsInProgress.push(otherMesh);
  13581. }
  13582. }
  13583. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13584. //They intersected, and now they don't.
  13585. //is this trigger an exit trigger? execute an event.
  13586. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13587. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13588. }
  13589. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13590. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13591. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13592. }
  13593. }
  13594. }
  13595. }
  13596. }
  13597. };
  13598. Scene.prototype.render = function () {
  13599. var startDate = BABYLON.Tools.Now;
  13600. this._particlesDuration = 0;
  13601. this._spritesDuration = 0;
  13602. this._activeParticles = 0;
  13603. this._renderDuration = 0;
  13604. this._renderTargetsDuration = 0;
  13605. this._evaluateActiveMeshesDuration = 0;
  13606. this._totalVertices = 0;
  13607. this._activeIndices = 0;
  13608. this._activeBones = 0;
  13609. this.getEngine().resetDrawCalls();
  13610. this._meshesForIntersections.reset();
  13611. this.resetCachedMaterial();
  13612. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13613. // Actions
  13614. if (this.actionManager) {
  13615. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13616. }
  13617. //Simplification Queue
  13618. if (!this.simplificationQueue.running) {
  13619. this.simplificationQueue.executeNext();
  13620. }
  13621. // Before render
  13622. if (this.beforeRender) {
  13623. this.beforeRender();
  13624. }
  13625. var callbackIndex;
  13626. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13627. this._onBeforeRenderCallbacks[callbackIndex]();
  13628. }
  13629. // Animations
  13630. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13631. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13632. this._animate();
  13633. // Physics
  13634. if (this._physicsEngine) {
  13635. BABYLON.Tools.StartPerformanceCounter("Physics");
  13636. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13637. BABYLON.Tools.EndPerformanceCounter("Physics");
  13638. }
  13639. // Customs render targets
  13640. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13641. var engine = this.getEngine();
  13642. var currentActiveCamera = this.activeCamera;
  13643. if (this.renderTargetsEnabled) {
  13644. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13645. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13646. var renderTarget = this.customRenderTargets[customIndex];
  13647. if (renderTarget._shouldRender()) {
  13648. this._renderId++;
  13649. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13650. if (!this.activeCamera)
  13651. throw new Error("Active camera not set");
  13652. // Viewport
  13653. engine.setViewport(this.activeCamera.viewport);
  13654. // Camera
  13655. this.updateTransformMatrix();
  13656. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13657. }
  13658. }
  13659. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13660. this._renderId++;
  13661. }
  13662. if (this.customRenderTargets.length > 0) {
  13663. engine.restoreDefaultFramebuffer();
  13664. }
  13665. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13666. this.activeCamera = currentActiveCamera;
  13667. // Procedural textures
  13668. if (this.proceduralTexturesEnabled) {
  13669. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13670. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13671. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13672. if (proceduralTexture._shouldRender()) {
  13673. proceduralTexture.render();
  13674. }
  13675. }
  13676. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13677. }
  13678. // Clear
  13679. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13680. // Shadows
  13681. if (this.shadowsEnabled) {
  13682. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13683. var light = this.lights[lightIndex];
  13684. var shadowGenerator = light.getShadowGenerator();
  13685. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13686. this._renderTargets.push(shadowGenerator.getShadowMap());
  13687. }
  13688. }
  13689. }
  13690. // Depth renderer
  13691. if (this._depthRenderer) {
  13692. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13693. }
  13694. // RenderPipeline
  13695. this.postProcessRenderPipelineManager.update();
  13696. // Multi-cameras?
  13697. if (this.activeCameras.length > 0) {
  13698. var currentRenderId = this._renderId;
  13699. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13700. this._renderId = currentRenderId;
  13701. this._processSubCameras(this.activeCameras[cameraIndex]);
  13702. }
  13703. }
  13704. else {
  13705. if (!this.activeCamera) {
  13706. throw new Error("No camera defined");
  13707. }
  13708. this._processSubCameras(this.activeCamera);
  13709. }
  13710. // Intersection checks
  13711. this._checkIntersections();
  13712. // Update the audio listener attached to the camera
  13713. this._updateAudioParameters();
  13714. // After render
  13715. if (this.afterRender) {
  13716. this.afterRender();
  13717. }
  13718. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13719. this._onAfterRenderCallbacks[callbackIndex]();
  13720. }
  13721. // Cleaning
  13722. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13723. this._toBeDisposed.data[index].dispose();
  13724. this._toBeDisposed[index] = null;
  13725. }
  13726. this._toBeDisposed.reset();
  13727. if (this.dumpNextRenderTargets) {
  13728. this.dumpNextRenderTargets = false;
  13729. }
  13730. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13731. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13732. };
  13733. Scene.prototype._updateAudioParameters = function () {
  13734. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13735. return;
  13736. }
  13737. var listeningCamera;
  13738. var audioEngine = BABYLON.Engine.audioEngine;
  13739. if (this.activeCameras.length > 0) {
  13740. listeningCamera = this.activeCameras[0];
  13741. }
  13742. else {
  13743. listeningCamera = this.activeCamera;
  13744. }
  13745. if (listeningCamera && audioEngine.canUseWebAudio) {
  13746. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13747. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13748. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13749. cameraDirection.normalize();
  13750. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13751. var i;
  13752. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13753. var sound = this.mainSoundTrack.soundCollection[i];
  13754. if (sound.useCustomAttenuation) {
  13755. sound.updateDistanceFromListener();
  13756. }
  13757. }
  13758. for (i = 0; i < this.soundTracks.length; i++) {
  13759. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13760. sound = this.soundTracks[i].soundCollection[j];
  13761. if (sound.useCustomAttenuation) {
  13762. sound.updateDistanceFromListener();
  13763. }
  13764. }
  13765. }
  13766. }
  13767. };
  13768. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13769. // Audio
  13770. get: function () {
  13771. return this._audioEnabled;
  13772. },
  13773. set: function (value) {
  13774. this._audioEnabled = value;
  13775. if (this._audioEnabled) {
  13776. this._enableAudio();
  13777. }
  13778. else {
  13779. this._disableAudio();
  13780. }
  13781. },
  13782. enumerable: true,
  13783. configurable: true
  13784. });
  13785. Scene.prototype._disableAudio = function () {
  13786. var i;
  13787. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13788. this.mainSoundTrack.soundCollection[i].pause();
  13789. }
  13790. for (i = 0; i < this.soundTracks.length; i++) {
  13791. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13792. this.soundTracks[i].soundCollection[j].pause();
  13793. }
  13794. }
  13795. };
  13796. Scene.prototype._enableAudio = function () {
  13797. var i;
  13798. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13799. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13800. this.mainSoundTrack.soundCollection[i].play();
  13801. }
  13802. }
  13803. for (i = 0; i < this.soundTracks.length; i++) {
  13804. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13805. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13806. this.soundTracks[i].soundCollection[j].play();
  13807. }
  13808. }
  13809. }
  13810. };
  13811. Object.defineProperty(Scene.prototype, "headphone", {
  13812. get: function () {
  13813. return this._headphone;
  13814. },
  13815. set: function (value) {
  13816. this._headphone = value;
  13817. if (this._headphone) {
  13818. this._switchAudioModeForHeadphones();
  13819. }
  13820. else {
  13821. this._switchAudioModeForNormalSpeakers();
  13822. }
  13823. },
  13824. enumerable: true,
  13825. configurable: true
  13826. });
  13827. Scene.prototype._switchAudioModeForHeadphones = function () {
  13828. this.mainSoundTrack.switchPanningModelToHRTF();
  13829. for (var i = 0; i < this.soundTracks.length; i++) {
  13830. this.soundTracks[i].switchPanningModelToHRTF();
  13831. }
  13832. };
  13833. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13834. this.mainSoundTrack.switchPanningModelToEqualPower();
  13835. for (var i = 0; i < this.soundTracks.length; i++) {
  13836. this.soundTracks[i].switchPanningModelToEqualPower();
  13837. }
  13838. };
  13839. Scene.prototype.enableDepthRenderer = function () {
  13840. if (this._depthRenderer) {
  13841. return this._depthRenderer;
  13842. }
  13843. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13844. return this._depthRenderer;
  13845. };
  13846. Scene.prototype.disableDepthRenderer = function () {
  13847. if (!this._depthRenderer) {
  13848. return;
  13849. }
  13850. this._depthRenderer.dispose();
  13851. this._depthRenderer = null;
  13852. };
  13853. Scene.prototype.dispose = function () {
  13854. this.beforeRender = null;
  13855. this.afterRender = null;
  13856. this.skeletons = [];
  13857. this._boundingBoxRenderer.dispose();
  13858. if (this._depthRenderer) {
  13859. this._depthRenderer.dispose();
  13860. }
  13861. // Debug layer
  13862. this.debugLayer.hide();
  13863. // Events
  13864. if (this.onDispose) {
  13865. this.onDispose();
  13866. }
  13867. this._onBeforeRenderCallbacks = [];
  13868. this._onAfterRenderCallbacks = [];
  13869. this.detachControl();
  13870. // Release sounds & sounds tracks
  13871. this.disposeSounds();
  13872. // Detach cameras
  13873. var canvas = this._engine.getRenderingCanvas();
  13874. var index;
  13875. for (index = 0; index < this.cameras.length; index++) {
  13876. this.cameras[index].detachControl(canvas);
  13877. }
  13878. // Release lights
  13879. while (this.lights.length) {
  13880. this.lights[0].dispose();
  13881. }
  13882. // Release meshes
  13883. while (this.meshes.length) {
  13884. this.meshes[0].dispose(true);
  13885. }
  13886. // Release cameras
  13887. while (this.cameras.length) {
  13888. this.cameras[0].dispose();
  13889. }
  13890. // Release materials
  13891. while (this.materials.length) {
  13892. this.materials[0].dispose();
  13893. }
  13894. // Release particles
  13895. while (this.particleSystems.length) {
  13896. this.particleSystems[0].dispose();
  13897. }
  13898. // Release sprites
  13899. while (this.spriteManagers.length) {
  13900. this.spriteManagers[0].dispose();
  13901. }
  13902. // Release layers
  13903. while (this.layers.length) {
  13904. this.layers[0].dispose();
  13905. }
  13906. // Release textures
  13907. while (this.textures.length) {
  13908. this.textures[0].dispose();
  13909. }
  13910. // Post-processes
  13911. this.postProcessManager.dispose();
  13912. // Physics
  13913. if (this._physicsEngine) {
  13914. this.disablePhysicsEngine();
  13915. }
  13916. // Remove from engine
  13917. index = this._engine.scenes.indexOf(this);
  13918. if (index > -1) {
  13919. this._engine.scenes.splice(index, 1);
  13920. }
  13921. this._engine.wipeCaches();
  13922. };
  13923. // Release sounds & sounds tracks
  13924. Scene.prototype.disposeSounds = function () {
  13925. this.mainSoundTrack.dispose();
  13926. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13927. this.soundTracks[scIndex].dispose();
  13928. }
  13929. };
  13930. // Octrees
  13931. Scene.prototype.getWorldExtends = function () {
  13932. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13933. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13934. for (var index = 0; index < this.meshes.length; index++) {
  13935. var mesh = this.meshes[index];
  13936. mesh.computeWorldMatrix(true);
  13937. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13938. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13939. BABYLON.Tools.CheckExtends(minBox, min, max);
  13940. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13941. }
  13942. return {
  13943. min: min,
  13944. max: max
  13945. };
  13946. };
  13947. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13948. if (maxCapacity === void 0) { maxCapacity = 64; }
  13949. if (maxDepth === void 0) { maxDepth = 2; }
  13950. if (!this._selectionOctree) {
  13951. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13952. }
  13953. var worldExtends = this.getWorldExtends();
  13954. // Update octree
  13955. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13956. return this._selectionOctree;
  13957. };
  13958. // Picking
  13959. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13960. var engine = this._engine;
  13961. if (!camera) {
  13962. if (!this.activeCamera)
  13963. throw new Error("Active camera not set");
  13964. camera = this.activeCamera;
  13965. }
  13966. var cameraViewport = camera.viewport;
  13967. var viewport = cameraViewport.toGlobal(engine);
  13968. // Moving coordinates to local viewport world
  13969. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13970. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13971. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13972. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13973. };
  13974. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13975. var pickingInfo = null;
  13976. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13977. var mesh = this.meshes[meshIndex];
  13978. if (predicate) {
  13979. if (!predicate(mesh)) {
  13980. continue;
  13981. }
  13982. }
  13983. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13984. continue;
  13985. }
  13986. var world = mesh.getWorldMatrix();
  13987. var ray = rayFunction(world);
  13988. var result = mesh.intersects(ray, fastCheck);
  13989. if (!result || !result.hit)
  13990. continue;
  13991. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13992. continue;
  13993. pickingInfo = result;
  13994. if (fastCheck) {
  13995. break;
  13996. }
  13997. }
  13998. return pickingInfo || new BABYLON.PickingInfo();
  13999. };
  14000. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14001. var _this = this;
  14002. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14003. /// <param name="x">X position on screen</param>
  14004. /// <param name="y">Y position on screen</param>
  14005. /// <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>
  14006. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14007. /// <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>
  14008. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14009. };
  14010. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14011. var _this = this;
  14012. return this._internalPick(function (world) {
  14013. if (!_this._pickWithRayInverseMatrix) {
  14014. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14015. }
  14016. world.invertToRef(_this._pickWithRayInverseMatrix);
  14017. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14018. }, predicate, fastCheck);
  14019. };
  14020. Scene.prototype.setPointerOverMesh = function (mesh) {
  14021. if (this._pointerOverMesh === mesh) {
  14022. return;
  14023. }
  14024. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14025. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14026. }
  14027. this._pointerOverMesh = mesh;
  14028. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14029. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14030. }
  14031. };
  14032. Scene.prototype.getPointerOverMesh = function () {
  14033. return this._pointerOverMesh;
  14034. };
  14035. // Physics
  14036. Scene.prototype.getPhysicsEngine = function () {
  14037. return this._physicsEngine;
  14038. };
  14039. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14040. if (this._physicsEngine) {
  14041. return true;
  14042. }
  14043. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14044. if (!this._physicsEngine.isSupported()) {
  14045. this._physicsEngine = null;
  14046. return false;
  14047. }
  14048. this._physicsEngine._initialize(gravity);
  14049. return true;
  14050. };
  14051. Scene.prototype.disablePhysicsEngine = function () {
  14052. if (!this._physicsEngine) {
  14053. return;
  14054. }
  14055. this._physicsEngine.dispose();
  14056. this._physicsEngine = undefined;
  14057. };
  14058. Scene.prototype.isPhysicsEnabled = function () {
  14059. return this._physicsEngine !== undefined;
  14060. };
  14061. Scene.prototype.setGravity = function (gravity) {
  14062. if (!this._physicsEngine) {
  14063. return;
  14064. }
  14065. this._physicsEngine._setGravity(gravity);
  14066. };
  14067. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14068. if (parts.parts) {
  14069. options = parts;
  14070. parts = parts.parts;
  14071. }
  14072. if (!this._physicsEngine) {
  14073. return null;
  14074. }
  14075. for (var index = 0; index < parts.length; index++) {
  14076. var mesh = parts[index].mesh;
  14077. mesh._physicImpostor = parts[index].impostor;
  14078. mesh._physicsMass = options.mass / parts.length;
  14079. mesh._physicsFriction = options.friction;
  14080. mesh._physicRestitution = options.restitution;
  14081. }
  14082. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14083. };
  14084. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14085. for (var index = 0; index < compound.parts.length; index++) {
  14086. var mesh = compound.parts[index].mesh;
  14087. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14088. this._physicsEngine._unregisterMesh(mesh);
  14089. }
  14090. };
  14091. // Misc.
  14092. Scene.prototype.createDefaultCameraOrLight = function () {
  14093. // Light
  14094. if (this.lights.length === 0) {
  14095. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14096. }
  14097. // Camera
  14098. if (!this.activeCamera) {
  14099. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14100. // Compute position
  14101. var worldExtends = this.getWorldExtends();
  14102. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14103. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14104. camera.setTarget(worldCenter);
  14105. this.activeCamera = camera;
  14106. }
  14107. };
  14108. // Tags
  14109. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14110. if (tagsQuery === undefined) {
  14111. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14112. return list;
  14113. }
  14114. var listByTags = [];
  14115. forEach = forEach || (function (item) { return; });
  14116. for (var i in list) {
  14117. var item = list[i];
  14118. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14119. listByTags.push(item);
  14120. forEach(item);
  14121. }
  14122. }
  14123. return listByTags;
  14124. };
  14125. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14126. return this._getByTags(this.meshes, tagsQuery, forEach);
  14127. };
  14128. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14129. return this._getByTags(this.cameras, tagsQuery, forEach);
  14130. };
  14131. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14132. return this._getByTags(this.lights, tagsQuery, forEach);
  14133. };
  14134. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14135. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14136. };
  14137. // Statics
  14138. Scene._FOGMODE_NONE = 0;
  14139. Scene._FOGMODE_EXP = 1;
  14140. Scene._FOGMODE_EXP2 = 2;
  14141. Scene._FOGMODE_LINEAR = 3;
  14142. Scene.MinDeltaTime = 1.0;
  14143. Scene.MaxDeltaTime = 1000.0;
  14144. return Scene;
  14145. })();
  14146. BABYLON.Scene = Scene;
  14147. })(BABYLON || (BABYLON = {}));
  14148. var BABYLON;
  14149. (function (BABYLON) {
  14150. var VertexBuffer = (function () {
  14151. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14152. if (engine instanceof BABYLON.Mesh) {
  14153. this._engine = engine.getScene().getEngine();
  14154. }
  14155. else {
  14156. this._engine = engine;
  14157. }
  14158. this._updatable = updatable;
  14159. this._data = data;
  14160. if (!postponeInternalCreation) {
  14161. this.create();
  14162. }
  14163. this._kind = kind;
  14164. if (stride) {
  14165. this._strideSize = stride;
  14166. return;
  14167. }
  14168. // Deduce stride from kind
  14169. switch (kind) {
  14170. case VertexBuffer.PositionKind:
  14171. this._strideSize = 3;
  14172. break;
  14173. case VertexBuffer.NormalKind:
  14174. this._strideSize = 3;
  14175. break;
  14176. case VertexBuffer.UVKind:
  14177. case VertexBuffer.UV2Kind:
  14178. case VertexBuffer.UV3Kind:
  14179. case VertexBuffer.UV4Kind:
  14180. case VertexBuffer.UV5Kind:
  14181. case VertexBuffer.UV6Kind:
  14182. this._strideSize = 2;
  14183. break;
  14184. case VertexBuffer.ColorKind:
  14185. this._strideSize = 4;
  14186. break;
  14187. case VertexBuffer.MatricesIndicesKind:
  14188. this._strideSize = 4;
  14189. break;
  14190. case VertexBuffer.MatricesWeightsKind:
  14191. this._strideSize = 4;
  14192. break;
  14193. }
  14194. }
  14195. // Properties
  14196. VertexBuffer.prototype.isUpdatable = function () {
  14197. return this._updatable;
  14198. };
  14199. VertexBuffer.prototype.getData = function () {
  14200. return this._data;
  14201. };
  14202. VertexBuffer.prototype.getBuffer = function () {
  14203. return this._buffer;
  14204. };
  14205. VertexBuffer.prototype.getStrideSize = function () {
  14206. return this._strideSize;
  14207. };
  14208. // Methods
  14209. VertexBuffer.prototype.create = function (data) {
  14210. if (!data && this._buffer) {
  14211. return; // nothing to do
  14212. }
  14213. data = data || this._data;
  14214. if (!this._buffer) {
  14215. if (this._updatable) {
  14216. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14217. }
  14218. else {
  14219. this._buffer = this._engine.createVertexBuffer(data);
  14220. }
  14221. }
  14222. if (this._updatable) {
  14223. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14224. this._data = data;
  14225. }
  14226. };
  14227. VertexBuffer.prototype.update = function (data) {
  14228. this.create(data);
  14229. };
  14230. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14231. if (!this._buffer) {
  14232. return;
  14233. }
  14234. if (this._updatable) {
  14235. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14236. this._data = null;
  14237. }
  14238. };
  14239. VertexBuffer.prototype.dispose = function () {
  14240. if (!this._buffer) {
  14241. return;
  14242. }
  14243. if (this._engine._releaseBuffer(this._buffer)) {
  14244. this._buffer = null;
  14245. }
  14246. };
  14247. Object.defineProperty(VertexBuffer, "PositionKind", {
  14248. get: function () {
  14249. return VertexBuffer._PositionKind;
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. Object.defineProperty(VertexBuffer, "NormalKind", {
  14255. get: function () {
  14256. return VertexBuffer._NormalKind;
  14257. },
  14258. enumerable: true,
  14259. configurable: true
  14260. });
  14261. Object.defineProperty(VertexBuffer, "UVKind", {
  14262. get: function () {
  14263. return VertexBuffer._UVKind;
  14264. },
  14265. enumerable: true,
  14266. configurable: true
  14267. });
  14268. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14269. get: function () {
  14270. return VertexBuffer._UV2Kind;
  14271. },
  14272. enumerable: true,
  14273. configurable: true
  14274. });
  14275. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14276. get: function () {
  14277. return VertexBuffer._UV3Kind;
  14278. },
  14279. enumerable: true,
  14280. configurable: true
  14281. });
  14282. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14283. get: function () {
  14284. return VertexBuffer._UV4Kind;
  14285. },
  14286. enumerable: true,
  14287. configurable: true
  14288. });
  14289. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14290. get: function () {
  14291. return VertexBuffer._UV5Kind;
  14292. },
  14293. enumerable: true,
  14294. configurable: true
  14295. });
  14296. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14297. get: function () {
  14298. return VertexBuffer._UV6Kind;
  14299. },
  14300. enumerable: true,
  14301. configurable: true
  14302. });
  14303. Object.defineProperty(VertexBuffer, "ColorKind", {
  14304. get: function () {
  14305. return VertexBuffer._ColorKind;
  14306. },
  14307. enumerable: true,
  14308. configurable: true
  14309. });
  14310. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14311. get: function () {
  14312. return VertexBuffer._MatricesIndicesKind;
  14313. },
  14314. enumerable: true,
  14315. configurable: true
  14316. });
  14317. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14318. get: function () {
  14319. return VertexBuffer._MatricesWeightsKind;
  14320. },
  14321. enumerable: true,
  14322. configurable: true
  14323. });
  14324. // Enums
  14325. VertexBuffer._PositionKind = "position";
  14326. VertexBuffer._NormalKind = "normal";
  14327. VertexBuffer._UVKind = "uv";
  14328. VertexBuffer._UV2Kind = "uv2";
  14329. VertexBuffer._UV3Kind = "uv3";
  14330. VertexBuffer._UV4Kind = "uv4";
  14331. VertexBuffer._UV5Kind = "uv5";
  14332. VertexBuffer._UV6Kind = "uv6";
  14333. VertexBuffer._ColorKind = "color";
  14334. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14335. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14336. return VertexBuffer;
  14337. })();
  14338. BABYLON.VertexBuffer = VertexBuffer;
  14339. })(BABYLON || (BABYLON = {}));
  14340. var BABYLON;
  14341. (function (BABYLON) {
  14342. /**
  14343. * Creates an instance based on a source mesh.
  14344. */
  14345. var InstancedMesh = (function (_super) {
  14346. __extends(InstancedMesh, _super);
  14347. function InstancedMesh(name, source) {
  14348. _super.call(this, name, source.getScene());
  14349. source.instances.push(this);
  14350. this._sourceMesh = source;
  14351. this.position.copyFrom(source.position);
  14352. this.rotation.copyFrom(source.rotation);
  14353. this.scaling.copyFrom(source.scaling);
  14354. if (source.rotationQuaternion) {
  14355. this.rotationQuaternion = source.rotationQuaternion.clone();
  14356. }
  14357. this.infiniteDistance = source.infiniteDistance;
  14358. this.setPivotMatrix(source.getPivotMatrix());
  14359. this.refreshBoundingInfo();
  14360. this._syncSubMeshes();
  14361. }
  14362. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14363. // Methods
  14364. get: function () {
  14365. return this._sourceMesh.receiveShadows;
  14366. },
  14367. enumerable: true,
  14368. configurable: true
  14369. });
  14370. Object.defineProperty(InstancedMesh.prototype, "material", {
  14371. get: function () {
  14372. return this._sourceMesh.material;
  14373. },
  14374. enumerable: true,
  14375. configurable: true
  14376. });
  14377. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14378. get: function () {
  14379. return this._sourceMesh.visibility;
  14380. },
  14381. enumerable: true,
  14382. configurable: true
  14383. });
  14384. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14385. get: function () {
  14386. return this._sourceMesh.skeleton;
  14387. },
  14388. enumerable: true,
  14389. configurable: true
  14390. });
  14391. InstancedMesh.prototype.getTotalVertices = function () {
  14392. return this._sourceMesh.getTotalVertices();
  14393. };
  14394. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14395. get: function () {
  14396. return this._sourceMesh;
  14397. },
  14398. enumerable: true,
  14399. configurable: true
  14400. });
  14401. InstancedMesh.prototype.getVerticesData = function (kind) {
  14402. return this._sourceMesh.getVerticesData(kind);
  14403. };
  14404. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14405. return this._sourceMesh.isVerticesDataPresent(kind);
  14406. };
  14407. InstancedMesh.prototype.getIndices = function () {
  14408. return this._sourceMesh.getIndices();
  14409. };
  14410. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14411. get: function () {
  14412. return this._sourceMesh._positions;
  14413. },
  14414. enumerable: true,
  14415. configurable: true
  14416. });
  14417. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14418. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14419. if (data) {
  14420. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14421. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14422. }
  14423. this._updateBoundingInfo();
  14424. };
  14425. InstancedMesh.prototype._preActivate = function () {
  14426. if (this._currentLOD) {
  14427. this._currentLOD._preActivate();
  14428. }
  14429. };
  14430. InstancedMesh.prototype._activate = function (renderId) {
  14431. if (this._currentLOD) {
  14432. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14433. }
  14434. };
  14435. InstancedMesh.prototype.getLOD = function (camera) {
  14436. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14437. if (this._currentLOD === this.sourceMesh) {
  14438. return this;
  14439. }
  14440. return this._currentLOD;
  14441. };
  14442. InstancedMesh.prototype._syncSubMeshes = function () {
  14443. this.releaseSubMeshes();
  14444. if (this._sourceMesh.subMeshes) {
  14445. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14446. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14447. }
  14448. }
  14449. };
  14450. InstancedMesh.prototype._generatePointsArray = function () {
  14451. return this._sourceMesh._generatePointsArray();
  14452. };
  14453. // Clone
  14454. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14455. var result = this._sourceMesh.createInstance(name);
  14456. // Deep copy
  14457. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14458. // Bounding info
  14459. this.refreshBoundingInfo();
  14460. // Parent
  14461. if (newParent) {
  14462. result.parent = newParent;
  14463. }
  14464. if (!doNotCloneChildren) {
  14465. // Children
  14466. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14467. var mesh = this.getScene().meshes[index];
  14468. if (mesh.parent === this) {
  14469. mesh.clone(mesh.name, result);
  14470. }
  14471. }
  14472. }
  14473. result.computeWorldMatrix(true);
  14474. return result;
  14475. };
  14476. // Dispoe
  14477. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14478. // Remove from mesh
  14479. var index = this._sourceMesh.instances.indexOf(this);
  14480. this._sourceMesh.instances.splice(index, 1);
  14481. _super.prototype.dispose.call(this, doNotRecurse);
  14482. };
  14483. return InstancedMesh;
  14484. })(BABYLON.AbstractMesh);
  14485. BABYLON.InstancedMesh = InstancedMesh;
  14486. })(BABYLON || (BABYLON = {}));
  14487. var BABYLON;
  14488. (function (BABYLON) {
  14489. var _InstancesBatch = (function () {
  14490. function _InstancesBatch() {
  14491. this.mustReturn = false;
  14492. this.visibleInstances = new Array();
  14493. this.renderSelf = new Array();
  14494. }
  14495. return _InstancesBatch;
  14496. })();
  14497. BABYLON._InstancesBatch = _InstancesBatch;
  14498. var Mesh = (function (_super) {
  14499. __extends(Mesh, _super);
  14500. /**
  14501. * @constructor
  14502. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14503. * @param {Scene} scene - The scene to add this mesh to.
  14504. * @param {Node} parent - The parent of this mesh, if it has one
  14505. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14506. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14507. * When false, achieved by calling a clone(), also passing False.
  14508. * This will make creation of children, recursive.
  14509. */
  14510. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14511. if (parent === void 0) { parent = null; }
  14512. _super.call(this, name, scene);
  14513. // Members
  14514. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14515. this.instances = new Array();
  14516. this._LODLevels = new Array();
  14517. this._onBeforeRenderCallbacks = new Array();
  14518. this._onAfterRenderCallbacks = new Array();
  14519. this._visibleInstances = {};
  14520. this._renderIdForInstances = new Array();
  14521. this._batchCache = new _InstancesBatch();
  14522. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14523. this._sideOrientation = Mesh._DEFAULTSIDE;
  14524. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14525. if (source) {
  14526. // Geometry
  14527. if (source._geometry) {
  14528. source._geometry.applyToMesh(this);
  14529. }
  14530. // Deep copy
  14531. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14532. this.id = name + "." + source.id;
  14533. // Material
  14534. this.material = source.material;
  14535. if (!doNotCloneChildren) {
  14536. // Children
  14537. for (var index = 0; index < scene.meshes.length; index++) {
  14538. var mesh = scene.meshes[index];
  14539. if (mesh.parent === source) {
  14540. // doNotCloneChildren is always going to be False
  14541. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14542. }
  14543. }
  14544. }
  14545. // Particles
  14546. for (index = 0; index < scene.particleSystems.length; index++) {
  14547. var system = scene.particleSystems[index];
  14548. if (system.emitter === source) {
  14549. system.clone(system.name, this);
  14550. }
  14551. }
  14552. this.computeWorldMatrix(true);
  14553. }
  14554. // Parent
  14555. if (parent !== null) {
  14556. this.parent = parent;
  14557. }
  14558. }
  14559. Object.defineProperty(Mesh, "FRONTSIDE", {
  14560. get: function () {
  14561. return Mesh._FRONTSIDE;
  14562. },
  14563. enumerable: true,
  14564. configurable: true
  14565. });
  14566. Object.defineProperty(Mesh, "BACKSIDE", {
  14567. get: function () {
  14568. return Mesh._BACKSIDE;
  14569. },
  14570. enumerable: true,
  14571. configurable: true
  14572. });
  14573. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14574. get: function () {
  14575. return Mesh._DOUBLESIDE;
  14576. },
  14577. enumerable: true,
  14578. configurable: true
  14579. });
  14580. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14581. get: function () {
  14582. return Mesh._DEFAULTSIDE;
  14583. },
  14584. enumerable: true,
  14585. configurable: true
  14586. });
  14587. Object.defineProperty(Mesh, "NO_CAP", {
  14588. get: function () {
  14589. return Mesh._NO_CAP;
  14590. },
  14591. enumerable: true,
  14592. configurable: true
  14593. });
  14594. Object.defineProperty(Mesh, "CAP_START", {
  14595. get: function () {
  14596. return Mesh._CAP_START;
  14597. },
  14598. enumerable: true,
  14599. configurable: true
  14600. });
  14601. Object.defineProperty(Mesh, "CAP_END", {
  14602. get: function () {
  14603. return Mesh._CAP_END;
  14604. },
  14605. enumerable: true,
  14606. configurable: true
  14607. });
  14608. Object.defineProperty(Mesh, "CAP_ALL", {
  14609. get: function () {
  14610. return Mesh._CAP_ALL;
  14611. },
  14612. enumerable: true,
  14613. configurable: true
  14614. });
  14615. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14616. // Methods
  14617. get: function () {
  14618. return this._LODLevels.length > 0;
  14619. },
  14620. enumerable: true,
  14621. configurable: true
  14622. });
  14623. Mesh.prototype._sortLODLevels = function () {
  14624. this._LODLevels.sort(function (a, b) {
  14625. if (a.distance < b.distance) {
  14626. return 1;
  14627. }
  14628. if (a.distance > b.distance) {
  14629. return -1;
  14630. }
  14631. return 0;
  14632. });
  14633. };
  14634. /**
  14635. * Add a mesh as LOD level triggered at the given distance.
  14636. * @param {number} distance - the distance from the center of the object to show this level
  14637. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14638. * @return {BABYLON.Mesh} this mesh (for chaining)
  14639. */
  14640. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14641. if (mesh && mesh._masterMesh) {
  14642. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14643. return this;
  14644. }
  14645. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14646. this._LODLevels.push(level);
  14647. if (mesh) {
  14648. mesh._masterMesh = this;
  14649. }
  14650. this._sortLODLevels();
  14651. return this;
  14652. };
  14653. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14654. for (var index = 0; index < this._LODLevels.length; index++) {
  14655. var level = this._LODLevels[index];
  14656. if (level.distance === distance) {
  14657. return level.mesh;
  14658. }
  14659. }
  14660. return null;
  14661. };
  14662. /**
  14663. * Remove a mesh from the LOD array
  14664. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14665. * @return {BABYLON.Mesh} this mesh (for chaining)
  14666. */
  14667. Mesh.prototype.removeLODLevel = function (mesh) {
  14668. for (var index = 0; index < this._LODLevels.length; index++) {
  14669. if (this._LODLevels[index].mesh === mesh) {
  14670. this._LODLevels.splice(index, 1);
  14671. if (mesh) {
  14672. mesh._masterMesh = null;
  14673. }
  14674. }
  14675. }
  14676. this._sortLODLevels();
  14677. return this;
  14678. };
  14679. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14680. if (!this._LODLevels || this._LODLevels.length === 0) {
  14681. return this;
  14682. }
  14683. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14684. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14685. if (this.onLODLevelSelection) {
  14686. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14687. }
  14688. return this;
  14689. }
  14690. for (var index = 0; index < this._LODLevels.length; index++) {
  14691. var level = this._LODLevels[index];
  14692. if (level.distance < distanceToCamera) {
  14693. if (level.mesh) {
  14694. level.mesh._preActivate();
  14695. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14696. }
  14697. if (this.onLODLevelSelection) {
  14698. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14699. }
  14700. return level.mesh;
  14701. }
  14702. }
  14703. if (this.onLODLevelSelection) {
  14704. this.onLODLevelSelection(distanceToCamera, this, this);
  14705. }
  14706. return this;
  14707. };
  14708. Object.defineProperty(Mesh.prototype, "geometry", {
  14709. get: function () {
  14710. return this._geometry;
  14711. },
  14712. enumerable: true,
  14713. configurable: true
  14714. });
  14715. Mesh.prototype.getTotalVertices = function () {
  14716. if (!this._geometry) {
  14717. return 0;
  14718. }
  14719. return this._geometry.getTotalVertices();
  14720. };
  14721. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14722. if (!this._geometry) {
  14723. return null;
  14724. }
  14725. return this._geometry.getVerticesData(kind, copyWhenShared);
  14726. };
  14727. Mesh.prototype.getVertexBuffer = function (kind) {
  14728. if (!this._geometry) {
  14729. return undefined;
  14730. }
  14731. return this._geometry.getVertexBuffer(kind);
  14732. };
  14733. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14734. if (!this._geometry) {
  14735. if (this._delayInfo) {
  14736. return this._delayInfo.indexOf(kind) !== -1;
  14737. }
  14738. return false;
  14739. }
  14740. return this._geometry.isVerticesDataPresent(kind);
  14741. };
  14742. Mesh.prototype.getVerticesDataKinds = function () {
  14743. if (!this._geometry) {
  14744. var result = [];
  14745. if (this._delayInfo) {
  14746. for (var kind in this._delayInfo) {
  14747. result.push(kind);
  14748. }
  14749. }
  14750. return result;
  14751. }
  14752. return this._geometry.getVerticesDataKinds();
  14753. };
  14754. Mesh.prototype.getTotalIndices = function () {
  14755. if (!this._geometry) {
  14756. return 0;
  14757. }
  14758. return this._geometry.getTotalIndices();
  14759. };
  14760. Mesh.prototype.getIndices = function (copyWhenShared) {
  14761. if (!this._geometry) {
  14762. return [];
  14763. }
  14764. return this._geometry.getIndices(copyWhenShared);
  14765. };
  14766. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14767. get: function () {
  14768. return this._masterMesh !== null && this._masterMesh !== undefined;
  14769. },
  14770. enumerable: true,
  14771. configurable: true
  14772. });
  14773. Mesh.prototype.isReady = function () {
  14774. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14775. return false;
  14776. }
  14777. return _super.prototype.isReady.call(this);
  14778. };
  14779. Mesh.prototype.isDisposed = function () {
  14780. return this._isDisposed;
  14781. };
  14782. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14783. get: function () {
  14784. return this._sideOrientation;
  14785. },
  14786. set: function (sideO) {
  14787. this._sideOrientation = sideO;
  14788. },
  14789. enumerable: true,
  14790. configurable: true
  14791. });
  14792. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14793. get: function () {
  14794. return this._areNormalsFrozen;
  14795. },
  14796. enumerable: true,
  14797. configurable: true
  14798. });
  14799. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14800. Mesh.prototype.freezeNormals = function () {
  14801. this._areNormalsFrozen = true;
  14802. };
  14803. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14804. Mesh.prototype.unfreezeNormals = function () {
  14805. this._areNormalsFrozen = false;
  14806. };
  14807. // Methods
  14808. Mesh.prototype._preActivate = function () {
  14809. var sceneRenderId = this.getScene().getRenderId();
  14810. if (this._preActivateId === sceneRenderId) {
  14811. return;
  14812. }
  14813. this._preActivateId = sceneRenderId;
  14814. this._visibleInstances = null;
  14815. };
  14816. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14817. if (!this._visibleInstances) {
  14818. this._visibleInstances = {};
  14819. this._visibleInstances.defaultRenderId = renderId;
  14820. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14821. }
  14822. if (!this._visibleInstances[renderId]) {
  14823. this._visibleInstances[renderId] = new Array();
  14824. }
  14825. this._visibleInstances[renderId].push(instance);
  14826. };
  14827. Mesh.prototype.refreshBoundingInfo = function () {
  14828. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14829. if (data) {
  14830. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14831. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14832. }
  14833. if (this.subMeshes) {
  14834. for (var index = 0; index < this.subMeshes.length; index++) {
  14835. this.subMeshes[index].refreshBoundingInfo();
  14836. }
  14837. }
  14838. this._updateBoundingInfo();
  14839. };
  14840. Mesh.prototype._createGlobalSubMesh = function () {
  14841. var totalVertices = this.getTotalVertices();
  14842. if (!totalVertices || !this.getIndices()) {
  14843. return null;
  14844. }
  14845. this.releaseSubMeshes();
  14846. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14847. };
  14848. Mesh.prototype.subdivide = function (count) {
  14849. if (count < 1) {
  14850. return;
  14851. }
  14852. var totalIndices = this.getTotalIndices();
  14853. var subdivisionSize = (totalIndices / count) | 0;
  14854. var offset = 0;
  14855. // Ensure that subdivisionSize is a multiple of 3
  14856. while (subdivisionSize % 3 !== 0) {
  14857. subdivisionSize++;
  14858. }
  14859. this.releaseSubMeshes();
  14860. for (var index = 0; index < count; index++) {
  14861. if (offset >= totalIndices) {
  14862. break;
  14863. }
  14864. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14865. offset += subdivisionSize;
  14866. }
  14867. this.synchronizeInstances();
  14868. };
  14869. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14870. if (kind instanceof Array) {
  14871. var temp = data;
  14872. data = kind;
  14873. kind = temp;
  14874. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14875. }
  14876. if (!this._geometry) {
  14877. var vertexData = new BABYLON.VertexData();
  14878. vertexData.set(data, kind);
  14879. var scene = this.getScene();
  14880. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14881. }
  14882. else {
  14883. this._geometry.setVerticesData(kind, data, updatable, stride);
  14884. }
  14885. };
  14886. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14887. if (!this._geometry) {
  14888. return;
  14889. }
  14890. if (!makeItUnique) {
  14891. this._geometry.updateVerticesData(kind, data, updateExtends);
  14892. }
  14893. else {
  14894. this.makeGeometryUnique();
  14895. this.updateVerticesData(kind, data, updateExtends, false);
  14896. }
  14897. };
  14898. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14899. if (!this._geometry) {
  14900. return;
  14901. }
  14902. if (!makeItUnique) {
  14903. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14904. }
  14905. else {
  14906. this.makeGeometryUnique();
  14907. this.updateVerticesDataDirectly(kind, data, offset, false);
  14908. }
  14909. };
  14910. // Mesh positions update function :
  14911. // updates the mesh positions according to the positionFunction returned values.
  14912. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14913. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14914. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14915. if (computeNormals === void 0) { computeNormals = true; }
  14916. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14917. positionFunction(positions);
  14918. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14919. if (computeNormals) {
  14920. var indices = this.getIndices();
  14921. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14922. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14923. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14924. }
  14925. };
  14926. Mesh.prototype.makeGeometryUnique = function () {
  14927. if (!this._geometry) {
  14928. return;
  14929. }
  14930. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14931. geometry.applyToMesh(this);
  14932. };
  14933. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14934. if (!this._geometry) {
  14935. var vertexData = new BABYLON.VertexData();
  14936. vertexData.indices = indices;
  14937. var scene = this.getScene();
  14938. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14939. }
  14940. else {
  14941. this._geometry.setIndices(indices, totalVertices);
  14942. }
  14943. };
  14944. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14945. var engine = this.getScene().getEngine();
  14946. // Wireframe
  14947. var indexToBind;
  14948. switch (fillMode) {
  14949. case BABYLON.Material.PointFillMode:
  14950. indexToBind = null;
  14951. break;
  14952. case BABYLON.Material.WireFrameFillMode:
  14953. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14954. break;
  14955. default:
  14956. case BABYLON.Material.TriangleFillMode:
  14957. indexToBind = this._geometry.getIndexBuffer();
  14958. break;
  14959. }
  14960. // VBOs
  14961. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14962. };
  14963. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14964. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14965. return;
  14966. }
  14967. var engine = this.getScene().getEngine();
  14968. // Draw order
  14969. switch (fillMode) {
  14970. case BABYLON.Material.PointFillMode:
  14971. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14972. break;
  14973. case BABYLON.Material.WireFrameFillMode:
  14974. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14975. break;
  14976. default:
  14977. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14978. }
  14979. };
  14980. Mesh.prototype.registerBeforeRender = function (func) {
  14981. this._onBeforeRenderCallbacks.push(func);
  14982. };
  14983. Mesh.prototype.unregisterBeforeRender = function (func) {
  14984. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14985. if (index > -1) {
  14986. this._onBeforeRenderCallbacks.splice(index, 1);
  14987. }
  14988. };
  14989. Mesh.prototype.registerAfterRender = function (func) {
  14990. this._onAfterRenderCallbacks.push(func);
  14991. };
  14992. Mesh.prototype.unregisterAfterRender = function (func) {
  14993. var index = this._onAfterRenderCallbacks.indexOf(func);
  14994. if (index > -1) {
  14995. this._onAfterRenderCallbacks.splice(index, 1);
  14996. }
  14997. };
  14998. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14999. var scene = this.getScene();
  15000. this._batchCache.mustReturn = false;
  15001. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15002. this._batchCache.visibleInstances[subMeshId] = null;
  15003. if (this._visibleInstances) {
  15004. var currentRenderId = scene.getRenderId();
  15005. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15006. var selfRenderId = this._renderId;
  15007. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15008. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15009. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15010. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15011. }
  15012. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15013. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15014. this._batchCache.mustReturn = true;
  15015. return this._batchCache;
  15016. }
  15017. if (currentRenderId !== selfRenderId) {
  15018. this._batchCache.renderSelf[subMeshId] = false;
  15019. }
  15020. }
  15021. this._renderIdForInstances[subMeshId] = currentRenderId;
  15022. }
  15023. return this._batchCache;
  15024. };
  15025. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15026. var visibleInstances = batch.visibleInstances[subMesh._id];
  15027. var matricesCount = visibleInstances.length + 1;
  15028. var bufferSize = matricesCount * 16 * 4;
  15029. while (this._instancesBufferSize < bufferSize) {
  15030. this._instancesBufferSize *= 2;
  15031. }
  15032. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15033. if (this._worldMatricesInstancesBuffer) {
  15034. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15035. }
  15036. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15037. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15038. }
  15039. var offset = 0;
  15040. var instancesCount = 0;
  15041. var world = this.getWorldMatrix();
  15042. if (batch.renderSelf[subMesh._id]) {
  15043. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15044. offset += 16;
  15045. instancesCount++;
  15046. }
  15047. if (visibleInstances) {
  15048. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15049. var instance = visibleInstances[instanceIndex];
  15050. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15051. offset += 16;
  15052. instancesCount++;
  15053. }
  15054. }
  15055. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15056. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15057. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15058. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15059. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15060. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15061. this._draw(subMesh, fillMode, instancesCount);
  15062. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15063. };
  15064. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15065. var scene = this.getScene();
  15066. var engine = scene.getEngine();
  15067. if (hardwareInstancedRendering) {
  15068. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15069. }
  15070. else {
  15071. if (batch.renderSelf[subMesh._id]) {
  15072. // Draw
  15073. if (onBeforeDraw) {
  15074. onBeforeDraw(false, this.getWorldMatrix());
  15075. }
  15076. this._draw(subMesh, fillMode);
  15077. }
  15078. if (batch.visibleInstances[subMesh._id]) {
  15079. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15080. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15081. // World
  15082. var world = instance.getWorldMatrix();
  15083. if (onBeforeDraw) {
  15084. onBeforeDraw(true, world);
  15085. }
  15086. // Draw
  15087. this._draw(subMesh, fillMode);
  15088. }
  15089. }
  15090. }
  15091. };
  15092. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15093. var scene = this.getScene();
  15094. // Managing instances
  15095. var batch = this._getInstancesRenderList(subMesh._id);
  15096. if (batch.mustReturn) {
  15097. return;
  15098. }
  15099. // Checking geometry state
  15100. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15101. return;
  15102. }
  15103. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15104. this._onBeforeRenderCallbacks[callbackIndex](this);
  15105. }
  15106. var engine = scene.getEngine();
  15107. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15108. // Material
  15109. var effectiveMaterial = subMesh.getMaterial();
  15110. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15111. return;
  15112. }
  15113. // Outline - step 1
  15114. var savedDepthWrite = engine.getDepthWrite();
  15115. if (this.renderOutline) {
  15116. engine.setDepthWrite(false);
  15117. scene.getOutlineRenderer().render(subMesh, batch);
  15118. engine.setDepthWrite(savedDepthWrite);
  15119. }
  15120. effectiveMaterial._preBind();
  15121. var effect = effectiveMaterial.getEffect();
  15122. // Bind
  15123. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15124. this._bind(subMesh, effect, fillMode);
  15125. var world = this.getWorldMatrix();
  15126. effectiveMaterial.bind(world, this);
  15127. // Alpha mode
  15128. if (enableAlphaMode) {
  15129. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15130. }
  15131. // Draw
  15132. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15133. if (isInstance) {
  15134. effectiveMaterial.bindOnlyWorldMatrix(world);
  15135. }
  15136. });
  15137. // Unbind
  15138. effectiveMaterial.unbind();
  15139. // Outline - step 2
  15140. if (this.renderOutline && savedDepthWrite) {
  15141. engine.setDepthWrite(true);
  15142. engine.setColorWrite(false);
  15143. scene.getOutlineRenderer().render(subMesh, batch);
  15144. engine.setColorWrite(true);
  15145. }
  15146. // Overlay
  15147. if (this.renderOverlay) {
  15148. var currentMode = engine.getAlphaMode();
  15149. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15150. scene.getOutlineRenderer().render(subMesh, batch, true);
  15151. engine.setAlphaMode(currentMode);
  15152. }
  15153. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15154. this._onAfterRenderCallbacks[callbackIndex](this);
  15155. }
  15156. };
  15157. Mesh.prototype.getEmittedParticleSystems = function () {
  15158. var results = new Array();
  15159. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15160. var particleSystem = this.getScene().particleSystems[index];
  15161. if (particleSystem.emitter === this) {
  15162. results.push(particleSystem);
  15163. }
  15164. }
  15165. return results;
  15166. };
  15167. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15168. var results = new Array();
  15169. var descendants = this.getDescendants();
  15170. descendants.push(this);
  15171. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15172. var particleSystem = this.getScene().particleSystems[index];
  15173. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15174. results.push(particleSystem);
  15175. }
  15176. }
  15177. return results;
  15178. };
  15179. Mesh.prototype.getChildren = function () {
  15180. var results = [];
  15181. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15182. var mesh = this.getScene().meshes[index];
  15183. if (mesh.parent === this) {
  15184. results.push(mesh);
  15185. }
  15186. }
  15187. return results;
  15188. };
  15189. Mesh.prototype._checkDelayState = function () {
  15190. var _this = this;
  15191. var that = this;
  15192. var scene = this.getScene();
  15193. if (this._geometry) {
  15194. this._geometry.load(scene);
  15195. }
  15196. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15197. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15198. scene._addPendingData(that);
  15199. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15200. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15201. if (data instanceof ArrayBuffer) {
  15202. _this._delayLoadingFunction(data, _this);
  15203. }
  15204. else {
  15205. _this._delayLoadingFunction(JSON.parse(data), _this);
  15206. }
  15207. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15208. scene._removePendingData(_this);
  15209. }, function () { }, scene.database, getBinaryData);
  15210. }
  15211. };
  15212. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15213. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15214. return false;
  15215. }
  15216. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15217. return false;
  15218. }
  15219. this._checkDelayState();
  15220. return true;
  15221. };
  15222. Mesh.prototype.setMaterialByID = function (id) {
  15223. var materials = this.getScene().materials;
  15224. for (var index = 0; index < materials.length; index++) {
  15225. if (materials[index].id === id) {
  15226. this.material = materials[index];
  15227. return;
  15228. }
  15229. }
  15230. // Multi
  15231. var multiMaterials = this.getScene().multiMaterials;
  15232. for (index = 0; index < multiMaterials.length; index++) {
  15233. if (multiMaterials[index].id === id) {
  15234. this.material = multiMaterials[index];
  15235. return;
  15236. }
  15237. }
  15238. };
  15239. Mesh.prototype.getAnimatables = function () {
  15240. var results = [];
  15241. if (this.material) {
  15242. results.push(this.material);
  15243. }
  15244. if (this.skeleton) {
  15245. results.push(this.skeleton);
  15246. }
  15247. return results;
  15248. };
  15249. // Geometry
  15250. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15251. // Position
  15252. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15253. return;
  15254. }
  15255. this._resetPointsArrayCache();
  15256. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15257. var temp = [];
  15258. for (var index = 0; index < data.length; index += 3) {
  15259. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15260. }
  15261. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15262. // Normals
  15263. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15264. return;
  15265. }
  15266. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15267. temp = [];
  15268. for (index = 0; index < data.length; index += 3) {
  15269. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15270. }
  15271. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15272. // flip faces?
  15273. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15274. this.flipFaces();
  15275. }
  15276. };
  15277. // Will apply current transform to mesh and reset world matrix
  15278. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15279. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15280. this.scaling.copyFromFloats(1, 1, 1);
  15281. this.position.copyFromFloats(0, 0, 0);
  15282. this.rotation.copyFromFloats(0, 0, 0);
  15283. //only if quaternion is already set
  15284. if (this.rotationQuaternion) {
  15285. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15286. }
  15287. this._worldMatrix = BABYLON.Matrix.Identity();
  15288. };
  15289. // Cache
  15290. Mesh.prototype._resetPointsArrayCache = function () {
  15291. this._positions = null;
  15292. };
  15293. Mesh.prototype._generatePointsArray = function () {
  15294. if (this._positions)
  15295. return true;
  15296. this._positions = [];
  15297. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15298. if (!data) {
  15299. return false;
  15300. }
  15301. for (var index = 0; index < data.length; index += 3) {
  15302. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15303. }
  15304. return true;
  15305. };
  15306. // Clone
  15307. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15308. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15309. };
  15310. // Dispose
  15311. Mesh.prototype.dispose = function (doNotRecurse) {
  15312. if (this._geometry) {
  15313. this._geometry.releaseForMesh(this, true);
  15314. }
  15315. // Instances
  15316. if (this._worldMatricesInstancesBuffer) {
  15317. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15318. this._worldMatricesInstancesBuffer = null;
  15319. }
  15320. while (this.instances.length) {
  15321. this.instances[0].dispose();
  15322. }
  15323. _super.prototype.dispose.call(this, doNotRecurse);
  15324. };
  15325. // Geometric tools
  15326. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15327. var _this = this;
  15328. var scene = this.getScene();
  15329. var onload = function (img) {
  15330. // Getting height map data
  15331. var canvas = document.createElement("canvas");
  15332. var context = canvas.getContext("2d");
  15333. var heightMapWidth = img.width;
  15334. var heightMapHeight = img.height;
  15335. canvas.width = heightMapWidth;
  15336. canvas.height = heightMapHeight;
  15337. context.drawImage(img, 0, 0);
  15338. // Create VertexData from map data
  15339. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15340. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15341. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15342. //execute success callback, if set
  15343. if (onSuccess) {
  15344. onSuccess(_this);
  15345. }
  15346. };
  15347. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15348. };
  15349. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15350. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15351. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15352. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15353. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15354. return;
  15355. }
  15356. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15357. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15358. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15359. var position = BABYLON.Vector3.Zero();
  15360. var normal = BABYLON.Vector3.Zero();
  15361. var uv = BABYLON.Vector2.Zero();
  15362. for (var index = 0; index < positions.length; index += 3) {
  15363. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15364. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15365. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15366. // Compute height
  15367. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15368. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15369. var pos = (u + v * heightMapWidth) * 4;
  15370. var r = buffer[pos] / 255.0;
  15371. var g = buffer[pos + 1] / 255.0;
  15372. var b = buffer[pos + 2] / 255.0;
  15373. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15374. normal.normalize();
  15375. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15376. position = position.add(normal);
  15377. position.toArray(positions, index);
  15378. }
  15379. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15380. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15381. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15382. };
  15383. Mesh.prototype.convertToFlatShadedMesh = function () {
  15384. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15385. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15386. var kinds = this.getVerticesDataKinds();
  15387. var vbs = [];
  15388. var data = [];
  15389. var newdata = [];
  15390. var updatableNormals = false;
  15391. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15392. var kind = kinds[kindIndex];
  15393. var vertexBuffer = this.getVertexBuffer(kind);
  15394. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15395. updatableNormals = vertexBuffer.isUpdatable();
  15396. kinds.splice(kindIndex, 1);
  15397. kindIndex--;
  15398. continue;
  15399. }
  15400. vbs[kind] = vertexBuffer;
  15401. data[kind] = vbs[kind].getData();
  15402. newdata[kind] = [];
  15403. }
  15404. // Save previous submeshes
  15405. var previousSubmeshes = this.subMeshes.slice(0);
  15406. var indices = this.getIndices();
  15407. var totalIndices = this.getTotalIndices();
  15408. // Generating unique vertices per face
  15409. for (var index = 0; index < totalIndices; index++) {
  15410. var vertexIndex = indices[index];
  15411. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15412. kind = kinds[kindIndex];
  15413. var stride = vbs[kind].getStrideSize();
  15414. for (var offset = 0; offset < stride; offset++) {
  15415. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15416. }
  15417. }
  15418. }
  15419. // Updating faces & normal
  15420. var normals = [];
  15421. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15422. for (index = 0; index < totalIndices; index += 3) {
  15423. indices[index] = index;
  15424. indices[index + 1] = index + 1;
  15425. indices[index + 2] = index + 2;
  15426. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15427. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15428. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15429. var p1p2 = p1.subtract(p2);
  15430. var p3p2 = p3.subtract(p2);
  15431. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15432. // Store same normals for every vertex
  15433. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15434. normals.push(normal.x);
  15435. normals.push(normal.y);
  15436. normals.push(normal.z);
  15437. }
  15438. }
  15439. this.setIndices(indices);
  15440. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15441. // Updating vertex buffers
  15442. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15443. kind = kinds[kindIndex];
  15444. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15445. }
  15446. // Updating submeshes
  15447. this.releaseSubMeshes();
  15448. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15449. var previousOne = previousSubmeshes[submeshIndex];
  15450. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15451. }
  15452. this.synchronizeInstances();
  15453. };
  15454. // will inverse faces orientations, and invert normals too if specified
  15455. Mesh.prototype.flipFaces = function (flipNormals) {
  15456. if (flipNormals === void 0) { flipNormals = false; }
  15457. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15458. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15459. for (var i = 0; i < vertex_data.normals.length; i++) {
  15460. vertex_data.normals[i] *= -1;
  15461. }
  15462. }
  15463. var temp;
  15464. for (var i = 0; i < vertex_data.indices.length; i += 3) {
  15465. // reassign indices
  15466. temp = vertex_data.indices[i + 1];
  15467. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15468. vertex_data.indices[i + 2] = temp;
  15469. }
  15470. vertex_data.applyToMesh(this);
  15471. };
  15472. // Instances
  15473. Mesh.prototype.createInstance = function (name) {
  15474. return new BABYLON.InstancedMesh(name, this);
  15475. };
  15476. Mesh.prototype.synchronizeInstances = function () {
  15477. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15478. var instance = this.instances[instanceIndex];
  15479. instance._syncSubMeshes();
  15480. }
  15481. };
  15482. /**
  15483. * Simplify the mesh according to the given array of settings.
  15484. * Function will return immediately and will simplify async.
  15485. * @param settings a collection of simplification settings.
  15486. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15487. * @param type the type of simplification to run.
  15488. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15489. */
  15490. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15491. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15492. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15493. this.getScene().simplificationQueue.addTask({
  15494. settings: settings,
  15495. parallelProcessing: parallelProcessing,
  15496. mesh: this,
  15497. simplificationType: simplificationType,
  15498. successCallback: successCallback
  15499. });
  15500. };
  15501. /**
  15502. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15503. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15504. * This should be used together with the simplification to avoid disappearing triangles.
  15505. * @param successCallback an optional success callback to be called after the optimization finished.
  15506. */
  15507. Mesh.prototype.optimizeIndices = function (successCallback) {
  15508. var _this = this;
  15509. var indices = this.getIndices();
  15510. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15511. var vectorPositions = [];
  15512. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15513. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15514. }
  15515. var dupes = [];
  15516. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15517. var realPos = vectorPositions.length - 1 - iteration;
  15518. var testedPosition = vectorPositions[realPos];
  15519. for (var j = 0; j < realPos; ++j) {
  15520. var againstPosition = vectorPositions[j];
  15521. if (testedPosition.equals(againstPosition)) {
  15522. dupes[realPos] = j;
  15523. break;
  15524. }
  15525. }
  15526. }, function () {
  15527. for (var i = 0; i < indices.length; ++i) {
  15528. indices[i] = dupes[indices[i]] || indices[i];
  15529. }
  15530. //indices are now reordered
  15531. var originalSubMeshes = _this.subMeshes.slice(0);
  15532. _this.setIndices(indices);
  15533. _this.subMeshes = originalSubMeshes;
  15534. if (successCallback) {
  15535. successCallback(_this);
  15536. }
  15537. });
  15538. };
  15539. // Statics
  15540. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15541. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15542. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15543. if (ribbonInstance) {
  15544. // positionFunction : ribbon case
  15545. // only pathArray and sideOrientation parameters are taken into account for positions update
  15546. var positionFunction = function (positions) {
  15547. var minlg = pathArray[0].length;
  15548. var i = 0;
  15549. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15550. for (var si = 1; si <= ns; si++) {
  15551. for (var p = 0; p < pathArray.length; p++) {
  15552. var path = pathArray[p];
  15553. var l = path.length;
  15554. minlg = (minlg < l) ? minlg : l;
  15555. var j = 0;
  15556. while (j < minlg) {
  15557. positions[i] = path[j].x;
  15558. positions[i + 1] = path[j].y;
  15559. positions[i + 2] = path[j].z;
  15560. j++;
  15561. i += 3;
  15562. }
  15563. if (ribbonInstance._closePath) {
  15564. positions[i] = path[0].x;
  15565. positions[i + 1] = path[0].y;
  15566. positions[i + 2] = path[0].z;
  15567. i += 3;
  15568. }
  15569. }
  15570. }
  15571. };
  15572. var positions = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15573. positionFunction(positions);
  15574. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15575. if (!(ribbonInstance.areNormalsFrozen)) {
  15576. var indices = ribbonInstance.getIndices();
  15577. var normals = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15578. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15579. if (ribbonInstance._closePath) {
  15580. var indexFirst = 0;
  15581. var indexLast = 0;
  15582. for (var p = 0; p < pathArray.length; p++) {
  15583. indexFirst = ribbonInstance._idx[p] * 3;
  15584. if (p + 1 < pathArray.length) {
  15585. indexLast = (ribbonInstance._idx[p + 1] - 1) * 3;
  15586. }
  15587. else {
  15588. indexLast = normals.length - 3;
  15589. }
  15590. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15591. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15592. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15593. normals[indexLast] = normals[indexFirst];
  15594. normals[indexLast + 1] = normals[indexFirst + 1];
  15595. normals[indexLast + 2] = normals[indexFirst + 2];
  15596. }
  15597. }
  15598. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15599. }
  15600. return ribbonInstance;
  15601. }
  15602. else {
  15603. var ribbon = new Mesh(name, scene);
  15604. ribbon.sideOrientation = sideOrientation;
  15605. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15606. if (closePath) {
  15607. ribbon._idx = vertexData._idx;
  15608. }
  15609. ribbon._closePath = closePath;
  15610. vertexData.applyToMesh(ribbon, updatable);
  15611. return ribbon;
  15612. }
  15613. };
  15614. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15615. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15616. var disc = new Mesh(name, scene);
  15617. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15618. vertexData.applyToMesh(disc, updatable);
  15619. return disc;
  15620. };
  15621. Mesh.CreateBox = function (name, options, scene, updatable, sideOrientation) {
  15622. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15623. // Check parameters
  15624. updatable = updatable || options.updatable;
  15625. sideOrientation = sideOrientation || options.sideOrientation;
  15626. var box = new Mesh(name, scene);
  15627. var vertexData = BABYLON.VertexData.CreateBox(options, sideOrientation);
  15628. vertexData.applyToMesh(box, updatable);
  15629. return box;
  15630. };
  15631. Mesh.CreateSphere = function (name, options, diameterOrScene, scene, updatable, sideOrientation) {
  15632. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15633. if (diameterOrScene instanceof BABYLON.Scene) {
  15634. scene = diameterOrScene;
  15635. updatable = options.updatable;
  15636. }
  15637. else {
  15638. var segments = options;
  15639. options = {
  15640. segments: segments,
  15641. diameterX: diameterOrScene,
  15642. diameterY: diameterOrScene,
  15643. diameterZ: diameterOrScene,
  15644. sideOrientation: sideOrientation
  15645. };
  15646. }
  15647. var sphere = new Mesh(name, scene);
  15648. var vertexData = BABYLON.VertexData.CreateSphere(options);
  15649. vertexData.applyToMesh(sphere, updatable);
  15650. return sphere;
  15651. };
  15652. // Cylinder and cone
  15653. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15654. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15655. // subdivisions is a new parameter, we need to support old signature
  15656. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15657. if (scene !== undefined) {
  15658. updatable = scene;
  15659. }
  15660. scene = subdivisions;
  15661. subdivisions = 1;
  15662. }
  15663. var cylinder = new Mesh(name, scene);
  15664. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation);
  15665. vertexData.applyToMesh(cylinder, updatable);
  15666. return cylinder;
  15667. };
  15668. // Torus (Code from SharpDX.org)
  15669. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15670. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15671. var torus = new Mesh(name, scene);
  15672. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15673. vertexData.applyToMesh(torus, updatable);
  15674. return torus;
  15675. };
  15676. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15677. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15678. var torusKnot = new Mesh(name, scene);
  15679. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15680. vertexData.applyToMesh(torusKnot, updatable);
  15681. return torusKnot;
  15682. };
  15683. // Lines
  15684. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15685. if (linesInstance === void 0) { linesInstance = null; }
  15686. if (linesInstance) {
  15687. var positionFunction = function (positions) {
  15688. var i = 0;
  15689. for (var p = 0; p < points.length; p++) {
  15690. positions[i] = points[p].x;
  15691. positions[i + 1] = points[p].y;
  15692. positions[i + 2] = points[p].z;
  15693. i += 3;
  15694. }
  15695. };
  15696. linesInstance.updateMeshPositions(positionFunction, false);
  15697. return linesInstance;
  15698. }
  15699. // lines creation
  15700. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15701. var vertexData = BABYLON.VertexData.CreateLines(points);
  15702. vertexData.applyToMesh(lines, updatable);
  15703. return lines;
  15704. };
  15705. // Dashed Lines
  15706. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15707. if (linesInstance === void 0) { linesInstance = null; }
  15708. if (linesInstance) {
  15709. var positionFunction = function (positions) {
  15710. var curvect = BABYLON.Vector3.Zero();
  15711. var nbSeg = positions.length / 6;
  15712. var lg = 0;
  15713. var nb = 0;
  15714. var shft = 0;
  15715. var dashshft = 0;
  15716. var curshft = 0;
  15717. var p = 0;
  15718. var i = 0;
  15719. var j = 0;
  15720. for (i = 0; i < points.length - 1; i++) {
  15721. points[i + 1].subtractToRef(points[i], curvect);
  15722. lg += curvect.length();
  15723. }
  15724. shft = lg / nbSeg;
  15725. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15726. for (i = 0; i < points.length - 1; i++) {
  15727. points[i + 1].subtractToRef(points[i], curvect);
  15728. nb = Math.floor(curvect.length() / shft);
  15729. curvect.normalize();
  15730. j = 0;
  15731. while (j < nb && p < positions.length) {
  15732. curshft = shft * j;
  15733. positions[p] = points[i].x + curshft * curvect.x;
  15734. positions[p + 1] = points[i].y + curshft * curvect.y;
  15735. positions[p + 2] = points[i].z + curshft * curvect.z;
  15736. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15737. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15738. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15739. p += 6;
  15740. j++;
  15741. }
  15742. }
  15743. while (p < positions.length) {
  15744. positions[p] = points[i].x;
  15745. positions[p + 1] = points[i].y;
  15746. positions[p + 2] = points[i].z;
  15747. p += 3;
  15748. }
  15749. };
  15750. linesInstance.updateMeshPositions(positionFunction, false);
  15751. return linesInstance;
  15752. }
  15753. // dashed lines creation
  15754. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15755. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15756. vertexData.applyToMesh(dashedLines, updatable);
  15757. dashedLines.dashSize = dashSize;
  15758. dashedLines.gapSize = gapSize;
  15759. return dashedLines;
  15760. };
  15761. // Extrusion
  15762. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15763. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15764. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15765. scale = scale || 1;
  15766. rotation = rotation || 0;
  15767. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15768. return extruded;
  15769. };
  15770. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15771. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15772. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15773. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15774. return extrudedCustom;
  15775. };
  15776. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15777. // extrusion geometry
  15778. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15779. var tangents = path3D.getTangents();
  15780. var normals = path3D.getNormals();
  15781. var binormals = path3D.getBinormals();
  15782. var distances = path3D.getDistances();
  15783. var angle = 0;
  15784. var returnScale = function (i, distance) { return scale; };
  15785. var returnRotation = function (i, distance) { return rotation; };
  15786. var rotate = custom ? rotateFunction : returnRotation;
  15787. var scl = custom ? scaleFunction : returnScale;
  15788. var index = 0;
  15789. for (var i = 0; i < curve.length; i++) {
  15790. var shapePath = new Array();
  15791. var angleStep = rotate(i, distances[i]);
  15792. var scaleRatio = scl(i, distances[i]);
  15793. for (var p = 0; p < shape.length; p++) {
  15794. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15795. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15796. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15797. shapePath.push(rotated);
  15798. }
  15799. shapePaths[index] = shapePath;
  15800. angle += angleStep;
  15801. index++;
  15802. }
  15803. // cap
  15804. var capPath = function (shapePath) {
  15805. var pointCap = Array();
  15806. var barycenter = BABYLON.Vector3.Zero();
  15807. var i;
  15808. for (i = 0; i < shapePath.length; i++) {
  15809. barycenter.addInPlace(shapePath[i]);
  15810. }
  15811. barycenter.scaleInPlace(1 / shapePath.length);
  15812. for (i = 0; i < shapePath.length; i++) {
  15813. pointCap.push(barycenter);
  15814. }
  15815. return pointCap;
  15816. };
  15817. switch (cap) {
  15818. case Mesh.NO_CAP:
  15819. break;
  15820. case Mesh.CAP_START:
  15821. shapePaths.unshift(capPath(shapePaths[0]));
  15822. break;
  15823. case Mesh.CAP_END:
  15824. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15825. break;
  15826. case Mesh.CAP_ALL:
  15827. shapePaths.unshift(capPath(shapePaths[0]));
  15828. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15829. break;
  15830. default:
  15831. break;
  15832. }
  15833. return shapePaths;
  15834. };
  15835. var path3D;
  15836. var pathArray;
  15837. if (instance) {
  15838. path3D = (instance.path3D).update(curve);
  15839. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15840. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15841. return instance;
  15842. }
  15843. // extruded shape creation
  15844. path3D = new BABYLON.Path3D(curve);
  15845. var newShapePaths = new Array();
  15846. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15847. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15848. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15849. extrudedGeneric.pathArray = pathArray;
  15850. extrudedGeneric.path3D = path3D;
  15851. extrudedGeneric.cap = cap;
  15852. return extrudedGeneric;
  15853. };
  15854. // Lathe
  15855. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15856. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15857. radius = radius || 1;
  15858. tessellation = tessellation || radius * 60;
  15859. var pi2 = Math.PI * 2;
  15860. var Y = BABYLON.Axis.Y;
  15861. var shapeLathe = new Array();
  15862. // first rotatable point
  15863. var i = 0;
  15864. while (shape[i].x === 0) {
  15865. i++;
  15866. }
  15867. var pt = shape[i];
  15868. for (i = 0; i < shape.length; i++) {
  15869. shapeLathe.push(shape[i].subtract(pt));
  15870. }
  15871. // circle path
  15872. var step = pi2 / tessellation;
  15873. var rotated;
  15874. var path = new Array();
  15875. ;
  15876. for (i = 0; i < tessellation; i++) {
  15877. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15878. path.push(rotated);
  15879. }
  15880. path.push(path[0]);
  15881. // extrusion
  15882. var scaleFunction = function () { return 1; };
  15883. var rotateFunction = function () { return 0; };
  15884. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15885. return lathe;
  15886. };
  15887. // Plane & ground
  15888. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15889. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15890. var plane = new Mesh(name, scene);
  15891. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15892. vertexData.applyToMesh(plane, updatable);
  15893. return plane;
  15894. };
  15895. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15896. var ground = new BABYLON.GroundMesh(name, scene);
  15897. ground._setReady(false);
  15898. ground._subdivisions = subdivisions;
  15899. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15900. vertexData.applyToMesh(ground, updatable);
  15901. ground._setReady(true);
  15902. return ground;
  15903. };
  15904. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15905. var tiledGround = new Mesh(name, scene);
  15906. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15907. vertexData.applyToMesh(tiledGround, updatable);
  15908. return tiledGround;
  15909. };
  15910. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15911. var ground = new BABYLON.GroundMesh(name, scene);
  15912. ground._subdivisions = subdivisions;
  15913. ground._setReady(false);
  15914. var onload = function (img) {
  15915. // Getting height map data
  15916. var canvas = document.createElement("canvas");
  15917. var context = canvas.getContext("2d");
  15918. var heightMapWidth = img.width;
  15919. var heightMapHeight = img.height;
  15920. canvas.width = heightMapWidth;
  15921. canvas.height = heightMapHeight;
  15922. context.drawImage(img, 0, 0);
  15923. // Create VertexData from map data
  15924. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15925. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15926. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15927. vertexData.applyToMesh(ground, updatable);
  15928. ground._setReady(true);
  15929. //execute ready callback, if set
  15930. if (onReady) {
  15931. onReady(ground);
  15932. }
  15933. };
  15934. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15935. return ground;
  15936. };
  15937. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15938. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15939. if (tubeInstance === void 0) { tubeInstance = null; }
  15940. // tube geometry
  15941. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15942. var tangents = path3D.getTangents();
  15943. var normals = path3D.getNormals();
  15944. var distances = path3D.getDistances();
  15945. var pi2 = Math.PI * 2;
  15946. var step = pi2 / tessellation;
  15947. var returnRadius = function (i, distance) { return radius; };
  15948. var radiusFunctionFinal = radiusFunction || returnRadius;
  15949. var circlePath;
  15950. var rad;
  15951. var normal;
  15952. var rotated;
  15953. var rotationMatrix;
  15954. var index = 0;
  15955. for (var i = 0; i < path.length; i++) {
  15956. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15957. circlePath = Array(); // current circle array
  15958. normal = normals[i]; // current normal
  15959. for (var t = 0; t < tessellation; t++) {
  15960. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15961. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15962. circlePath.push(rotated);
  15963. }
  15964. circlePaths[index] = circlePath;
  15965. index++;
  15966. }
  15967. // cap
  15968. var capPath = function (nbPoints, pathIndex) {
  15969. var pointCap = Array();
  15970. for (var i = 0; i < nbPoints; i++) {
  15971. pointCap.push(path[pathIndex]);
  15972. }
  15973. return pointCap;
  15974. };
  15975. switch (cap) {
  15976. case Mesh.NO_CAP:
  15977. break;
  15978. case Mesh.CAP_START:
  15979. circlePaths.unshift(capPath(tessellation + 1, 0));
  15980. break;
  15981. case Mesh.CAP_END:
  15982. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15983. break;
  15984. case Mesh.CAP_ALL:
  15985. circlePaths.unshift(capPath(tessellation + 1, 0));
  15986. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15987. break;
  15988. default:
  15989. break;
  15990. }
  15991. return circlePaths;
  15992. };
  15993. var path3D;
  15994. var pathArray;
  15995. if (tubeInstance) {
  15996. path3D = (tubeInstance.path3D).update(path);
  15997. pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15998. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15999. return tubeInstance;
  16000. }
  16001. // tube creation
  16002. path3D = new BABYLON.Path3D(path);
  16003. var newPathArray = new Array();
  16004. cap = (cap < 0 || cap > 3) ? 0 : cap;
  16005. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  16006. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  16007. tube.pathArray = pathArray;
  16008. tube.path3D = path3D;
  16009. tube.tessellation = tessellation;
  16010. tube.cap = cap;
  16011. return tube;
  16012. };
  16013. // Decals
  16014. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  16015. if (angle === void 0) { angle = 0; }
  16016. var indices = sourceMesh.getIndices();
  16017. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16018. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16019. // Getting correct rotation
  16020. if (!normal) {
  16021. var target = new BABYLON.Vector3(0, 0, 1);
  16022. var camera = sourceMesh.getScene().activeCamera;
  16023. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16024. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16025. }
  16026. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16027. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16028. var pitch = Math.atan2(normal.y, len);
  16029. // Matrix
  16030. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16031. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16032. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16033. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16034. var vertexData = new BABYLON.VertexData();
  16035. vertexData.indices = [];
  16036. vertexData.positions = [];
  16037. vertexData.normals = [];
  16038. vertexData.uvs = [];
  16039. var currentVertexDataIndex = 0;
  16040. var extractDecalVector3 = function (indexId) {
  16041. var vertexId = indices[indexId];
  16042. var result = new BABYLON.PositionNormalVertex();
  16043. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16044. // Send vector to decal local world
  16045. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16046. // Get normal
  16047. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16048. return result;
  16049. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16050. var clip = function (vertices, axis) {
  16051. if (vertices.length === 0) {
  16052. return vertices;
  16053. }
  16054. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16055. var clipVertices = function (v0, v1) {
  16056. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16057. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16058. };
  16059. var result = new Array();
  16060. for (var index = 0; index < vertices.length; index += 3) {
  16061. var v1Out;
  16062. var v2Out;
  16063. var v3Out;
  16064. var total = 0;
  16065. var nV1, nV2, nV3, nV4;
  16066. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16067. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16068. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16069. v1Out = d1 > 0;
  16070. v2Out = d2 > 0;
  16071. v3Out = d3 > 0;
  16072. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16073. switch (total) {
  16074. case 0:
  16075. result.push(vertices[index]);
  16076. result.push(vertices[index + 1]);
  16077. result.push(vertices[index + 2]);
  16078. break;
  16079. case 1:
  16080. if (v1Out) {
  16081. nV1 = vertices[index + 1];
  16082. nV2 = vertices[index + 2];
  16083. nV3 = clipVertices(vertices[index], nV1);
  16084. nV4 = clipVertices(vertices[index], nV2);
  16085. }
  16086. if (v2Out) {
  16087. nV1 = vertices[index];
  16088. nV2 = vertices[index + 2];
  16089. nV3 = clipVertices(vertices[index + 1], nV1);
  16090. nV4 = clipVertices(vertices[index + 1], nV2);
  16091. result.push(nV3);
  16092. result.push(nV2.clone());
  16093. result.push(nV1.clone());
  16094. result.push(nV2.clone());
  16095. result.push(nV3.clone());
  16096. result.push(nV4);
  16097. break;
  16098. }
  16099. if (v3Out) {
  16100. nV1 = vertices[index];
  16101. nV2 = vertices[index + 1];
  16102. nV3 = clipVertices(vertices[index + 2], nV1);
  16103. nV4 = clipVertices(vertices[index + 2], nV2);
  16104. }
  16105. result.push(nV1.clone());
  16106. result.push(nV2.clone());
  16107. result.push(nV3);
  16108. result.push(nV4);
  16109. result.push(nV3.clone());
  16110. result.push(nV2.clone());
  16111. break;
  16112. case 2:
  16113. if (!v1Out) {
  16114. nV1 = vertices[index].clone();
  16115. nV2 = clipVertices(nV1, vertices[index + 1]);
  16116. nV3 = clipVertices(nV1, vertices[index + 2]);
  16117. result.push(nV1);
  16118. result.push(nV2);
  16119. result.push(nV3);
  16120. }
  16121. if (!v2Out) {
  16122. nV1 = vertices[index + 1].clone();
  16123. nV2 = clipVertices(nV1, vertices[index + 2]);
  16124. nV3 = clipVertices(nV1, vertices[index]);
  16125. result.push(nV1);
  16126. result.push(nV2);
  16127. result.push(nV3);
  16128. }
  16129. if (!v3Out) {
  16130. nV1 = vertices[index + 2].clone();
  16131. nV2 = clipVertices(nV1, vertices[index]);
  16132. nV3 = clipVertices(nV1, vertices[index + 1]);
  16133. result.push(nV1);
  16134. result.push(nV2);
  16135. result.push(nV3);
  16136. }
  16137. break;
  16138. case 3:
  16139. break;
  16140. }
  16141. }
  16142. return result;
  16143. };
  16144. for (var index = 0; index < indices.length; index += 3) {
  16145. var faceVertices = new Array();
  16146. faceVertices.push(extractDecalVector3(index));
  16147. faceVertices.push(extractDecalVector3(index + 1));
  16148. faceVertices.push(extractDecalVector3(index + 2));
  16149. // Clip
  16150. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16151. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16152. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16153. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16154. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16155. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16156. if (faceVertices.length === 0) {
  16157. continue;
  16158. }
  16159. // Add UVs and get back to world
  16160. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16161. var vertex = faceVertices[vIndex];
  16162. vertexData.indices.push(currentVertexDataIndex);
  16163. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16164. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16165. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16166. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16167. currentVertexDataIndex++;
  16168. }
  16169. }
  16170. // Return mesh
  16171. var decal = new Mesh(name, sourceMesh.getScene());
  16172. vertexData.applyToMesh(decal);
  16173. decal.position = position.clone();
  16174. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16175. return decal;
  16176. };
  16177. // Skeletons
  16178. /**
  16179. * Update the vertex buffers by applying transformation from the bones
  16180. * @param {skeleton} skeleton to apply
  16181. */
  16182. Mesh.prototype.applySkeleton = function (skeleton) {
  16183. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16184. return this;
  16185. }
  16186. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16187. return this;
  16188. }
  16189. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16190. return this;
  16191. }
  16192. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16193. return this;
  16194. }
  16195. var source;
  16196. if (!this._sourcePositions) {
  16197. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16198. this._sourcePositions = new Float32Array(source);
  16199. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16200. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16201. }
  16202. }
  16203. if (!this._sourceNormals) {
  16204. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16205. this._sourceNormals = new Float32Array(source);
  16206. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16207. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16208. }
  16209. }
  16210. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16211. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16212. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16213. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16214. var skeletonMatrices = skeleton.getTransformMatrices();
  16215. var tempVector3 = BABYLON.Vector3.Zero();
  16216. var finalMatrix = new BABYLON.Matrix();
  16217. var tempMatrix = new BABYLON.Matrix();
  16218. for (var index = 0; index < positionsData.length; index += 3) {
  16219. var index4 = (index / 3) * 4;
  16220. var matricesWeight0 = matricesWeightsData[index4];
  16221. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16222. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16223. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16224. if (matricesWeight0 > 0) {
  16225. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16226. finalMatrix.addToSelf(tempMatrix);
  16227. }
  16228. if (matricesWeight1 > 0) {
  16229. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16230. finalMatrix.addToSelf(tempMatrix);
  16231. }
  16232. if (matricesWeight2 > 0) {
  16233. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16234. finalMatrix.addToSelf(tempMatrix);
  16235. }
  16236. if (matricesWeight3 > 0) {
  16237. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16238. finalMatrix.addToSelf(tempMatrix);
  16239. }
  16240. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16241. tempVector3.toArray(positionsData, index);
  16242. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16243. tempVector3.toArray(normalsData, index);
  16244. finalMatrix.reset();
  16245. }
  16246. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16247. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16248. return this;
  16249. };
  16250. // Tools
  16251. Mesh.MinMax = function (meshes) {
  16252. var minVector = null;
  16253. var maxVector = null;
  16254. for (var i in meshes) {
  16255. var mesh = meshes[i];
  16256. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16257. if (!minVector) {
  16258. minVector = boundingBox.minimumWorld;
  16259. maxVector = boundingBox.maximumWorld;
  16260. continue;
  16261. }
  16262. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16263. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16264. }
  16265. return {
  16266. min: minVector,
  16267. max: maxVector
  16268. };
  16269. };
  16270. Mesh.Center = function (meshesOrMinMaxVector) {
  16271. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16272. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16273. };
  16274. /**
  16275. * Merge the array of meshes into a single mesh for performance reasons.
  16276. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16277. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16278. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16279. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16280. */
  16281. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16282. if (disposeSource === void 0) { disposeSource = true; }
  16283. var index;
  16284. if (!allow32BitsIndices) {
  16285. var totalVertices = 0;
  16286. // Counting vertices
  16287. for (index = 0; index < meshes.length; index++) {
  16288. if (meshes[index]) {
  16289. totalVertices += meshes[index].getTotalVertices();
  16290. if (totalVertices > 65536) {
  16291. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16292. return null;
  16293. }
  16294. }
  16295. }
  16296. }
  16297. // Merge
  16298. var vertexData;
  16299. var otherVertexData;
  16300. var source;
  16301. for (index = 0; index < meshes.length; index++) {
  16302. if (meshes[index]) {
  16303. meshes[index].computeWorldMatrix(true);
  16304. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16305. otherVertexData.transform(meshes[index].getWorldMatrix());
  16306. if (vertexData) {
  16307. vertexData.merge(otherVertexData);
  16308. }
  16309. else {
  16310. vertexData = otherVertexData;
  16311. source = meshes[index];
  16312. }
  16313. }
  16314. }
  16315. if (!meshSubclass) {
  16316. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16317. }
  16318. vertexData.applyToMesh(meshSubclass);
  16319. // Setting properties
  16320. meshSubclass.material = source.material;
  16321. meshSubclass.checkCollisions = source.checkCollisions;
  16322. // Cleaning
  16323. if (disposeSource) {
  16324. for (index = 0; index < meshes.length; index++) {
  16325. if (meshes[index]) {
  16326. meshes[index].dispose();
  16327. }
  16328. }
  16329. }
  16330. return meshSubclass;
  16331. };
  16332. // Consts
  16333. Mesh._FRONTSIDE = 0;
  16334. Mesh._BACKSIDE = 1;
  16335. Mesh._DOUBLESIDE = 2;
  16336. Mesh._DEFAULTSIDE = 0;
  16337. Mesh._NO_CAP = 0;
  16338. Mesh._CAP_START = 1;
  16339. Mesh._CAP_END = 2;
  16340. Mesh._CAP_ALL = 3;
  16341. return Mesh;
  16342. })(BABYLON.AbstractMesh);
  16343. BABYLON.Mesh = Mesh;
  16344. })(BABYLON || (BABYLON = {}));
  16345. var BABYLON;
  16346. (function (BABYLON) {
  16347. var SubMesh = (function () {
  16348. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16349. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16350. this.materialIndex = materialIndex;
  16351. this.verticesStart = verticesStart;
  16352. this.verticesCount = verticesCount;
  16353. this.indexStart = indexStart;
  16354. this.indexCount = indexCount;
  16355. this._renderId = 0;
  16356. this._mesh = mesh;
  16357. this._renderingMesh = renderingMesh || mesh;
  16358. mesh.subMeshes.push(this);
  16359. this._trianglePlanes = [];
  16360. this._id = mesh.subMeshes.length - 1;
  16361. if (createBoundingBox) {
  16362. this.refreshBoundingInfo();
  16363. mesh.computeWorldMatrix(true);
  16364. }
  16365. }
  16366. SubMesh.prototype.getBoundingInfo = function () {
  16367. return this._boundingInfo;
  16368. };
  16369. SubMesh.prototype.getMesh = function () {
  16370. return this._mesh;
  16371. };
  16372. SubMesh.prototype.getRenderingMesh = function () {
  16373. return this._renderingMesh;
  16374. };
  16375. SubMesh.prototype.getMaterial = function () {
  16376. var rootMaterial = this._renderingMesh.material;
  16377. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16378. var multiMaterial = rootMaterial;
  16379. return multiMaterial.getSubMaterial(this.materialIndex);
  16380. }
  16381. if (!rootMaterial) {
  16382. return this._mesh.getScene().defaultMaterial;
  16383. }
  16384. return rootMaterial;
  16385. };
  16386. // Methods
  16387. SubMesh.prototype.refreshBoundingInfo = function () {
  16388. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16389. if (!data) {
  16390. this._boundingInfo = this._mesh._boundingInfo;
  16391. return;
  16392. }
  16393. var indices = this._renderingMesh.getIndices();
  16394. var extend;
  16395. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16396. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16397. }
  16398. else {
  16399. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16400. }
  16401. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16402. };
  16403. SubMesh.prototype._checkCollision = function (collider) {
  16404. return this._boundingInfo._checkCollision(collider);
  16405. };
  16406. SubMesh.prototype.updateBoundingInfo = function (world) {
  16407. if (!this._boundingInfo) {
  16408. this.refreshBoundingInfo();
  16409. }
  16410. this._boundingInfo._update(world);
  16411. };
  16412. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16413. return this._boundingInfo.isInFrustum(frustumPlanes);
  16414. };
  16415. SubMesh.prototype.render = function (enableAlphaMode) {
  16416. this._renderingMesh.render(this, enableAlphaMode);
  16417. };
  16418. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16419. if (!this._linesIndexBuffer) {
  16420. var linesIndices = [];
  16421. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16422. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16423. }
  16424. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16425. this.linesIndexCount = linesIndices.length;
  16426. }
  16427. return this._linesIndexBuffer;
  16428. };
  16429. SubMesh.prototype.canIntersects = function (ray) {
  16430. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16431. };
  16432. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16433. var intersectInfo = null;
  16434. // Triangles test
  16435. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16436. var p0 = positions[indices[index]];
  16437. var p1 = positions[indices[index + 1]];
  16438. var p2 = positions[indices[index + 2]];
  16439. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16440. if (currentIntersectInfo) {
  16441. if (currentIntersectInfo.distance < 0) {
  16442. continue;
  16443. }
  16444. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16445. intersectInfo = currentIntersectInfo;
  16446. intersectInfo.faceId = index / 3;
  16447. if (fastCheck) {
  16448. break;
  16449. }
  16450. }
  16451. }
  16452. }
  16453. return intersectInfo;
  16454. };
  16455. // Clone
  16456. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16457. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16458. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16459. return result;
  16460. };
  16461. // Dispose
  16462. SubMesh.prototype.dispose = function () {
  16463. if (this._linesIndexBuffer) {
  16464. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16465. this._linesIndexBuffer = null;
  16466. }
  16467. // Remove from mesh
  16468. var index = this._mesh.subMeshes.indexOf(this);
  16469. this._mesh.subMeshes.splice(index, 1);
  16470. };
  16471. // Statics
  16472. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16473. var minVertexIndex = Number.MAX_VALUE;
  16474. var maxVertexIndex = -Number.MAX_VALUE;
  16475. renderingMesh = renderingMesh || mesh;
  16476. var indices = renderingMesh.getIndices();
  16477. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16478. var vertexIndex = indices[index];
  16479. if (vertexIndex < minVertexIndex)
  16480. minVertexIndex = vertexIndex;
  16481. if (vertexIndex > maxVertexIndex)
  16482. maxVertexIndex = vertexIndex;
  16483. }
  16484. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16485. };
  16486. return SubMesh;
  16487. })();
  16488. BABYLON.SubMesh = SubMesh;
  16489. })(BABYLON || (BABYLON = {}));
  16490. var BABYLON;
  16491. (function (BABYLON) {
  16492. var BaseTexture = (function () {
  16493. function BaseTexture(scene) {
  16494. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16495. this.hasAlpha = false;
  16496. this.getAlphaFromRGB = false;
  16497. this.level = 1;
  16498. this.isCube = false;
  16499. this.isRenderTarget = false;
  16500. this.animations = new Array();
  16501. this.coordinatesIndex = 0;
  16502. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16503. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16504. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16505. this.anisotropicFilteringLevel = 4;
  16506. this._scene = scene;
  16507. this._scene.textures.push(this);
  16508. }
  16509. BaseTexture.prototype.getScene = function () {
  16510. return this._scene;
  16511. };
  16512. BaseTexture.prototype.getTextureMatrix = function () {
  16513. return null;
  16514. };
  16515. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16516. return null;
  16517. };
  16518. BaseTexture.prototype.getInternalTexture = function () {
  16519. return this._texture;
  16520. };
  16521. BaseTexture.prototype.isReady = function () {
  16522. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16523. return true;
  16524. }
  16525. if (this._texture) {
  16526. return this._texture.isReady;
  16527. }
  16528. return false;
  16529. };
  16530. BaseTexture.prototype.getSize = function () {
  16531. if (this._texture._width) {
  16532. return { width: this._texture._width, height: this._texture._height };
  16533. }
  16534. if (this._texture._size) {
  16535. return { width: this._texture._size, height: this._texture._size };
  16536. }
  16537. return { width: 0, height: 0 };
  16538. };
  16539. BaseTexture.prototype.getBaseSize = function () {
  16540. if (!this.isReady())
  16541. return { width: 0, height: 0 };
  16542. if (this._texture._size) {
  16543. return { width: this._texture._size, height: this._texture._size };
  16544. }
  16545. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16546. };
  16547. BaseTexture.prototype.scale = function (ratio) {
  16548. };
  16549. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16550. get: function () {
  16551. return false;
  16552. },
  16553. enumerable: true,
  16554. configurable: true
  16555. });
  16556. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16557. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16558. for (var index = 0; index < texturesCache.length; index++) {
  16559. var texturesCacheEntry = texturesCache[index];
  16560. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16561. texturesCache.splice(index, 1);
  16562. return;
  16563. }
  16564. }
  16565. };
  16566. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16567. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16568. for (var index = 0; index < texturesCache.length; index++) {
  16569. var texturesCacheEntry = texturesCache[index];
  16570. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16571. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16572. texturesCacheEntry.references++;
  16573. return texturesCacheEntry;
  16574. }
  16575. }
  16576. }
  16577. return null;
  16578. };
  16579. BaseTexture.prototype.delayLoad = function () {
  16580. };
  16581. BaseTexture.prototype.releaseInternalTexture = function () {
  16582. if (!this._texture) {
  16583. return;
  16584. }
  16585. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16586. this._texture.references--;
  16587. // Final reference ?
  16588. if (this._texture.references === 0) {
  16589. var index = texturesCache.indexOf(this._texture);
  16590. texturesCache.splice(index, 1);
  16591. this._scene.getEngine()._releaseTexture(this._texture);
  16592. delete this._texture;
  16593. }
  16594. };
  16595. BaseTexture.prototype.clone = function () {
  16596. return null;
  16597. };
  16598. BaseTexture.prototype.dispose = function () {
  16599. // Remove from scene
  16600. var index = this._scene.textures.indexOf(this);
  16601. if (index >= 0) {
  16602. this._scene.textures.splice(index, 1);
  16603. }
  16604. if (this._texture === undefined) {
  16605. return;
  16606. }
  16607. this.releaseInternalTexture();
  16608. // Callback
  16609. if (this.onDispose) {
  16610. this.onDispose();
  16611. }
  16612. };
  16613. return BaseTexture;
  16614. })();
  16615. BABYLON.BaseTexture = BaseTexture;
  16616. })(BABYLON || (BABYLON = {}));
  16617. var BABYLON;
  16618. (function (BABYLON) {
  16619. var Texture = (function (_super) {
  16620. __extends(Texture, _super);
  16621. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16622. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16623. if (onLoad === void 0) { onLoad = null; }
  16624. if (onError === void 0) { onError = null; }
  16625. if (buffer === void 0) { buffer = null; }
  16626. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16627. _super.call(this, scene);
  16628. this.uOffset = 0;
  16629. this.vOffset = 0;
  16630. this.uScale = 1.0;
  16631. this.vScale = 1.0;
  16632. this.uAng = 0;
  16633. this.vAng = 0;
  16634. this.wAng = 0;
  16635. this.name = url;
  16636. this.url = url;
  16637. this._noMipmap = noMipmap;
  16638. this._invertY = invertY;
  16639. this._samplingMode = samplingMode;
  16640. this._buffer = buffer;
  16641. this._deleteBuffer = deleteBuffer;
  16642. if (!url) {
  16643. return;
  16644. }
  16645. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16646. if (!this._texture) {
  16647. if (!scene.useDelayedTextureLoading) {
  16648. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16649. if (deleteBuffer) {
  16650. delete this._buffer;
  16651. }
  16652. }
  16653. else {
  16654. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16655. }
  16656. }
  16657. else {
  16658. BABYLON.Tools.SetImmediate(function () {
  16659. if (onLoad) {
  16660. onLoad();
  16661. }
  16662. });
  16663. }
  16664. }
  16665. Texture.prototype.delayLoad = function () {
  16666. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16667. return;
  16668. }
  16669. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16670. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16671. if (!this._texture) {
  16672. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16673. if (this._deleteBuffer) {
  16674. delete this._buffer;
  16675. }
  16676. }
  16677. };
  16678. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16679. if (!this._texture) {
  16680. return;
  16681. }
  16682. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16683. };
  16684. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16685. x -= this.uOffset + 0.5;
  16686. y -= this.vOffset + 0.5;
  16687. z -= 0.5;
  16688. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16689. t.x *= this.uScale;
  16690. t.y *= this.vScale;
  16691. t.x += 0.5;
  16692. t.y += 0.5;
  16693. t.z += 0.5;
  16694. };
  16695. Texture.prototype.getTextureMatrix = function () {
  16696. if (this.uOffset === this._cachedUOffset &&
  16697. this.vOffset === this._cachedVOffset &&
  16698. this.uScale === this._cachedUScale &&
  16699. this.vScale === this._cachedVScale &&
  16700. this.uAng === this._cachedUAng &&
  16701. this.vAng === this._cachedVAng &&
  16702. this.wAng === this._cachedWAng) {
  16703. return this._cachedTextureMatrix;
  16704. }
  16705. this._cachedUOffset = this.uOffset;
  16706. this._cachedVOffset = this.vOffset;
  16707. this._cachedUScale = this.uScale;
  16708. this._cachedVScale = this.vScale;
  16709. this._cachedUAng = this.uAng;
  16710. this._cachedVAng = this.vAng;
  16711. this._cachedWAng = this.wAng;
  16712. if (!this._cachedTextureMatrix) {
  16713. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16714. this._rowGenerationMatrix = new BABYLON.Matrix();
  16715. this._t0 = BABYLON.Vector3.Zero();
  16716. this._t1 = BABYLON.Vector3.Zero();
  16717. this._t2 = BABYLON.Vector3.Zero();
  16718. }
  16719. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16720. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16721. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16722. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16723. this._t1.subtractInPlace(this._t0);
  16724. this._t2.subtractInPlace(this._t0);
  16725. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16726. this._cachedTextureMatrix.m[0] = this._t1.x;
  16727. this._cachedTextureMatrix.m[1] = this._t1.y;
  16728. this._cachedTextureMatrix.m[2] = this._t1.z;
  16729. this._cachedTextureMatrix.m[4] = this._t2.x;
  16730. this._cachedTextureMatrix.m[5] = this._t2.y;
  16731. this._cachedTextureMatrix.m[6] = this._t2.z;
  16732. this._cachedTextureMatrix.m[8] = this._t0.x;
  16733. this._cachedTextureMatrix.m[9] = this._t0.y;
  16734. this._cachedTextureMatrix.m[10] = this._t0.z;
  16735. return this._cachedTextureMatrix;
  16736. };
  16737. Texture.prototype.getReflectionTextureMatrix = function () {
  16738. if (this.uOffset === this._cachedUOffset &&
  16739. this.vOffset === this._cachedVOffset &&
  16740. this.uScale === this._cachedUScale &&
  16741. this.vScale === this._cachedVScale &&
  16742. this.coordinatesMode === this._cachedCoordinatesMode) {
  16743. return this._cachedTextureMatrix;
  16744. }
  16745. if (!this._cachedTextureMatrix) {
  16746. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16747. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16748. }
  16749. this._cachedCoordinatesMode = this.coordinatesMode;
  16750. switch (this.coordinatesMode) {
  16751. case Texture.SPHERICAL_MODE:
  16752. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16753. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16754. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16755. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16756. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16757. break;
  16758. case Texture.PLANAR_MODE:
  16759. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16760. this._cachedTextureMatrix[0] = this.uScale;
  16761. this._cachedTextureMatrix[5] = this.vScale;
  16762. this._cachedTextureMatrix[12] = this.uOffset;
  16763. this._cachedTextureMatrix[13] = this.vOffset;
  16764. break;
  16765. case Texture.PROJECTION_MODE:
  16766. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16767. this._projectionModeMatrix.m[0] = 0.5;
  16768. this._projectionModeMatrix.m[5] = -0.5;
  16769. this._projectionModeMatrix.m[10] = 0.0;
  16770. this._projectionModeMatrix.m[12] = 0.5;
  16771. this._projectionModeMatrix.m[13] = 0.5;
  16772. this._projectionModeMatrix.m[14] = 1.0;
  16773. this._projectionModeMatrix.m[15] = 1.0;
  16774. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16775. break;
  16776. default:
  16777. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16778. break;
  16779. }
  16780. return this._cachedTextureMatrix;
  16781. };
  16782. Texture.prototype.clone = function () {
  16783. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16784. // Base texture
  16785. newTexture.hasAlpha = this.hasAlpha;
  16786. newTexture.level = this.level;
  16787. newTexture.wrapU = this.wrapU;
  16788. newTexture.wrapV = this.wrapV;
  16789. newTexture.coordinatesIndex = this.coordinatesIndex;
  16790. newTexture.coordinatesMode = this.coordinatesMode;
  16791. // Texture
  16792. newTexture.uOffset = this.uOffset;
  16793. newTexture.vOffset = this.vOffset;
  16794. newTexture.uScale = this.uScale;
  16795. newTexture.vScale = this.vScale;
  16796. newTexture.uAng = this.uAng;
  16797. newTexture.vAng = this.vAng;
  16798. newTexture.wAng = this.wAng;
  16799. return newTexture;
  16800. };
  16801. // Statics
  16802. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16803. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16804. if (onLoad === void 0) { onLoad = null; }
  16805. if (onError === void 0) { onError = null; }
  16806. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16807. };
  16808. // Constants
  16809. Texture.NEAREST_SAMPLINGMODE = 1;
  16810. Texture.BILINEAR_SAMPLINGMODE = 2;
  16811. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16812. Texture.EXPLICIT_MODE = 0;
  16813. Texture.SPHERICAL_MODE = 1;
  16814. Texture.PLANAR_MODE = 2;
  16815. Texture.CUBIC_MODE = 3;
  16816. Texture.PROJECTION_MODE = 4;
  16817. Texture.SKYBOX_MODE = 5;
  16818. Texture.CLAMP_ADDRESSMODE = 0;
  16819. Texture.WRAP_ADDRESSMODE = 1;
  16820. Texture.MIRROR_ADDRESSMODE = 2;
  16821. return Texture;
  16822. })(BABYLON.BaseTexture);
  16823. BABYLON.Texture = Texture;
  16824. })(BABYLON || (BABYLON = {}));
  16825. var BABYLON;
  16826. (function (BABYLON) {
  16827. var CubeTexture = (function (_super) {
  16828. __extends(CubeTexture, _super);
  16829. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16830. _super.call(this, scene);
  16831. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16832. this.name = rootUrl;
  16833. this.url = rootUrl;
  16834. this._noMipmap = noMipmap;
  16835. this.hasAlpha = false;
  16836. this._texture = this._getFromCache(rootUrl, noMipmap);
  16837. if (!extensions) {
  16838. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16839. }
  16840. this._extensions = extensions;
  16841. if (!this._texture) {
  16842. if (!scene.useDelayedTextureLoading) {
  16843. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16844. }
  16845. else {
  16846. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16847. }
  16848. }
  16849. this.isCube = true;
  16850. this._textureMatrix = BABYLON.Matrix.Identity();
  16851. }
  16852. CubeTexture.prototype.clone = function () {
  16853. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16854. // Base texture
  16855. newTexture.level = this.level;
  16856. newTexture.wrapU = this.wrapU;
  16857. newTexture.wrapV = this.wrapV;
  16858. newTexture.coordinatesIndex = this.coordinatesIndex;
  16859. newTexture.coordinatesMode = this.coordinatesMode;
  16860. return newTexture;
  16861. };
  16862. // Methods
  16863. CubeTexture.prototype.delayLoad = function () {
  16864. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16865. return;
  16866. }
  16867. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16868. this._texture = this._getFromCache(this.url, this._noMipmap);
  16869. if (!this._texture) {
  16870. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16871. }
  16872. };
  16873. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16874. return this._textureMatrix;
  16875. };
  16876. return CubeTexture;
  16877. })(BABYLON.BaseTexture);
  16878. BABYLON.CubeTexture = CubeTexture;
  16879. })(BABYLON || (BABYLON = {}));
  16880. var BABYLON;
  16881. (function (BABYLON) {
  16882. var RenderTargetTexture = (function (_super) {
  16883. __extends(RenderTargetTexture, _super);
  16884. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16885. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16886. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16887. _super.call(this, null, scene, !generateMipMaps);
  16888. this.renderList = new Array();
  16889. this.renderParticles = true;
  16890. this.renderSprites = false;
  16891. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16892. this._currentRefreshId = -1;
  16893. this._refreshRate = 1;
  16894. this.name = name;
  16895. this.isRenderTarget = true;
  16896. this._size = size;
  16897. this._generateMipMaps = generateMipMaps;
  16898. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16899. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16900. // Rendering groups
  16901. this._renderingManager = new BABYLON.RenderingManager(scene);
  16902. }
  16903. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16904. this._currentRefreshId = -1;
  16905. };
  16906. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16907. get: function () {
  16908. return this._refreshRate;
  16909. },
  16910. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16911. set: function (value) {
  16912. this._refreshRate = value;
  16913. this.resetRefreshCounter();
  16914. },
  16915. enumerable: true,
  16916. configurable: true
  16917. });
  16918. RenderTargetTexture.prototype._shouldRender = function () {
  16919. if (this._currentRefreshId === -1) {
  16920. this._currentRefreshId = 1;
  16921. return true;
  16922. }
  16923. if (this.refreshRate === this._currentRefreshId) {
  16924. this._currentRefreshId = 1;
  16925. return true;
  16926. }
  16927. this._currentRefreshId++;
  16928. return false;
  16929. };
  16930. RenderTargetTexture.prototype.isReady = function () {
  16931. if (!this.getScene().renderTargetsEnabled) {
  16932. return false;
  16933. }
  16934. return _super.prototype.isReady.call(this);
  16935. };
  16936. RenderTargetTexture.prototype.getRenderSize = function () {
  16937. return this._size;
  16938. };
  16939. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16940. get: function () {
  16941. return true;
  16942. },
  16943. enumerable: true,
  16944. configurable: true
  16945. });
  16946. RenderTargetTexture.prototype.scale = function (ratio) {
  16947. var newSize = this._size * ratio;
  16948. this.resize(newSize, this._generateMipMaps);
  16949. };
  16950. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16951. this.releaseInternalTexture();
  16952. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16953. };
  16954. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16955. var scene = this.getScene();
  16956. var engine = scene.getEngine();
  16957. if (this._waitingRenderList) {
  16958. this.renderList = [];
  16959. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16960. var id = this._waitingRenderList[index];
  16961. this.renderList.push(scene.getMeshByID(id));
  16962. }
  16963. delete this._waitingRenderList;
  16964. }
  16965. if (this.renderList && this.renderList.length === 0) {
  16966. return;
  16967. }
  16968. // Bind
  16969. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16970. engine.bindFramebuffer(this._texture);
  16971. }
  16972. this._renderingManager.reset();
  16973. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16974. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16975. var mesh = currentRenderList[meshIndex];
  16976. if (mesh) {
  16977. if (!mesh.isReady()) {
  16978. // Reset _currentRefreshId
  16979. this.resetRefreshCounter();
  16980. continue;
  16981. }
  16982. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16983. mesh._activate(scene.getRenderId());
  16984. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16985. var subMesh = mesh.subMeshes[subIndex];
  16986. scene._activeIndices += subMesh.indexCount;
  16987. this._renderingManager.dispatch(subMesh);
  16988. }
  16989. }
  16990. }
  16991. }
  16992. if (this.onBeforeRender) {
  16993. this.onBeforeRender();
  16994. }
  16995. // Clear
  16996. if (this.onClear) {
  16997. this.onClear(engine);
  16998. }
  16999. else {
  17000. engine.clear(scene.clearColor, true, true);
  17001. }
  17002. if (!this._doNotChangeAspectRatio) {
  17003. scene.updateTransformMatrix(true);
  17004. }
  17005. // Render
  17006. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  17007. if (useCameraPostProcess) {
  17008. scene.postProcessManager._finalizeFrame(false, this._texture);
  17009. }
  17010. if (!this._doNotChangeAspectRatio) {
  17011. scene.updateTransformMatrix(true);
  17012. }
  17013. if (this.onAfterRender) {
  17014. this.onAfterRender();
  17015. }
  17016. // Dump ?
  17017. if (dumpForDebug) {
  17018. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17019. }
  17020. // Unbind
  17021. engine.unBindFramebuffer(this._texture);
  17022. if (this.onAfterUnbind) {
  17023. this.onAfterUnbind();
  17024. }
  17025. };
  17026. RenderTargetTexture.prototype.clone = function () {
  17027. var textureSize = this.getSize();
  17028. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17029. // Base texture
  17030. newTexture.hasAlpha = this.hasAlpha;
  17031. newTexture.level = this.level;
  17032. // RenderTarget Texture
  17033. newTexture.coordinatesMode = this.coordinatesMode;
  17034. newTexture.renderList = this.renderList.slice(0);
  17035. return newTexture;
  17036. };
  17037. return RenderTargetTexture;
  17038. })(BABYLON.Texture);
  17039. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17040. })(BABYLON || (BABYLON = {}));
  17041. var BABYLON;
  17042. (function (BABYLON) {
  17043. var ProceduralTexture = (function (_super) {
  17044. __extends(ProceduralTexture, _super);
  17045. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17046. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17047. _super.call(this, null, scene, !generateMipMaps);
  17048. this._currentRefreshId = -1;
  17049. this._refreshRate = 1;
  17050. this._vertexDeclaration = [2];
  17051. this._vertexStrideSize = 2 * 4;
  17052. this._uniforms = new Array();
  17053. this._samplers = new Array();
  17054. this._textures = new Array();
  17055. this._floats = new Array();
  17056. this._floatsArrays = {};
  17057. this._colors3 = new Array();
  17058. this._colors4 = new Array();
  17059. this._vectors2 = new Array();
  17060. this._vectors3 = new Array();
  17061. this._matrices = new Array();
  17062. this._fallbackTextureUsed = false;
  17063. scene._proceduralTextures.push(this);
  17064. this.name = name;
  17065. this.isRenderTarget = true;
  17066. this._size = size;
  17067. this._generateMipMaps = generateMipMaps;
  17068. this.setFragment(fragment);
  17069. this._fallbackTexture = fallbackTexture;
  17070. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17071. // VBO
  17072. var vertices = [];
  17073. vertices.push(1, 1);
  17074. vertices.push(-1, 1);
  17075. vertices.push(-1, -1);
  17076. vertices.push(1, -1);
  17077. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17078. // Indices
  17079. var indices = [];
  17080. indices.push(0);
  17081. indices.push(1);
  17082. indices.push(2);
  17083. indices.push(0);
  17084. indices.push(2);
  17085. indices.push(3);
  17086. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17087. }
  17088. ProceduralTexture.prototype.reset = function () {
  17089. if (this._effect === undefined) {
  17090. return;
  17091. }
  17092. var engine = this.getScene().getEngine();
  17093. engine._releaseEffect(this._effect);
  17094. };
  17095. ProceduralTexture.prototype.isReady = function () {
  17096. var _this = this;
  17097. var engine = this.getScene().getEngine();
  17098. var shaders;
  17099. if (!this._fragment) {
  17100. return false;
  17101. }
  17102. if (this._fallbackTextureUsed) {
  17103. return true;
  17104. }
  17105. if (this._fragment.fragmentElement !== undefined) {
  17106. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17107. }
  17108. else {
  17109. shaders = { vertex: "procedural", fragment: this._fragment };
  17110. }
  17111. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17112. _this.releaseInternalTexture();
  17113. if (_this._fallbackTexture) {
  17114. _this._texture = _this._fallbackTexture._texture;
  17115. _this._texture.references++;
  17116. }
  17117. _this._fallbackTextureUsed = true;
  17118. });
  17119. return this._effect.isReady();
  17120. };
  17121. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17122. this._currentRefreshId = -1;
  17123. };
  17124. ProceduralTexture.prototype.setFragment = function (fragment) {
  17125. this._fragment = fragment;
  17126. };
  17127. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17128. get: function () {
  17129. return this._refreshRate;
  17130. },
  17131. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17132. set: function (value) {
  17133. this._refreshRate = value;
  17134. this.resetRefreshCounter();
  17135. },
  17136. enumerable: true,
  17137. configurable: true
  17138. });
  17139. ProceduralTexture.prototype._shouldRender = function () {
  17140. if (!this.isReady() || !this._texture) {
  17141. return false;
  17142. }
  17143. if (this._fallbackTextureUsed) {
  17144. return false;
  17145. }
  17146. if (this._currentRefreshId === -1) {
  17147. this._currentRefreshId = 1;
  17148. return true;
  17149. }
  17150. if (this.refreshRate === this._currentRefreshId) {
  17151. this._currentRefreshId = 1;
  17152. return true;
  17153. }
  17154. this._currentRefreshId++;
  17155. return false;
  17156. };
  17157. ProceduralTexture.prototype.getRenderSize = function () {
  17158. return this._size;
  17159. };
  17160. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17161. if (this._fallbackTextureUsed) {
  17162. return;
  17163. }
  17164. this.releaseInternalTexture();
  17165. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17166. };
  17167. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17168. if (this._uniforms.indexOf(uniformName) === -1) {
  17169. this._uniforms.push(uniformName);
  17170. }
  17171. };
  17172. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17173. if (this._samplers.indexOf(name) === -1) {
  17174. this._samplers.push(name);
  17175. }
  17176. this._textures[name] = texture;
  17177. return this;
  17178. };
  17179. ProceduralTexture.prototype.setFloat = function (name, value) {
  17180. this._checkUniform(name);
  17181. this._floats[name] = value;
  17182. return this;
  17183. };
  17184. ProceduralTexture.prototype.setFloats = function (name, value) {
  17185. this._checkUniform(name);
  17186. this._floatsArrays[name] = value;
  17187. return this;
  17188. };
  17189. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17190. this._checkUniform(name);
  17191. this._colors3[name] = value;
  17192. return this;
  17193. };
  17194. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17195. this._checkUniform(name);
  17196. this._colors4[name] = value;
  17197. return this;
  17198. };
  17199. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17200. this._checkUniform(name);
  17201. this._vectors2[name] = value;
  17202. return this;
  17203. };
  17204. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17205. this._checkUniform(name);
  17206. this._vectors3[name] = value;
  17207. return this;
  17208. };
  17209. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17210. this._checkUniform(name);
  17211. this._matrices[name] = value;
  17212. return this;
  17213. };
  17214. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17215. var scene = this.getScene();
  17216. var engine = scene.getEngine();
  17217. engine.bindFramebuffer(this._texture);
  17218. // Clear
  17219. engine.clear(scene.clearColor, true, true);
  17220. // Render
  17221. engine.enableEffect(this._effect);
  17222. engine.setState(false);
  17223. // Texture
  17224. for (var name in this._textures) {
  17225. this._effect.setTexture(name, this._textures[name]);
  17226. }
  17227. // Float
  17228. for (name in this._floats) {
  17229. this._effect.setFloat(name, this._floats[name]);
  17230. }
  17231. // Floats
  17232. for (name in this._floatsArrays) {
  17233. this._effect.setArray(name, this._floatsArrays[name]);
  17234. }
  17235. // Color3
  17236. for (name in this._colors3) {
  17237. this._effect.setColor3(name, this._colors3[name]);
  17238. }
  17239. // Color4
  17240. for (name in this._colors4) {
  17241. var color = this._colors4[name];
  17242. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17243. }
  17244. // Vector2
  17245. for (name in this._vectors2) {
  17246. this._effect.setVector2(name, this._vectors2[name]);
  17247. }
  17248. // Vector3
  17249. for (name in this._vectors3) {
  17250. this._effect.setVector3(name, this._vectors3[name]);
  17251. }
  17252. // Matrix
  17253. for (name in this._matrices) {
  17254. this._effect.setMatrix(name, this._matrices[name]);
  17255. }
  17256. // VBOs
  17257. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17258. // Draw order
  17259. engine.draw(true, 0, 6);
  17260. // Unbind
  17261. engine.unBindFramebuffer(this._texture);
  17262. };
  17263. ProceduralTexture.prototype.clone = function () {
  17264. var textureSize = this.getSize();
  17265. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17266. // Base texture
  17267. newTexture.hasAlpha = this.hasAlpha;
  17268. newTexture.level = this.level;
  17269. // RenderTarget Texture
  17270. newTexture.coordinatesMode = this.coordinatesMode;
  17271. return newTexture;
  17272. };
  17273. ProceduralTexture.prototype.dispose = function () {
  17274. var index = this.getScene()._proceduralTextures.indexOf(this);
  17275. if (index >= 0) {
  17276. this.getScene()._proceduralTextures.splice(index, 1);
  17277. }
  17278. _super.prototype.dispose.call(this);
  17279. };
  17280. return ProceduralTexture;
  17281. })(BABYLON.Texture);
  17282. BABYLON.ProceduralTexture = ProceduralTexture;
  17283. })(BABYLON || (BABYLON = {}));
  17284. var BABYLON;
  17285. (function (BABYLON) {
  17286. var MirrorTexture = (function (_super) {
  17287. __extends(MirrorTexture, _super);
  17288. function MirrorTexture(name, size, scene, generateMipMaps) {
  17289. var _this = this;
  17290. _super.call(this, name, size, scene, generateMipMaps, true);
  17291. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17292. this._transformMatrix = BABYLON.Matrix.Zero();
  17293. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17294. this.onBeforeRender = function () {
  17295. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17296. _this._savedViewMatrix = scene.getViewMatrix();
  17297. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17298. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17299. scene.clipPlane = _this.mirrorPlane;
  17300. scene.getEngine().cullBackFaces = false;
  17301. };
  17302. this.onAfterRender = function () {
  17303. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17304. scene.getEngine().cullBackFaces = true;
  17305. delete scene.clipPlane;
  17306. };
  17307. }
  17308. MirrorTexture.prototype.clone = function () {
  17309. var textureSize = this.getSize();
  17310. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17311. // Base texture
  17312. newTexture.hasAlpha = this.hasAlpha;
  17313. newTexture.level = this.level;
  17314. // Mirror Texture
  17315. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17316. newTexture.renderList = this.renderList.slice(0);
  17317. return newTexture;
  17318. };
  17319. return MirrorTexture;
  17320. })(BABYLON.RenderTargetTexture);
  17321. BABYLON.MirrorTexture = MirrorTexture;
  17322. })(BABYLON || (BABYLON = {}));
  17323. var BABYLON;
  17324. (function (BABYLON) {
  17325. var DynamicTexture = (function (_super) {
  17326. __extends(DynamicTexture, _super);
  17327. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17328. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17329. _super.call(this, null, scene, !generateMipMaps);
  17330. this.name = name;
  17331. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17332. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17333. this._generateMipMaps = generateMipMaps;
  17334. if (options.getContext) {
  17335. this._canvas = options;
  17336. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17337. }
  17338. else {
  17339. this._canvas = document.createElement("canvas");
  17340. if (options.width) {
  17341. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17342. }
  17343. else {
  17344. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17345. }
  17346. }
  17347. var textureSize = this.getSize();
  17348. this._canvas.width = textureSize.width;
  17349. this._canvas.height = textureSize.height;
  17350. this._context = this._canvas.getContext("2d");
  17351. }
  17352. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17353. get: function () {
  17354. return true;
  17355. },
  17356. enumerable: true,
  17357. configurable: true
  17358. });
  17359. DynamicTexture.prototype.scale = function (ratio) {
  17360. var textureSize = this.getSize();
  17361. textureSize.width *= ratio;
  17362. textureSize.height *= ratio;
  17363. this._canvas.width = textureSize.width;
  17364. this._canvas.height = textureSize.height;
  17365. this.releaseInternalTexture();
  17366. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17367. };
  17368. DynamicTexture.prototype.getContext = function () {
  17369. return this._context;
  17370. };
  17371. DynamicTexture.prototype.clear = function () {
  17372. var size = this.getSize();
  17373. this._context.fillRect(0, 0, size.width, size.height);
  17374. };
  17375. DynamicTexture.prototype.update = function (invertY) {
  17376. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17377. };
  17378. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17379. if (update === void 0) { update = true; }
  17380. var size = this.getSize();
  17381. if (clearColor) {
  17382. this._context.fillStyle = clearColor;
  17383. this._context.fillRect(0, 0, size.width, size.height);
  17384. }
  17385. this._context.font = font;
  17386. if (x === null) {
  17387. var textSize = this._context.measureText(text);
  17388. x = (size.width - textSize.width) / 2;
  17389. }
  17390. this._context.fillStyle = color;
  17391. this._context.fillText(text, x, y);
  17392. if (update) {
  17393. this.update(invertY);
  17394. }
  17395. };
  17396. DynamicTexture.prototype.clone = function () {
  17397. var textureSize = this.getSize();
  17398. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17399. // Base texture
  17400. newTexture.hasAlpha = this.hasAlpha;
  17401. newTexture.level = this.level;
  17402. // Dynamic Texture
  17403. newTexture.wrapU = this.wrapU;
  17404. newTexture.wrapV = this.wrapV;
  17405. return newTexture;
  17406. };
  17407. return DynamicTexture;
  17408. })(BABYLON.Texture);
  17409. BABYLON.DynamicTexture = DynamicTexture;
  17410. })(BABYLON || (BABYLON = {}));
  17411. var BABYLON;
  17412. (function (BABYLON) {
  17413. var VideoTexture = (function (_super) {
  17414. __extends(VideoTexture, _super);
  17415. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17416. var _this = this;
  17417. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17418. if (invertY === void 0) { invertY = false; }
  17419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17420. _super.call(this, null, scene, !generateMipMaps, invertY);
  17421. this._autoLaunch = true;
  17422. this.name = name;
  17423. this.video = document.createElement("video");
  17424. this.video.autoplay = false;
  17425. this.video.loop = true;
  17426. this.video.addEventListener("canplaythrough", function () {
  17427. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17428. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17429. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17430. }
  17431. else {
  17432. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17433. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17434. generateMipMaps = false;
  17435. }
  17436. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17437. _this._texture.isReady = true;
  17438. });
  17439. urls.forEach(function (url) {
  17440. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17441. var source = document.createElement("source");
  17442. source.src = url;
  17443. _this.video.appendChild(source);
  17444. });
  17445. this._lastUpdate = BABYLON.Tools.Now;
  17446. }
  17447. VideoTexture.prototype.update = function () {
  17448. if (this._autoLaunch) {
  17449. this._autoLaunch = false;
  17450. this.video.play();
  17451. }
  17452. var now = BABYLON.Tools.Now;
  17453. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17454. return false;
  17455. }
  17456. this._lastUpdate = now;
  17457. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17458. return true;
  17459. };
  17460. return VideoTexture;
  17461. })(BABYLON.Texture);
  17462. BABYLON.VideoTexture = VideoTexture;
  17463. })(BABYLON || (BABYLON = {}));
  17464. var BABYLON;
  17465. (function (BABYLON) {
  17466. var CustomProceduralTexture = (function (_super) {
  17467. __extends(CustomProceduralTexture, _super);
  17468. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17469. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17470. this._animate = true;
  17471. this._time = 0;
  17472. this._texturePath = texturePath;
  17473. //Try to load json
  17474. this.loadJson(texturePath);
  17475. this.refreshRate = 1;
  17476. }
  17477. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17478. var _this = this;
  17479. var that = this;
  17480. function noConfigFile() {
  17481. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17482. try {
  17483. that.setFragment(that._texturePath);
  17484. }
  17485. catch (ex) {
  17486. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17487. }
  17488. }
  17489. var configFileUrl = jsonUrl + "/config.json";
  17490. var xhr = new XMLHttpRequest();
  17491. xhr.open("GET", configFileUrl, true);
  17492. xhr.addEventListener("load", function () {
  17493. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17494. try {
  17495. _this._config = JSON.parse(xhr.response);
  17496. _this.updateShaderUniforms();
  17497. _this.updateTextures();
  17498. _this.setFragment(_this._texturePath + "/custom");
  17499. _this._animate = _this._config.animate;
  17500. _this.refreshRate = _this._config.refreshrate;
  17501. }
  17502. catch (ex) {
  17503. noConfigFile();
  17504. }
  17505. }
  17506. else {
  17507. noConfigFile();
  17508. }
  17509. }, false);
  17510. xhr.addEventListener("error", function () {
  17511. noConfigFile();
  17512. }, false);
  17513. try {
  17514. xhr.send();
  17515. }
  17516. catch (ex) {
  17517. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17518. }
  17519. };
  17520. CustomProceduralTexture.prototype.isReady = function () {
  17521. if (!_super.prototype.isReady.call(this)) {
  17522. return false;
  17523. }
  17524. for (var name in this._textures) {
  17525. var texture = this._textures[name];
  17526. if (!texture.isReady()) {
  17527. return false;
  17528. }
  17529. }
  17530. return true;
  17531. };
  17532. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17533. if (this._animate) {
  17534. this._time += this.getScene().getAnimationRatio() * 0.03;
  17535. this.updateShaderUniforms();
  17536. }
  17537. _super.prototype.render.call(this, useCameraPostProcess);
  17538. };
  17539. CustomProceduralTexture.prototype.updateTextures = function () {
  17540. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17541. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17542. }
  17543. };
  17544. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17545. if (this._config) {
  17546. for (var j = 0; j < this._config.uniforms.length; j++) {
  17547. var uniform = this._config.uniforms[j];
  17548. switch (uniform.type) {
  17549. case "float":
  17550. this.setFloat(uniform.name, uniform.value);
  17551. break;
  17552. case "color3":
  17553. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17554. break;
  17555. case "color4":
  17556. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17557. break;
  17558. case "vector2":
  17559. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17560. break;
  17561. case "vector3":
  17562. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17563. break;
  17564. }
  17565. }
  17566. }
  17567. this.setFloat("time", this._time);
  17568. };
  17569. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17570. get: function () {
  17571. return this._animate;
  17572. },
  17573. set: function (value) {
  17574. this._animate = value;
  17575. },
  17576. enumerable: true,
  17577. configurable: true
  17578. });
  17579. return CustomProceduralTexture;
  17580. })(BABYLON.ProceduralTexture);
  17581. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17582. })(BABYLON || (BABYLON = {}));
  17583. var BABYLON;
  17584. (function (BABYLON) {
  17585. var WoodProceduralTexture = (function (_super) {
  17586. __extends(WoodProceduralTexture, _super);
  17587. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17588. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17589. this._ampScale = 100.0;
  17590. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17591. this.updateShaderUniforms();
  17592. this.refreshRate = 0;
  17593. }
  17594. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17595. this.setFloat("ampScale", this._ampScale);
  17596. this.setColor3("woodColor", this._woodColor);
  17597. };
  17598. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17599. get: function () {
  17600. return this._ampScale;
  17601. },
  17602. set: function (value) {
  17603. this._ampScale = value;
  17604. this.updateShaderUniforms();
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17610. get: function () {
  17611. return this._woodColor;
  17612. },
  17613. set: function (value) {
  17614. this._woodColor = value;
  17615. this.updateShaderUniforms();
  17616. },
  17617. enumerable: true,
  17618. configurable: true
  17619. });
  17620. return WoodProceduralTexture;
  17621. })(BABYLON.ProceduralTexture);
  17622. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17623. var FireProceduralTexture = (function (_super) {
  17624. __extends(FireProceduralTexture, _super);
  17625. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17626. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17627. this._time = 0.0;
  17628. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17629. this._autoGenerateTime = true;
  17630. this._alphaThreshold = 0.5;
  17631. this._fireColors = FireProceduralTexture.RedFireColors;
  17632. this.updateShaderUniforms();
  17633. this.refreshRate = 1;
  17634. }
  17635. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17636. this.setFloat("time", this._time);
  17637. this.setVector2("speed", this._speed);
  17638. this.setColor3("c1", this._fireColors[0]);
  17639. this.setColor3("c2", this._fireColors[1]);
  17640. this.setColor3("c3", this._fireColors[2]);
  17641. this.setColor3("c4", this._fireColors[3]);
  17642. this.setColor3("c5", this._fireColors[4]);
  17643. this.setColor3("c6", this._fireColors[5]);
  17644. this.setFloat("alphaThreshold", this._alphaThreshold);
  17645. };
  17646. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17647. if (this._autoGenerateTime) {
  17648. this._time += this.getScene().getAnimationRatio() * 0.03;
  17649. this.updateShaderUniforms();
  17650. }
  17651. _super.prototype.render.call(this, useCameraPostProcess);
  17652. };
  17653. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17654. get: function () {
  17655. return [
  17656. new BABYLON.Color3(0.5, 0.0, 1.0),
  17657. new BABYLON.Color3(0.9, 0.0, 1.0),
  17658. new BABYLON.Color3(0.2, 0.0, 1.0),
  17659. new BABYLON.Color3(1.0, 0.9, 1.0),
  17660. new BABYLON.Color3(0.1, 0.1, 1.0),
  17661. new BABYLON.Color3(0.9, 0.9, 1.0)
  17662. ];
  17663. },
  17664. enumerable: true,
  17665. configurable: true
  17666. });
  17667. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17668. get: function () {
  17669. return [
  17670. new BABYLON.Color3(0.5, 1.0, 0.0),
  17671. new BABYLON.Color3(0.5, 1.0, 0.0),
  17672. new BABYLON.Color3(0.3, 0.4, 0.0),
  17673. new BABYLON.Color3(0.5, 1.0, 0.0),
  17674. new BABYLON.Color3(0.2, 0.0, 0.0),
  17675. new BABYLON.Color3(0.5, 1.0, 0.0)
  17676. ];
  17677. },
  17678. enumerable: true,
  17679. configurable: true
  17680. });
  17681. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17682. get: function () {
  17683. return [
  17684. new BABYLON.Color3(0.5, 0.0, 0.1),
  17685. new BABYLON.Color3(0.9, 0.0, 0.0),
  17686. new BABYLON.Color3(0.2, 0.0, 0.0),
  17687. new BABYLON.Color3(1.0, 0.9, 0.0),
  17688. new BABYLON.Color3(0.1, 0.1, 0.1),
  17689. new BABYLON.Color3(0.9, 0.9, 0.9)
  17690. ];
  17691. },
  17692. enumerable: true,
  17693. configurable: true
  17694. });
  17695. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17696. get: function () {
  17697. return [
  17698. new BABYLON.Color3(0.1, 0.0, 0.5),
  17699. new BABYLON.Color3(0.0, 0.0, 0.5),
  17700. new BABYLON.Color3(0.1, 0.0, 0.2),
  17701. new BABYLON.Color3(0.0, 0.0, 1.0),
  17702. new BABYLON.Color3(0.1, 0.2, 0.3),
  17703. new BABYLON.Color3(0.0, 0.2, 0.9)
  17704. ];
  17705. },
  17706. enumerable: true,
  17707. configurable: true
  17708. });
  17709. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17710. get: function () {
  17711. return this._fireColors;
  17712. },
  17713. set: function (value) {
  17714. this._fireColors = value;
  17715. this.updateShaderUniforms();
  17716. },
  17717. enumerable: true,
  17718. configurable: true
  17719. });
  17720. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17721. get: function () {
  17722. return this._time;
  17723. },
  17724. set: function (value) {
  17725. this._time = value;
  17726. this.updateShaderUniforms();
  17727. },
  17728. enumerable: true,
  17729. configurable: true
  17730. });
  17731. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17732. get: function () {
  17733. return this._speed;
  17734. },
  17735. set: function (value) {
  17736. this._speed = value;
  17737. this.updateShaderUniforms();
  17738. },
  17739. enumerable: true,
  17740. configurable: true
  17741. });
  17742. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17743. get: function () {
  17744. return this._alphaThreshold;
  17745. },
  17746. set: function (value) {
  17747. this._alphaThreshold = value;
  17748. this.updateShaderUniforms();
  17749. },
  17750. enumerable: true,
  17751. configurable: true
  17752. });
  17753. return FireProceduralTexture;
  17754. })(BABYLON.ProceduralTexture);
  17755. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17756. var CloudProceduralTexture = (function (_super) {
  17757. __extends(CloudProceduralTexture, _super);
  17758. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17759. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17760. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17761. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17762. this.updateShaderUniforms();
  17763. this.refreshRate = 0;
  17764. }
  17765. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17766. this.setColor4("skyColor", this._skyColor);
  17767. this.setColor4("cloudColor", this._cloudColor);
  17768. };
  17769. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17770. get: function () {
  17771. return this._skyColor;
  17772. },
  17773. set: function (value) {
  17774. this._skyColor = value;
  17775. this.updateShaderUniforms();
  17776. },
  17777. enumerable: true,
  17778. configurable: true
  17779. });
  17780. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17781. get: function () {
  17782. return this._cloudColor;
  17783. },
  17784. set: function (value) {
  17785. this._cloudColor = value;
  17786. this.updateShaderUniforms();
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. return CloudProceduralTexture;
  17792. })(BABYLON.ProceduralTexture);
  17793. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17794. var GrassProceduralTexture = (function (_super) {
  17795. __extends(GrassProceduralTexture, _super);
  17796. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17797. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17798. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17799. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17800. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17801. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17802. this._grassColors = [
  17803. new BABYLON.Color3(0.29, 0.38, 0.02),
  17804. new BABYLON.Color3(0.36, 0.49, 0.09),
  17805. new BABYLON.Color3(0.51, 0.6, 0.28)
  17806. ];
  17807. this.updateShaderUniforms();
  17808. this.refreshRate = 0;
  17809. }
  17810. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17811. this.setColor3("herb1Color", this._grassColors[0]);
  17812. this.setColor3("herb2Color", this._grassColors[1]);
  17813. this.setColor3("herb3Color", this._grassColors[2]);
  17814. this.setColor3("groundColor", this._groundColor);
  17815. };
  17816. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17817. get: function () {
  17818. return this._grassColors;
  17819. },
  17820. set: function (value) {
  17821. this._grassColors = value;
  17822. this.updateShaderUniforms();
  17823. },
  17824. enumerable: true,
  17825. configurable: true
  17826. });
  17827. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17828. get: function () {
  17829. return this._groundColor;
  17830. },
  17831. set: function (value) {
  17832. this.groundColor = value;
  17833. this.updateShaderUniforms();
  17834. },
  17835. enumerable: true,
  17836. configurable: true
  17837. });
  17838. return GrassProceduralTexture;
  17839. })(BABYLON.ProceduralTexture);
  17840. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17841. var RoadProceduralTexture = (function (_super) {
  17842. __extends(RoadProceduralTexture, _super);
  17843. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17844. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17845. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17846. this.updateShaderUniforms();
  17847. this.refreshRate = 0;
  17848. }
  17849. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17850. this.setColor3("roadColor", this._roadColor);
  17851. };
  17852. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17853. get: function () {
  17854. return this._roadColor;
  17855. },
  17856. set: function (value) {
  17857. this._roadColor = value;
  17858. this.updateShaderUniforms();
  17859. },
  17860. enumerable: true,
  17861. configurable: true
  17862. });
  17863. return RoadProceduralTexture;
  17864. })(BABYLON.ProceduralTexture);
  17865. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17866. var BrickProceduralTexture = (function (_super) {
  17867. __extends(BrickProceduralTexture, _super);
  17868. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17869. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17870. this._numberOfBricksHeight = 15;
  17871. this._numberOfBricksWidth = 5;
  17872. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17873. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17874. this.updateShaderUniforms();
  17875. this.refreshRate = 0;
  17876. }
  17877. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17878. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17879. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17880. this.setColor3("brickColor", this._brickColor);
  17881. this.setColor3("jointColor", this._jointColor);
  17882. };
  17883. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17884. get: function () {
  17885. return this._numberOfBricksHeight;
  17886. },
  17887. set: function (value) {
  17888. this._numberOfBricksHeight = value;
  17889. this.updateShaderUniforms();
  17890. },
  17891. enumerable: true,
  17892. configurable: true
  17893. });
  17894. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17895. get: function () {
  17896. return this._numberOfBricksWidth;
  17897. },
  17898. set: function (value) {
  17899. this._numberOfBricksWidth = value;
  17900. this.updateShaderUniforms();
  17901. },
  17902. enumerable: true,
  17903. configurable: true
  17904. });
  17905. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17906. get: function () {
  17907. return this._jointColor;
  17908. },
  17909. set: function (value) {
  17910. this._jointColor = value;
  17911. this.updateShaderUniforms();
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17917. get: function () {
  17918. return this._brickColor;
  17919. },
  17920. set: function (value) {
  17921. this._brickColor = value;
  17922. this.updateShaderUniforms();
  17923. },
  17924. enumerable: true,
  17925. configurable: true
  17926. });
  17927. return BrickProceduralTexture;
  17928. })(BABYLON.ProceduralTexture);
  17929. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17930. var MarbleProceduralTexture = (function (_super) {
  17931. __extends(MarbleProceduralTexture, _super);
  17932. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17933. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17934. this._numberOfTilesHeight = 3;
  17935. this._numberOfTilesWidth = 3;
  17936. this._amplitude = 9.0;
  17937. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17938. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17939. this.updateShaderUniforms();
  17940. this.refreshRate = 0;
  17941. }
  17942. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17943. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17944. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17945. this.setFloat("amplitude", this._amplitude);
  17946. this.setColor3("marbleColor", this._marbleColor);
  17947. this.setColor3("jointColor", this._jointColor);
  17948. };
  17949. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17950. get: function () {
  17951. return this._numberOfTilesHeight;
  17952. },
  17953. set: function (value) {
  17954. this._numberOfTilesHeight = value;
  17955. this.updateShaderUniforms();
  17956. },
  17957. enumerable: true,
  17958. configurable: true
  17959. });
  17960. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17961. get: function () {
  17962. return this._numberOfTilesWidth;
  17963. },
  17964. set: function (value) {
  17965. this._numberOfTilesWidth = value;
  17966. this.updateShaderUniforms();
  17967. },
  17968. enumerable: true,
  17969. configurable: true
  17970. });
  17971. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17972. get: function () {
  17973. return this._jointColor;
  17974. },
  17975. set: function (value) {
  17976. this._jointColor = value;
  17977. this.updateShaderUniforms();
  17978. },
  17979. enumerable: true,
  17980. configurable: true
  17981. });
  17982. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17983. get: function () {
  17984. return this._marbleColor;
  17985. },
  17986. set: function (value) {
  17987. this._marbleColor = value;
  17988. this.updateShaderUniforms();
  17989. },
  17990. enumerable: true,
  17991. configurable: true
  17992. });
  17993. return MarbleProceduralTexture;
  17994. })(BABYLON.ProceduralTexture);
  17995. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17996. })(BABYLON || (BABYLON = {}));
  17997. var BABYLON;
  17998. (function (BABYLON) {
  17999. var EffectFallbacks = (function () {
  18000. function EffectFallbacks() {
  18001. this._defines = {};
  18002. this._currentRank = 32;
  18003. this._maxRank = -1;
  18004. }
  18005. EffectFallbacks.prototype.addFallback = function (rank, define) {
  18006. if (!this._defines[rank]) {
  18007. if (rank < this._currentRank) {
  18008. this._currentRank = rank;
  18009. }
  18010. if (rank > this._maxRank) {
  18011. this._maxRank = rank;
  18012. }
  18013. this._defines[rank] = new Array();
  18014. }
  18015. this._defines[rank].push(define);
  18016. };
  18017. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18018. get: function () {
  18019. return this._currentRank <= this._maxRank;
  18020. },
  18021. enumerable: true,
  18022. configurable: true
  18023. });
  18024. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18025. var currentFallbacks = this._defines[this._currentRank];
  18026. for (var index = 0; index < currentFallbacks.length; index++) {
  18027. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18028. }
  18029. this._currentRank++;
  18030. return currentDefines;
  18031. };
  18032. return EffectFallbacks;
  18033. })();
  18034. BABYLON.EffectFallbacks = EffectFallbacks;
  18035. var Effect = (function () {
  18036. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18037. var _this = this;
  18038. this._isReady = false;
  18039. this._compilationError = "";
  18040. this._valueCache = [];
  18041. this._engine = engine;
  18042. this.name = baseName;
  18043. this.defines = defines;
  18044. this._uniformsNames = uniformsNames.concat(samplers);
  18045. this._samplers = samplers;
  18046. this._attributesNames = attributesNames;
  18047. this.onError = onError;
  18048. this.onCompiled = onCompiled;
  18049. var vertexSource;
  18050. var fragmentSource;
  18051. if (baseName.vertexElement) {
  18052. vertexSource = document.getElementById(baseName.vertexElement);
  18053. if (!vertexSource) {
  18054. vertexSource = baseName.vertexElement;
  18055. }
  18056. }
  18057. else {
  18058. vertexSource = baseName.vertex || baseName;
  18059. }
  18060. if (baseName.fragmentElement) {
  18061. fragmentSource = document.getElementById(baseName.fragmentElement);
  18062. if (!fragmentSource) {
  18063. fragmentSource = baseName.fragmentElement;
  18064. }
  18065. }
  18066. else {
  18067. fragmentSource = baseName.fragment || baseName;
  18068. }
  18069. this._loadVertexShader(vertexSource, function (vertexCode) {
  18070. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18071. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18072. });
  18073. });
  18074. }
  18075. // Properties
  18076. Effect.prototype.isReady = function () {
  18077. return this._isReady;
  18078. };
  18079. Effect.prototype.getProgram = function () {
  18080. return this._program;
  18081. };
  18082. Effect.prototype.getAttributesNames = function () {
  18083. return this._attributesNames;
  18084. };
  18085. Effect.prototype.getAttributeLocation = function (index) {
  18086. return this._attributes[index];
  18087. };
  18088. Effect.prototype.getAttributeLocationByName = function (name) {
  18089. var index = this._attributesNames.indexOf(name);
  18090. return this._attributes[index];
  18091. };
  18092. Effect.prototype.getAttributesCount = function () {
  18093. return this._attributes.length;
  18094. };
  18095. Effect.prototype.getUniformIndex = function (uniformName) {
  18096. return this._uniformsNames.indexOf(uniformName);
  18097. };
  18098. Effect.prototype.getUniform = function (uniformName) {
  18099. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18100. };
  18101. Effect.prototype.getSamplers = function () {
  18102. return this._samplers;
  18103. };
  18104. Effect.prototype.getCompilationError = function () {
  18105. return this._compilationError;
  18106. };
  18107. // Methods
  18108. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18109. // DOM element ?
  18110. if (vertex instanceof HTMLElement) {
  18111. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18112. callback(vertexCode);
  18113. return;
  18114. }
  18115. // Is in local store ?
  18116. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18117. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18118. return;
  18119. }
  18120. var vertexShaderUrl;
  18121. if (vertex[0] === "." || vertex[0] === "/") {
  18122. vertexShaderUrl = vertex;
  18123. }
  18124. else {
  18125. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18126. }
  18127. // Vertex shader
  18128. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18129. };
  18130. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18131. // DOM element ?
  18132. if (fragment instanceof HTMLElement) {
  18133. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18134. callback(fragmentCode);
  18135. return;
  18136. }
  18137. // Is in local store ?
  18138. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18139. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18140. return;
  18141. }
  18142. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18143. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18144. return;
  18145. }
  18146. var fragmentShaderUrl;
  18147. if (fragment[0] === "." || fragment[0] === "/") {
  18148. fragmentShaderUrl = fragment;
  18149. }
  18150. else {
  18151. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18152. }
  18153. // Fragment shader
  18154. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18155. };
  18156. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18157. try {
  18158. var engine = this._engine;
  18159. if (!engine.getCaps().highPrecisionShaderSupported) {
  18160. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18161. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18162. }
  18163. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18164. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18165. this._attributes = engine.getAttributes(this._program, attributesNames);
  18166. for (var index = 0; index < this._samplers.length; index++) {
  18167. var sampler = this.getUniform(this._samplers[index]);
  18168. if (sampler == null) {
  18169. this._samplers.splice(index, 1);
  18170. index--;
  18171. }
  18172. }
  18173. engine.bindSamplers(this);
  18174. this._isReady = true;
  18175. if (this.onCompiled) {
  18176. this.onCompiled(this);
  18177. }
  18178. }
  18179. catch (e) {
  18180. // Is it a problem with precision?
  18181. if (e.message.indexOf("highp") !== -1) {
  18182. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18183. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18184. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18185. return;
  18186. }
  18187. // Let's go through fallbacks then
  18188. if (fallbacks && fallbacks.isMoreFallbacks) {
  18189. defines = fallbacks.reduce(defines);
  18190. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18191. }
  18192. else {
  18193. BABYLON.Tools.Error("Unable to compile effect: ");
  18194. if (this.name.vertexElement) {
  18195. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18196. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18197. }
  18198. else if (this.name.vertex) {
  18199. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18200. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18201. }
  18202. else {
  18203. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18204. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18205. }
  18206. BABYLON.Tools.Error("Defines: " + defines);
  18207. BABYLON.Tools.Error("Error: " + e.message);
  18208. this._compilationError = e.message;
  18209. if (this.onError) {
  18210. this.onError(this, this._compilationError);
  18211. }
  18212. }
  18213. }
  18214. };
  18215. Effect.prototype._bindTexture = function (channel, texture) {
  18216. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18217. };
  18218. Effect.prototype.setTexture = function (channel, texture) {
  18219. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18220. };
  18221. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18222. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18223. };
  18224. //public _cacheMatrix(uniformName, matrix) {
  18225. // if (!this._valueCache[uniformName]) {
  18226. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18227. // }
  18228. // for (var index = 0; index < 16; index++) {
  18229. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18230. // }
  18231. //};
  18232. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18233. if (!this._valueCache[uniformName]) {
  18234. this._valueCache[uniformName] = [x, y];
  18235. return;
  18236. }
  18237. this._valueCache[uniformName][0] = x;
  18238. this._valueCache[uniformName][1] = y;
  18239. };
  18240. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18241. if (!this._valueCache[uniformName]) {
  18242. this._valueCache[uniformName] = [x, y, z];
  18243. return;
  18244. }
  18245. this._valueCache[uniformName][0] = x;
  18246. this._valueCache[uniformName][1] = y;
  18247. this._valueCache[uniformName][2] = z;
  18248. };
  18249. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18250. if (!this._valueCache[uniformName]) {
  18251. this._valueCache[uniformName] = [x, y, z, w];
  18252. return;
  18253. }
  18254. this._valueCache[uniformName][0] = x;
  18255. this._valueCache[uniformName][1] = y;
  18256. this._valueCache[uniformName][2] = z;
  18257. this._valueCache[uniformName][3] = w;
  18258. };
  18259. Effect.prototype.setArray = function (uniformName, array) {
  18260. this._engine.setArray(this.getUniform(uniformName), array);
  18261. return this;
  18262. };
  18263. Effect.prototype.setArray2 = function (uniformName, array) {
  18264. this._engine.setArray2(this.getUniform(uniformName), array);
  18265. return this;
  18266. };
  18267. Effect.prototype.setArray3 = function (uniformName, array) {
  18268. this._engine.setArray3(this.getUniform(uniformName), array);
  18269. return this;
  18270. };
  18271. Effect.prototype.setArray4 = function (uniformName, array) {
  18272. this._engine.setArray4(this.getUniform(uniformName), array);
  18273. return this;
  18274. };
  18275. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18276. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18277. return this;
  18278. };
  18279. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18280. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18281. // return;
  18282. //this._cacheMatrix(uniformName, matrix);
  18283. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18284. return this;
  18285. };
  18286. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18287. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18288. return this;
  18289. };
  18290. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18291. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18292. return this;
  18293. };
  18294. Effect.prototype.setFloat = function (uniformName, value) {
  18295. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18296. return this;
  18297. this._valueCache[uniformName] = value;
  18298. this._engine.setFloat(this.getUniform(uniformName), value);
  18299. return this;
  18300. };
  18301. Effect.prototype.setBool = function (uniformName, bool) {
  18302. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18303. return this;
  18304. this._valueCache[uniformName] = bool;
  18305. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18306. return this;
  18307. };
  18308. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18309. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18310. return this;
  18311. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18312. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18313. return this;
  18314. };
  18315. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18316. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18317. return this;
  18318. this._cacheFloat2(uniformName, x, y);
  18319. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18320. return this;
  18321. };
  18322. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18323. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18324. return this;
  18325. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18326. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18327. return this;
  18328. };
  18329. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18330. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18331. return this;
  18332. this._cacheFloat3(uniformName, x, y, z);
  18333. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18334. return this;
  18335. };
  18336. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18337. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector4.x && this._valueCache[uniformName][1] === vector4.y && this._valueCache[uniformName][2] === vector4.z && this._valueCache[uniformName][3] === vector4.w)
  18338. return this;
  18339. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18340. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18341. return this;
  18342. };
  18343. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18344. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18345. return this;
  18346. this._cacheFloat4(uniformName, x, y, z, w);
  18347. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18348. return this;
  18349. };
  18350. Effect.prototype.setColor3 = function (uniformName, color3) {
  18351. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18352. return this;
  18353. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18354. this._engine.setColor3(this.getUniform(uniformName), color3);
  18355. return this;
  18356. };
  18357. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18358. 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)
  18359. return this;
  18360. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18361. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18362. return this;
  18363. };
  18364. // Statics
  18365. Effect.ShadersStore = {};
  18366. return Effect;
  18367. })();
  18368. BABYLON.Effect = Effect;
  18369. })(BABYLON || (BABYLON = {}));
  18370. var BABYLON;
  18371. (function (BABYLON) {
  18372. var Material = (function () {
  18373. function Material(name, scene, doNotAdd) {
  18374. this.name = name;
  18375. this.checkReadyOnEveryCall = true;
  18376. this.checkReadyOnlyOnce = false;
  18377. this.state = "";
  18378. this.alpha = 1.0;
  18379. this.backFaceCulling = true;
  18380. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18381. this.disableDepthWrite = false;
  18382. this._wasPreviouslyReady = false;
  18383. this._fillMode = Material.TriangleFillMode;
  18384. this.pointSize = 1.0;
  18385. this.zOffset = 0;
  18386. this.id = name;
  18387. this._scene = scene;
  18388. if (!doNotAdd) {
  18389. scene.materials.push(this);
  18390. }
  18391. }
  18392. Object.defineProperty(Material, "TriangleFillMode", {
  18393. get: function () {
  18394. return Material._TriangleFillMode;
  18395. },
  18396. enumerable: true,
  18397. configurable: true
  18398. });
  18399. Object.defineProperty(Material, "WireFrameFillMode", {
  18400. get: function () {
  18401. return Material._WireFrameFillMode;
  18402. },
  18403. enumerable: true,
  18404. configurable: true
  18405. });
  18406. Object.defineProperty(Material, "PointFillMode", {
  18407. get: function () {
  18408. return Material._PointFillMode;
  18409. },
  18410. enumerable: true,
  18411. configurable: true
  18412. });
  18413. Object.defineProperty(Material.prototype, "wireframe", {
  18414. get: function () {
  18415. return this._fillMode === Material.WireFrameFillMode;
  18416. },
  18417. set: function (value) {
  18418. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18419. },
  18420. enumerable: true,
  18421. configurable: true
  18422. });
  18423. Object.defineProperty(Material.prototype, "pointsCloud", {
  18424. get: function () {
  18425. return this._fillMode === Material.PointFillMode;
  18426. },
  18427. set: function (value) {
  18428. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18429. },
  18430. enumerable: true,
  18431. configurable: true
  18432. });
  18433. Object.defineProperty(Material.prototype, "fillMode", {
  18434. get: function () {
  18435. return this._fillMode;
  18436. },
  18437. set: function (value) {
  18438. this._fillMode = value;
  18439. },
  18440. enumerable: true,
  18441. configurable: true
  18442. });
  18443. Material.prototype.isReady = function (mesh, useInstances) {
  18444. return true;
  18445. };
  18446. Material.prototype.getEffect = function () {
  18447. return this._effect;
  18448. };
  18449. Material.prototype.getScene = function () {
  18450. return this._scene;
  18451. };
  18452. Material.prototype.needAlphaBlending = function () {
  18453. return (this.alpha < 1.0);
  18454. };
  18455. Material.prototype.needAlphaTesting = function () {
  18456. return false;
  18457. };
  18458. Material.prototype.getAlphaTestTexture = function () {
  18459. return null;
  18460. };
  18461. Material.prototype.trackCreation = function (onCompiled, onError) {
  18462. };
  18463. Material.prototype._preBind = function () {
  18464. var engine = this._scene.getEngine();
  18465. engine.enableEffect(this._effect);
  18466. engine.setState(this.backFaceCulling, this.zOffset);
  18467. };
  18468. Material.prototype.bind = function (world, mesh) {
  18469. this._scene._cachedMaterial = this;
  18470. if (this.onBind) {
  18471. this.onBind(this, mesh);
  18472. }
  18473. if (this.disableDepthWrite) {
  18474. var engine = this._scene.getEngine();
  18475. this._cachedDepthWriteState = engine.getDepthWrite();
  18476. engine.setDepthWrite(false);
  18477. }
  18478. };
  18479. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18480. };
  18481. Material.prototype.unbind = function () {
  18482. if (this.disableDepthWrite) {
  18483. var engine = this._scene.getEngine();
  18484. engine.setDepthWrite(this._cachedDepthWriteState);
  18485. }
  18486. };
  18487. Material.prototype.clone = function (name) {
  18488. return null;
  18489. };
  18490. Material.prototype.dispose = function (forceDisposeEffect) {
  18491. // Remove from scene
  18492. var index = this._scene.materials.indexOf(this);
  18493. this._scene.materials.splice(index, 1);
  18494. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18495. if (forceDisposeEffect && this._effect) {
  18496. this._scene.getEngine()._releaseEffect(this._effect);
  18497. this._effect = null;
  18498. }
  18499. // Callback
  18500. if (this.onDispose) {
  18501. this.onDispose();
  18502. }
  18503. };
  18504. Material._TriangleFillMode = 0;
  18505. Material._WireFrameFillMode = 1;
  18506. Material._PointFillMode = 2;
  18507. return Material;
  18508. })();
  18509. BABYLON.Material = Material;
  18510. })(BABYLON || (BABYLON = {}));
  18511. var BABYLON;
  18512. (function (BABYLON) {
  18513. var maxSimultaneousLights = 4;
  18514. var FresnelParameters = (function () {
  18515. function FresnelParameters() {
  18516. this.isEnabled = true;
  18517. this.leftColor = BABYLON.Color3.White();
  18518. this.rightColor = BABYLON.Color3.Black();
  18519. this.bias = 0;
  18520. this.power = 1;
  18521. }
  18522. return FresnelParameters;
  18523. })();
  18524. BABYLON.FresnelParameters = FresnelParameters;
  18525. var StandardMaterialDefines = (function () {
  18526. function StandardMaterialDefines() {
  18527. this.DIFFUSE = false;
  18528. this.AMBIENT = false;
  18529. this.OPACITY = false;
  18530. this.OPACITYRGB = false;
  18531. this.REFLECTION = false;
  18532. this.EMISSIVE = false;
  18533. this.SPECULAR = false;
  18534. this.BUMP = false;
  18535. this.SPECULAROVERALPHA = false;
  18536. this.CLIPPLANE = false;
  18537. this.ALPHATEST = false;
  18538. this.ALPHAFROMDIFFUSE = false;
  18539. this.POINTSIZE = false;
  18540. this.FOG = false;
  18541. this.LIGHT0 = false;
  18542. this.LIGHT1 = false;
  18543. this.LIGHT2 = false;
  18544. this.LIGHT3 = false;
  18545. this.SPOTLIGHT0 = false;
  18546. this.SPOTLIGHT1 = false;
  18547. this.SPOTLIGHT2 = false;
  18548. this.SPOTLIGHT3 = false;
  18549. this.HEMILIGHT0 = false;
  18550. this.HEMILIGHT1 = false;
  18551. this.HEMILIGHT2 = false;
  18552. this.HEMILIGHT3 = false;
  18553. this.POINTDIRLIGHT0 = false;
  18554. this.POINTDIRLIGHT1 = false;
  18555. this.POINTDIRLIGHT2 = false;
  18556. this.POINTDIRLIGHT3 = false;
  18557. this.SPECULARTERM = false;
  18558. this.SHADOW0 = false;
  18559. this.SHADOW1 = false;
  18560. this.SHADOW2 = false;
  18561. this.SHADOW3 = false;
  18562. this.SHADOWS = false;
  18563. this.SHADOWVSM0 = false;
  18564. this.SHADOWVSM1 = false;
  18565. this.SHADOWVSM2 = false;
  18566. this.SHADOWVSM3 = false;
  18567. this.SHADOWPCF0 = false;
  18568. this.SHADOWPCF1 = false;
  18569. this.SHADOWPCF2 = false;
  18570. this.SHADOWPCF3 = false;
  18571. this.DIFFUSEFRESNEL = false;
  18572. this.OPACITYFRESNEL = false;
  18573. this.REFLECTIONFRESNEL = false;
  18574. this.EMISSIVEFRESNEL = false;
  18575. this.FRESNEL = false;
  18576. this.NORMAL = false;
  18577. this.UV1 = false;
  18578. this.UV2 = false;
  18579. this.VERTEXCOLOR = false;
  18580. this.VERTEXALPHA = false;
  18581. this.BONES = false;
  18582. this.BONES4 = false;
  18583. this.BonesPerMesh = 0;
  18584. this.INSTANCES = false;
  18585. this.GLOSSINESS = false;
  18586. this._keys = Object.keys(this);
  18587. }
  18588. StandardMaterialDefines.prototype.isEqual = function (other) {
  18589. for (var index = 0; index < this._keys.length; index++) {
  18590. var prop = this._keys[index];
  18591. if (this[prop] !== other[prop]) {
  18592. return false;
  18593. }
  18594. }
  18595. return true;
  18596. };
  18597. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18598. for (var index = 0; index < this._keys.length; index++) {
  18599. var prop = this._keys[index];
  18600. other[prop] = this[prop];
  18601. }
  18602. };
  18603. StandardMaterialDefines.prototype.reset = function () {
  18604. for (var index = 0; index < this._keys.length; index++) {
  18605. var prop = this._keys[index];
  18606. if (prop === "BonesPerMesh") {
  18607. this[prop] = 0;
  18608. continue;
  18609. }
  18610. this[prop] = false;
  18611. }
  18612. };
  18613. StandardMaterialDefines.prototype.toString = function () {
  18614. var result = "";
  18615. for (var index = 0; index < this._keys.length; index++) {
  18616. var prop = this._keys[index];
  18617. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18618. result += "#define BonesPerMesh " + this[prop] + "\n";
  18619. continue;
  18620. }
  18621. if (this[prop]) {
  18622. result += "#define " + prop + "\n";
  18623. }
  18624. }
  18625. return result;
  18626. };
  18627. return StandardMaterialDefines;
  18628. })();
  18629. var StandardMaterial = (function (_super) {
  18630. __extends(StandardMaterial, _super);
  18631. function StandardMaterial(name, scene) {
  18632. var _this = this;
  18633. _super.call(this, name, scene);
  18634. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18635. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18636. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18637. this.specularPower = 64;
  18638. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18639. this.useAlphaFromDiffuseTexture = false;
  18640. this.useSpecularOverAlpha = true;
  18641. this.fogEnabled = true;
  18642. this.useGlossinessFromSpecularMapAlpha = false;
  18643. this._renderTargets = new BABYLON.SmartArray(16);
  18644. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18645. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18646. this._scaledDiffuse = new BABYLON.Color3();
  18647. this._scaledSpecular = new BABYLON.Color3();
  18648. this._defines = new StandardMaterialDefines();
  18649. this._cachedDefines = new StandardMaterialDefines();
  18650. this._cachedDefines.BonesPerMesh = -1;
  18651. this.getRenderTargetTextures = function () {
  18652. _this._renderTargets.reset();
  18653. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18654. _this._renderTargets.push(_this.reflectionTexture);
  18655. }
  18656. return _this._renderTargets;
  18657. };
  18658. }
  18659. StandardMaterial.prototype.needAlphaBlending = function () {
  18660. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18661. };
  18662. StandardMaterial.prototype.needAlphaTesting = function () {
  18663. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18664. };
  18665. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18666. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18667. };
  18668. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18669. return this.diffuseTexture;
  18670. };
  18671. // Methods
  18672. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18673. if (this.checkReadyOnlyOnce) {
  18674. if (this._wasPreviouslyReady) {
  18675. return true;
  18676. }
  18677. }
  18678. var scene = this.getScene();
  18679. if (!this.checkReadyOnEveryCall) {
  18680. if (this._renderId === scene.getRenderId()) {
  18681. return true;
  18682. }
  18683. }
  18684. var engine = scene.getEngine();
  18685. var needNormals = false;
  18686. var needUVs = false;
  18687. this._defines.reset();
  18688. // Textures
  18689. if (scene.texturesEnabled) {
  18690. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18691. if (!this.diffuseTexture.isReady()) {
  18692. return false;
  18693. }
  18694. else {
  18695. needUVs = true;
  18696. this._defines.DIFFUSE = true;
  18697. }
  18698. }
  18699. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18700. if (!this.ambientTexture.isReady()) {
  18701. return false;
  18702. }
  18703. else {
  18704. needUVs = true;
  18705. this._defines.AMBIENT = true;
  18706. }
  18707. }
  18708. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18709. if (!this.opacityTexture.isReady()) {
  18710. return false;
  18711. }
  18712. else {
  18713. needUVs = true;
  18714. this._defines.OPACITY = true;
  18715. if (this.opacityTexture.getAlphaFromRGB) {
  18716. this._defines.OPACITYRGB = true;
  18717. }
  18718. }
  18719. }
  18720. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18721. if (!this.reflectionTexture.isReady()) {
  18722. return false;
  18723. }
  18724. else {
  18725. needNormals = true;
  18726. needUVs = true;
  18727. this._defines.REFLECTION = true;
  18728. }
  18729. }
  18730. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18731. if (!this.emissiveTexture.isReady()) {
  18732. return false;
  18733. }
  18734. else {
  18735. needUVs = true;
  18736. this._defines.EMISSIVE = true;
  18737. }
  18738. }
  18739. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18740. if (!this.specularTexture.isReady()) {
  18741. return false;
  18742. }
  18743. else {
  18744. needUVs = true;
  18745. this._defines.SPECULAR = true;
  18746. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18747. }
  18748. }
  18749. }
  18750. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18751. if (!this.bumpTexture.isReady()) {
  18752. return false;
  18753. }
  18754. else {
  18755. needUVs = true;
  18756. this._defines.BUMP = true;
  18757. }
  18758. }
  18759. // Effect
  18760. if (scene.clipPlane) {
  18761. this._defines.CLIPPLANE = true;
  18762. }
  18763. if (engine.getAlphaTesting()) {
  18764. this._defines.ALPHATEST = true;
  18765. }
  18766. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18767. this._defines.ALPHAFROMDIFFUSE = true;
  18768. }
  18769. // Point size
  18770. if (this.pointsCloud || scene.forcePointsCloud) {
  18771. this._defines.POINTSIZE = true;
  18772. }
  18773. // Fog
  18774. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18775. this._defines.FOG = true;
  18776. }
  18777. var lightIndex = 0;
  18778. if (scene.lightsEnabled) {
  18779. for (var index = 0; index < scene.lights.length; index++) {
  18780. var light = scene.lights[index];
  18781. if (!light.isEnabled()) {
  18782. continue;
  18783. }
  18784. // Excluded check
  18785. if (light._excludedMeshesIds.length > 0) {
  18786. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18787. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18788. if (excludedMesh) {
  18789. light.excludedMeshes.push(excludedMesh);
  18790. }
  18791. }
  18792. light._excludedMeshesIds = [];
  18793. }
  18794. // Included check
  18795. if (light._includedOnlyMeshesIds.length > 0) {
  18796. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18797. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18798. if (includedOnlyMesh) {
  18799. light.includedOnlyMeshes.push(includedOnlyMesh);
  18800. }
  18801. }
  18802. light._includedOnlyMeshesIds = [];
  18803. }
  18804. if (!light.canAffectMesh(mesh)) {
  18805. continue;
  18806. }
  18807. needNormals = true;
  18808. this._defines["LIGHT" + lightIndex] = true;
  18809. var type;
  18810. if (light instanceof BABYLON.SpotLight) {
  18811. type = "SPOTLIGHT" + lightIndex;
  18812. }
  18813. else if (light instanceof BABYLON.HemisphericLight) {
  18814. type = "HEMILIGHT" + lightIndex;
  18815. }
  18816. else {
  18817. type = "POINTDIRLIGHT" + lightIndex;
  18818. }
  18819. this._defines[type] = true;
  18820. // Specular
  18821. if (!light.specular.equalsFloats(0, 0, 0)) {
  18822. this._defines.SPECULARTERM = true;
  18823. }
  18824. // Shadows
  18825. if (scene.shadowsEnabled) {
  18826. var shadowGenerator = light.getShadowGenerator();
  18827. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18828. this._defines["SHADOW" + lightIndex] = true;
  18829. this._defines.SHADOWS = true;
  18830. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18831. this._defines["SHADOWVSM" + lightIndex] = true;
  18832. }
  18833. if (shadowGenerator.usePoissonSampling) {
  18834. this._defines["SHADOWPCF" + lightIndex] = true;
  18835. }
  18836. }
  18837. }
  18838. lightIndex++;
  18839. if (lightIndex === maxSimultaneousLights)
  18840. break;
  18841. }
  18842. }
  18843. if (StandardMaterial.FresnelEnabled) {
  18844. // Fresnel
  18845. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18846. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18847. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18848. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18849. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18850. this._defines.DIFFUSEFRESNEL = true;
  18851. }
  18852. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18853. this._defines.OPACITYFRESNEL = true;
  18854. }
  18855. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18856. this._defines.REFLECTIONFRESNEL = true;
  18857. }
  18858. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18859. this._defines.EMISSIVEFRESNEL = true;
  18860. }
  18861. needNormals = true;
  18862. this._defines.FRESNEL = true;
  18863. }
  18864. }
  18865. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18866. this._defines.SPECULAROVERALPHA = true;
  18867. }
  18868. // Attribs
  18869. if (mesh) {
  18870. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18871. this._defines.NORMAL = true;
  18872. }
  18873. if (needUVs) {
  18874. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18875. this._defines.UV1 = true;
  18876. }
  18877. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18878. this._defines.UV2 = true;
  18879. }
  18880. }
  18881. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18882. this._defines.VERTEXCOLOR = true;
  18883. if (mesh.hasVertexAlpha) {
  18884. this._defines.VERTEXALPHA = true;
  18885. }
  18886. }
  18887. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18888. this._defines.BONES = true;
  18889. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18890. this._defines.BONES4 = true;
  18891. }
  18892. // Instances
  18893. if (useInstances) {
  18894. this._defines.INSTANCES = true;
  18895. }
  18896. }
  18897. // Get correct effect
  18898. if (!this._defines.isEqual(this._cachedDefines)) {
  18899. this._defines.cloneTo(this._cachedDefines);
  18900. scene.resetCachedMaterial();
  18901. // Fallbacks
  18902. var fallbacks = new BABYLON.EffectFallbacks();
  18903. if (this._defines.REFLECTION) {
  18904. fallbacks.addFallback(0, "REFLECTION");
  18905. }
  18906. if (this._defines.SPECULAR) {
  18907. fallbacks.addFallback(0, "SPECULAR");
  18908. }
  18909. if (this._defines.BUMP) {
  18910. fallbacks.addFallback(0, "BUMP");
  18911. }
  18912. if (this._defines.SPECULAROVERALPHA) {
  18913. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18914. }
  18915. if (this._defines.FOG) {
  18916. fallbacks.addFallback(1, "FOG");
  18917. }
  18918. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18919. if (!this._defines["LIGHT" + lightIndex]) {
  18920. continue;
  18921. }
  18922. if (lightIndex > 0) {
  18923. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18924. }
  18925. if (this._defines["SHADOW" + lightIndex]) {
  18926. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18927. }
  18928. if (this._defines["SHADOWPCF" + lightIndex]) {
  18929. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18930. }
  18931. if (this._defines["SHADOWVSM" + lightIndex]) {
  18932. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18933. }
  18934. }
  18935. if (this._defines.SPECULARTERM) {
  18936. fallbacks.addFallback(0, "SPECULARTERM");
  18937. }
  18938. if (this._defines.DIFFUSEFRESNEL) {
  18939. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18940. }
  18941. if (this._defines.OPACITYFRESNEL) {
  18942. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18943. }
  18944. if (this._defines.REFLECTIONFRESNEL) {
  18945. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18946. }
  18947. if (this._defines.EMISSIVEFRESNEL) {
  18948. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18949. }
  18950. if (this._defines.FRESNEL) {
  18951. fallbacks.addFallback(4, "FRESNEL");
  18952. }
  18953. if (this._defines.BONES4) {
  18954. fallbacks.addFallback(0, "BONES4");
  18955. }
  18956. //Attributes
  18957. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18958. if (this._defines.NORMAL) {
  18959. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18960. }
  18961. if (this._defines.UV1) {
  18962. attribs.push(BABYLON.VertexBuffer.UVKind);
  18963. }
  18964. if (this._defines.UV2) {
  18965. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18966. }
  18967. if (this._defines.VERTEXCOLOR) {
  18968. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18969. }
  18970. if (this._defines.BONES) {
  18971. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18972. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18973. }
  18974. if (this._defines.INSTANCES) {
  18975. attribs.push("world0");
  18976. attribs.push("world1");
  18977. attribs.push("world2");
  18978. attribs.push("world3");
  18979. }
  18980. // Legacy browser patch
  18981. var shaderName = "default";
  18982. if (!scene.getEngine().getCaps().standardDerivatives) {
  18983. shaderName = "legacydefault";
  18984. }
  18985. var join = this._defines.toString();
  18986. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18987. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18988. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18989. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18990. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18991. "vFogInfos", "vFogColor", "pointSize",
  18992. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18993. "mBones",
  18994. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18995. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18996. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18997. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18998. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18999. ], join, fallbacks, this.onCompiled, this.onError);
  19000. }
  19001. if (!this._effect.isReady()) {
  19002. return false;
  19003. }
  19004. this._renderId = scene.getRenderId();
  19005. this._wasPreviouslyReady = true;
  19006. return true;
  19007. };
  19008. StandardMaterial.prototype.unbind = function () {
  19009. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  19010. this._effect.setTexture("reflection2DSampler", null);
  19011. }
  19012. _super.prototype.unbind.call(this);
  19013. };
  19014. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19015. this._effect.setMatrix("world", world);
  19016. };
  19017. StandardMaterial.prototype.bind = function (world, mesh) {
  19018. var scene = this.getScene();
  19019. // Matrices
  19020. this.bindOnlyWorldMatrix(world);
  19021. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19022. // Bones
  19023. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19024. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19025. }
  19026. if (scene.getCachedMaterial() !== this) {
  19027. if (StandardMaterial.FresnelEnabled) {
  19028. // Fresnel
  19029. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19030. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19031. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19032. }
  19033. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19034. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19035. }
  19036. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19037. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19038. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19039. }
  19040. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19041. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19042. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19043. }
  19044. }
  19045. // Textures
  19046. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19047. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19048. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19049. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19050. }
  19051. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19052. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19053. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19054. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19055. }
  19056. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19057. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19058. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19059. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19060. }
  19061. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19062. if (this.reflectionTexture.isCube) {
  19063. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19064. }
  19065. else {
  19066. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19067. }
  19068. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19069. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  19070. }
  19071. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19072. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19073. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19074. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19075. }
  19076. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19077. this._effect.setTexture("specularSampler", this.specularTexture);
  19078. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19079. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19080. }
  19081. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19082. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19083. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19084. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19085. }
  19086. // Clip plane
  19087. if (scene.clipPlane) {
  19088. var clipPlane = scene.clipPlane;
  19089. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19090. }
  19091. // Point size
  19092. if (this.pointsCloud) {
  19093. this._effect.setFloat("pointSize", this.pointSize);
  19094. }
  19095. // Colors
  19096. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19097. // Scaling down color according to emissive
  19098. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19099. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19100. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19101. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  19102. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19103. if (this._defines.SPECULARTERM) {
  19104. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19105. }
  19106. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19107. }
  19108. // Scaling down color according to emissive
  19109. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19110. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19111. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19112. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19113. if (scene.lightsEnabled) {
  19114. var lightIndex = 0;
  19115. for (var index = 0; index < scene.lights.length; index++) {
  19116. var light = scene.lights[index];
  19117. if (!light.isEnabled()) {
  19118. continue;
  19119. }
  19120. if (!light.canAffectMesh(mesh)) {
  19121. continue;
  19122. }
  19123. if (light instanceof BABYLON.PointLight) {
  19124. // Point Light
  19125. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19126. }
  19127. else if (light instanceof BABYLON.DirectionalLight) {
  19128. // Directional Light
  19129. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19130. }
  19131. else if (light instanceof BABYLON.SpotLight) {
  19132. // Spot Light
  19133. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19134. }
  19135. else if (light instanceof BABYLON.HemisphericLight) {
  19136. // Hemispheric Light
  19137. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19138. }
  19139. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19140. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19141. if (this._defines.SPECULARTERM) {
  19142. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19143. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19144. }
  19145. // Shadows
  19146. if (scene.shadowsEnabled) {
  19147. var shadowGenerator = light.getShadowGenerator();
  19148. if (mesh.receiveShadows && shadowGenerator) {
  19149. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19150. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19151. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19152. }
  19153. }
  19154. lightIndex++;
  19155. if (lightIndex === maxSimultaneousLights)
  19156. break;
  19157. }
  19158. }
  19159. // View
  19160. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19161. this._effect.setMatrix("view", scene.getViewMatrix());
  19162. }
  19163. // Fog
  19164. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19165. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19166. this._effect.setColor3("vFogColor", scene.fogColor);
  19167. }
  19168. _super.prototype.bind.call(this, world, mesh);
  19169. };
  19170. StandardMaterial.prototype.getAnimatables = function () {
  19171. var results = [];
  19172. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19173. results.push(this.diffuseTexture);
  19174. }
  19175. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19176. results.push(this.ambientTexture);
  19177. }
  19178. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19179. results.push(this.opacityTexture);
  19180. }
  19181. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19182. results.push(this.reflectionTexture);
  19183. }
  19184. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19185. results.push(this.emissiveTexture);
  19186. }
  19187. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19188. results.push(this.specularTexture);
  19189. }
  19190. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19191. results.push(this.bumpTexture);
  19192. }
  19193. return results;
  19194. };
  19195. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19196. if (this.diffuseTexture) {
  19197. this.diffuseTexture.dispose();
  19198. }
  19199. if (this.ambientTexture) {
  19200. this.ambientTexture.dispose();
  19201. }
  19202. if (this.opacityTexture) {
  19203. this.opacityTexture.dispose();
  19204. }
  19205. if (this.reflectionTexture) {
  19206. this.reflectionTexture.dispose();
  19207. }
  19208. if (this.emissiveTexture) {
  19209. this.emissiveTexture.dispose();
  19210. }
  19211. if (this.specularTexture) {
  19212. this.specularTexture.dispose();
  19213. }
  19214. if (this.bumpTexture) {
  19215. this.bumpTexture.dispose();
  19216. }
  19217. _super.prototype.dispose.call(this, forceDisposeEffect);
  19218. };
  19219. StandardMaterial.prototype.clone = function (name) {
  19220. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19221. // Base material
  19222. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19223. newStandardMaterial.alpha = this.alpha;
  19224. newStandardMaterial.fillMode = this.fillMode;
  19225. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  19226. // Standard material
  19227. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19228. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19229. }
  19230. if (this.ambientTexture && this.ambientTexture.clone) {
  19231. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19232. }
  19233. if (this.opacityTexture && this.opacityTexture.clone) {
  19234. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19235. }
  19236. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19237. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19238. }
  19239. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19240. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19241. }
  19242. if (this.specularTexture && this.specularTexture.clone) {
  19243. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19244. }
  19245. if (this.bumpTexture && this.bumpTexture.clone) {
  19246. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19247. }
  19248. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19249. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19250. newStandardMaterial.specularColor = this.specularColor.clone();
  19251. newStandardMaterial.specularPower = this.specularPower;
  19252. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19253. return newStandardMaterial;
  19254. };
  19255. // Statics
  19256. // Flags used to enable or disable a type of texture for all Standard Materials
  19257. StandardMaterial.DiffuseTextureEnabled = true;
  19258. StandardMaterial.AmbientTextureEnabled = true;
  19259. StandardMaterial.OpacityTextureEnabled = true;
  19260. StandardMaterial.ReflectionTextureEnabled = true;
  19261. StandardMaterial.EmissiveTextureEnabled = true;
  19262. StandardMaterial.SpecularTextureEnabled = true;
  19263. StandardMaterial.BumpTextureEnabled = true;
  19264. StandardMaterial.FresnelEnabled = true;
  19265. return StandardMaterial;
  19266. })(BABYLON.Material);
  19267. BABYLON.StandardMaterial = StandardMaterial;
  19268. })(BABYLON || (BABYLON = {}));
  19269. var BABYLON;
  19270. (function (BABYLON) {
  19271. var MultiMaterial = (function (_super) {
  19272. __extends(MultiMaterial, _super);
  19273. function MultiMaterial(name, scene) {
  19274. _super.call(this, name, scene, true);
  19275. this.subMaterials = new Array();
  19276. scene.multiMaterials.push(this);
  19277. }
  19278. // Properties
  19279. MultiMaterial.prototype.getSubMaterial = function (index) {
  19280. if (index < 0 || index >= this.subMaterials.length) {
  19281. return this.getScene().defaultMaterial;
  19282. }
  19283. return this.subMaterials[index];
  19284. };
  19285. // Methods
  19286. MultiMaterial.prototype.isReady = function (mesh) {
  19287. for (var index = 0; index < this.subMaterials.length; index++) {
  19288. var subMaterial = this.subMaterials[index];
  19289. if (subMaterial) {
  19290. if (!this.subMaterials[index].isReady(mesh)) {
  19291. return false;
  19292. }
  19293. }
  19294. }
  19295. return true;
  19296. };
  19297. MultiMaterial.prototype.clone = function (name) {
  19298. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19299. for (var index = 0; index < this.subMaterials.length; index++) {
  19300. var subMaterial = this.subMaterials[index];
  19301. newMultiMaterial.subMaterials.push(subMaterial);
  19302. }
  19303. return newMultiMaterial;
  19304. };
  19305. return MultiMaterial;
  19306. })(BABYLON.Material);
  19307. BABYLON.MultiMaterial = MultiMaterial;
  19308. })(BABYLON || (BABYLON = {}));
  19309. var BABYLON;
  19310. (function (BABYLON) {
  19311. var SceneLoader = (function () {
  19312. function SceneLoader() {
  19313. }
  19314. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19315. get: function () {
  19316. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19317. },
  19318. set: function (value) {
  19319. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19320. },
  19321. enumerable: true,
  19322. configurable: true
  19323. });
  19324. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19325. get: function () {
  19326. return SceneLoader._ShowLoadingScreen;
  19327. },
  19328. set: function (value) {
  19329. SceneLoader._ShowLoadingScreen = value;
  19330. },
  19331. enumerable: true,
  19332. configurable: true
  19333. });
  19334. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19335. var dotPosition = sceneFilename.lastIndexOf(".");
  19336. var queryStringPosition = sceneFilename.indexOf("?");
  19337. if (queryStringPosition === -1) {
  19338. queryStringPosition = sceneFilename.length;
  19339. }
  19340. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19341. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19342. var plugin = this._registeredPlugins[index];
  19343. if (plugin.extensions.indexOf(extension) !== -1) {
  19344. return plugin;
  19345. }
  19346. }
  19347. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19348. };
  19349. // Public functions
  19350. SceneLoader.RegisterPlugin = function (plugin) {
  19351. plugin.extensions = plugin.extensions.toLowerCase();
  19352. SceneLoader._registeredPlugins.push(plugin);
  19353. };
  19354. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19355. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19356. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19357. return;
  19358. }
  19359. var loadingToken = {};
  19360. scene._addPendingData(loadingToken);
  19361. var manifestChecked = function (success) {
  19362. scene.database = database;
  19363. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19364. var importMeshFromData = function (data) {
  19365. var meshes = [];
  19366. var particleSystems = [];
  19367. var skeletons = [];
  19368. try {
  19369. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19370. if (onerror) {
  19371. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19372. }
  19373. scene._removePendingData(loadingToken);
  19374. return;
  19375. }
  19376. }
  19377. catch (e) {
  19378. if (onerror) {
  19379. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19380. }
  19381. scene._removePendingData(loadingToken);
  19382. return;
  19383. }
  19384. if (onsuccess) {
  19385. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19386. onsuccess(meshes, particleSystems, skeletons);
  19387. scene._removePendingData(loadingToken);
  19388. }
  19389. };
  19390. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19391. // Direct load
  19392. importMeshFromData(sceneFilename.substr(5));
  19393. return;
  19394. }
  19395. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19396. importMeshFromData(data);
  19397. }, progressCallBack, database);
  19398. };
  19399. if (scene.getEngine().enableOfflineSupport) {
  19400. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19401. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19402. }
  19403. else {
  19404. manifestChecked(true);
  19405. }
  19406. };
  19407. /**
  19408. * Load a scene
  19409. * @param rootUrl a string that defines the root url for scene and resources
  19410. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19411. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19412. */
  19413. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19414. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19415. };
  19416. /**
  19417. * Append a scene
  19418. * @param rootUrl a string that defines the root url for scene and resources
  19419. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19420. * @param scene is the instance of BABYLON.Scene to append to
  19421. */
  19422. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19423. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19424. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19425. return;
  19426. }
  19427. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19428. var database;
  19429. var loadingToken = {};
  19430. scene._addPendingData(loadingToken);
  19431. if (SceneLoader.ShowLoadingScreen) {
  19432. scene.getEngine().displayLoadingUI();
  19433. }
  19434. var loadSceneFromData = function (data) {
  19435. scene.database = database;
  19436. if (!plugin.load(scene, data, rootUrl)) {
  19437. if (onerror) {
  19438. onerror(scene);
  19439. }
  19440. scene._removePendingData(loadingToken);
  19441. scene.getEngine().hideLoadingUI();
  19442. return;
  19443. }
  19444. if (onsuccess) {
  19445. onsuccess(scene);
  19446. }
  19447. scene._removePendingData(loadingToken);
  19448. if (SceneLoader.ShowLoadingScreen) {
  19449. scene.executeWhenReady(function () {
  19450. scene.getEngine().hideLoadingUI();
  19451. });
  19452. }
  19453. };
  19454. var manifestChecked = function (success) {
  19455. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19456. };
  19457. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19458. // Direct load
  19459. loadSceneFromData(sceneFilename.substr(5));
  19460. return;
  19461. }
  19462. if (rootUrl.indexOf("file:") === -1) {
  19463. if (scene.getEngine().enableOfflineSupport) {
  19464. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19465. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19466. }
  19467. else {
  19468. manifestChecked(true);
  19469. }
  19470. }
  19471. else {
  19472. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19473. }
  19474. };
  19475. // Flags
  19476. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19477. SceneLoader._ShowLoadingScreen = true;
  19478. // Members
  19479. SceneLoader._registeredPlugins = new Array();
  19480. return SceneLoader;
  19481. })();
  19482. BABYLON.SceneLoader = SceneLoader;
  19483. ;
  19484. })(BABYLON || (BABYLON = {}));
  19485. var BABYLON;
  19486. (function (BABYLON) {
  19487. var Internals;
  19488. (function (Internals) {
  19489. var checkColors4 = function (colors, count) {
  19490. // Check if color3 was used
  19491. if (colors.length === count * 3) {
  19492. var colors4 = [];
  19493. for (var index = 0; index < colors.length; index += 3) {
  19494. var newIndex = (index / 3) * 4;
  19495. colors4[newIndex] = colors[index];
  19496. colors4[newIndex + 1] = colors[index + 1];
  19497. colors4[newIndex + 2] = colors[index + 2];
  19498. colors4[newIndex + 3] = 1.0;
  19499. }
  19500. return colors4;
  19501. }
  19502. return colors;
  19503. };
  19504. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19505. var texture = null;
  19506. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19507. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19508. texture.name = parsedTexture.name;
  19509. texture.hasAlpha = parsedTexture.hasAlpha;
  19510. texture.level = parsedTexture.level;
  19511. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19512. }
  19513. return texture;
  19514. };
  19515. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19516. if (parsedTexture.isCube) {
  19517. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19518. }
  19519. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19520. return null;
  19521. }
  19522. var texture;
  19523. if (parsedTexture.mirrorPlane) {
  19524. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19525. texture._waitingRenderList = parsedTexture.renderList;
  19526. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19527. }
  19528. else if (parsedTexture.isRenderTarget) {
  19529. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19530. texture._waitingRenderList = parsedTexture.renderList;
  19531. }
  19532. else {
  19533. if (parsedTexture.base64String) {
  19534. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19535. }
  19536. else {
  19537. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19538. }
  19539. }
  19540. texture.name = parsedTexture.name;
  19541. texture.hasAlpha = parsedTexture.hasAlpha;
  19542. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19543. texture.level = parsedTexture.level;
  19544. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19545. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19546. texture.uOffset = parsedTexture.uOffset;
  19547. texture.vOffset = parsedTexture.vOffset;
  19548. texture.uScale = parsedTexture.uScale;
  19549. texture.vScale = parsedTexture.vScale;
  19550. texture.uAng = parsedTexture.uAng;
  19551. texture.vAng = parsedTexture.vAng;
  19552. texture.wAng = parsedTexture.wAng;
  19553. texture.wrapU = parsedTexture.wrapU;
  19554. texture.wrapV = parsedTexture.wrapV;
  19555. // Animations
  19556. if (parsedTexture.animations) {
  19557. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19558. var parsedAnimation = parsedTexture.animations[animationIndex];
  19559. texture.animations.push(parseAnimation(parsedAnimation));
  19560. }
  19561. }
  19562. return texture;
  19563. };
  19564. var parseSkeleton = function (parsedSkeleton, scene) {
  19565. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19566. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19567. var parsedBone = parsedSkeleton.bones[index];
  19568. var parentBone = null;
  19569. if (parsedBone.parentBoneIndex > -1) {
  19570. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19571. }
  19572. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19573. if (parsedBone.animation) {
  19574. bone.animations.push(parseAnimation(parsedBone.animation));
  19575. }
  19576. }
  19577. return skeleton;
  19578. };
  19579. var parseFresnelParameters = function (parsedFresnelParameters) {
  19580. var fresnelParameters = new BABYLON.FresnelParameters();
  19581. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19582. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19583. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19584. fresnelParameters.bias = parsedFresnelParameters.bias;
  19585. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19586. return fresnelParameters;
  19587. };
  19588. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19589. var material;
  19590. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19591. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19592. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19593. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19594. material.specularPower = parsedMaterial.specularPower;
  19595. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19596. material.alpha = parsedMaterial.alpha;
  19597. material.id = parsedMaterial.id;
  19598. if (parsedMaterial.disableDepthWrite) {
  19599. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19600. }
  19601. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19602. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19603. material.wireframe = parsedMaterial.wireframe;
  19604. if (parsedMaterial.diffuseTexture) {
  19605. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19606. }
  19607. if (parsedMaterial.diffuseFresnelParameters) {
  19608. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19609. }
  19610. if (parsedMaterial.ambientTexture) {
  19611. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19612. }
  19613. if (parsedMaterial.opacityTexture) {
  19614. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19615. }
  19616. if (parsedMaterial.opacityFresnelParameters) {
  19617. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19618. }
  19619. if (parsedMaterial.reflectionTexture) {
  19620. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19621. }
  19622. if (parsedMaterial.reflectionFresnelParameters) {
  19623. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19624. }
  19625. if (parsedMaterial.emissiveTexture) {
  19626. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19627. }
  19628. if (parsedMaterial.emissiveFresnelParameters) {
  19629. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19630. }
  19631. if (parsedMaterial.specularTexture) {
  19632. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19633. }
  19634. if (parsedMaterial.bumpTexture) {
  19635. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19636. }
  19637. if (parsedMaterial.checkReadyOnlyOnce) {
  19638. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19639. }
  19640. return material;
  19641. };
  19642. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19643. for (var index = 0; index < parsedData.materials.length; index++) {
  19644. var parsedMaterial = parsedData.materials[index];
  19645. if (parsedMaterial.id === id) {
  19646. return parseMaterial(parsedMaterial, scene, rootUrl);
  19647. }
  19648. }
  19649. return null;
  19650. };
  19651. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19652. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19653. multiMaterial.id = parsedMultiMaterial.id;
  19654. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19655. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19656. var subMatId = parsedMultiMaterial.materials[matIndex];
  19657. if (subMatId) {
  19658. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19659. }
  19660. else {
  19661. multiMaterial.subMaterials.push(null);
  19662. }
  19663. }
  19664. return multiMaterial;
  19665. };
  19666. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19667. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19668. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19669. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19670. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19671. var parsedFlare = parsedLensFlareSystem.flares[index];
  19672. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19673. }
  19674. return lensFlareSystem;
  19675. };
  19676. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19677. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19678. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19679. if (parsedParticleSystem.textureName) {
  19680. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19681. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19682. }
  19683. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19684. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19685. particleSystem.minSize = parsedParticleSystem.minSize;
  19686. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19687. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19688. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19689. particleSystem.emitter = emitter;
  19690. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19691. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19692. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19693. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19694. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19695. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19696. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19697. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19698. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19699. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19700. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19701. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19702. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19703. particleSystem.start();
  19704. return particleSystem;
  19705. };
  19706. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19707. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19708. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19709. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19710. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19711. shadowGenerator.getShadowMap().renderList.push(mesh);
  19712. }
  19713. if (parsedShadowGenerator.usePoissonSampling) {
  19714. shadowGenerator.usePoissonSampling = true;
  19715. }
  19716. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19717. shadowGenerator.useVarianceShadowMap = true;
  19718. }
  19719. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19720. shadowGenerator.useBlurVarianceShadowMap = true;
  19721. if (parsedShadowGenerator.blurScale) {
  19722. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19723. }
  19724. if (parsedShadowGenerator.blurBoxOffset) {
  19725. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19726. }
  19727. }
  19728. if (parsedShadowGenerator.bias !== undefined) {
  19729. shadowGenerator.bias = parsedShadowGenerator.bias;
  19730. }
  19731. return shadowGenerator;
  19732. };
  19733. var parseAnimation = function (parsedAnimation) {
  19734. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19735. var dataType = parsedAnimation.dataType;
  19736. var keys = [];
  19737. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19738. var key = parsedAnimation.keys[index];
  19739. var data;
  19740. switch (dataType) {
  19741. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19742. data = key.values[0];
  19743. break;
  19744. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19745. data = BABYLON.Quaternion.FromArray(key.values);
  19746. break;
  19747. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19748. data = BABYLON.Matrix.FromArray(key.values);
  19749. break;
  19750. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19751. default:
  19752. data = BABYLON.Vector3.FromArray(key.values);
  19753. break;
  19754. }
  19755. keys.push({
  19756. frame: key.frame,
  19757. value: data
  19758. });
  19759. }
  19760. animation.setKeys(keys);
  19761. return animation;
  19762. };
  19763. var parseLight = function (parsedLight, scene) {
  19764. var light;
  19765. switch (parsedLight.type) {
  19766. case 0:
  19767. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19768. break;
  19769. case 1:
  19770. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19771. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19772. break;
  19773. case 2:
  19774. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19775. break;
  19776. case 3:
  19777. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19778. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19779. break;
  19780. }
  19781. light.id = parsedLight.id;
  19782. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19783. if (parsedLight.intensity !== undefined) {
  19784. light.intensity = parsedLight.intensity;
  19785. }
  19786. if (parsedLight.range) {
  19787. light.range = parsedLight.range;
  19788. }
  19789. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19790. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19791. if (parsedLight.excludedMeshesIds) {
  19792. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19793. }
  19794. // Parent
  19795. if (parsedLight.parentId) {
  19796. light._waitingParentId = parsedLight.parentId;
  19797. }
  19798. if (parsedLight.includedOnlyMeshesIds) {
  19799. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19800. }
  19801. // Animations
  19802. if (parsedLight.animations) {
  19803. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19804. var parsedAnimation = parsedLight.animations[animationIndex];
  19805. light.animations.push(parseAnimation(parsedAnimation));
  19806. }
  19807. }
  19808. if (parsedLight.autoAnimate) {
  19809. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19810. }
  19811. };
  19812. var parseCamera = function (parsedCamera, scene) {
  19813. var camera;
  19814. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19815. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19816. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19817. var alpha = parsedCamera.alpha;
  19818. var beta = parsedCamera.beta;
  19819. var radius = parsedCamera.radius;
  19820. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19821. var interaxial_distance = parsedCamera.interaxial_distance;
  19822. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19823. }
  19824. else {
  19825. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19826. }
  19827. }
  19828. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19829. interaxial_distance = parsedCamera.interaxial_distance;
  19830. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19831. }
  19832. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19833. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19834. }
  19835. else if (parsedCamera.type === "FollowCamera") {
  19836. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19837. camera.heightOffset = parsedCamera.heightOffset;
  19838. camera.radius = parsedCamera.radius;
  19839. camera.rotationOffset = parsedCamera.rotationOffset;
  19840. if (lockedTargetMesh)
  19841. camera.target = lockedTargetMesh;
  19842. }
  19843. else if (parsedCamera.type === "GamepadCamera") {
  19844. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19845. }
  19846. else if (parsedCamera.type === "TouchCamera") {
  19847. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19848. }
  19849. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19850. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19851. }
  19852. else if (parsedCamera.type === "WebVRFreeCamera") {
  19853. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19854. }
  19855. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19856. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19857. }
  19858. else {
  19859. // Free Camera is the default value
  19860. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19861. }
  19862. // apply 3d rig, when found
  19863. if (parsedCamera.cameraRigMode) {
  19864. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19865. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19866. }
  19867. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19868. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19869. camera.lockedTarget = lockedTargetMesh;
  19870. }
  19871. camera.id = parsedCamera.id;
  19872. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19873. // Parent
  19874. if (parsedCamera.parentId) {
  19875. camera._waitingParentId = parsedCamera.parentId;
  19876. }
  19877. // Target
  19878. if (parsedCamera.target) {
  19879. if (camera.setTarget) {
  19880. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19881. }
  19882. else {
  19883. //For ArcRotate
  19884. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19885. }
  19886. }
  19887. else {
  19888. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19889. }
  19890. camera.fov = parsedCamera.fov;
  19891. camera.minZ = parsedCamera.minZ;
  19892. camera.maxZ = parsedCamera.maxZ;
  19893. camera.speed = parsedCamera.speed;
  19894. camera.inertia = parsedCamera.inertia;
  19895. camera.checkCollisions = parsedCamera.checkCollisions;
  19896. camera.applyGravity = parsedCamera.applyGravity;
  19897. if (parsedCamera.ellipsoid) {
  19898. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19899. }
  19900. // Animations
  19901. if (parsedCamera.animations) {
  19902. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19903. var parsedAnimation = parsedCamera.animations[animationIndex];
  19904. camera.animations.push(parseAnimation(parsedAnimation));
  19905. }
  19906. }
  19907. if (parsedCamera.autoAnimate) {
  19908. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19909. }
  19910. // Layer Mask
  19911. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19912. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19913. }
  19914. else {
  19915. camera.layerMask = 0x0FFFFFFF;
  19916. }
  19917. return camera;
  19918. };
  19919. var parseGeometry = function (parsedGeometry, scene) {
  19920. var id = parsedGeometry.id;
  19921. return scene.getGeometryByID(id);
  19922. };
  19923. var parseBox = function (parsedBox, scene) {
  19924. if (parseGeometry(parsedBox, scene)) {
  19925. return null; // null since geometry could be something else than a box...
  19926. }
  19927. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19928. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19929. scene.pushGeometry(box, true);
  19930. return box;
  19931. };
  19932. var parseSphere = function (parsedSphere, scene) {
  19933. if (parseGeometry(parsedSphere, scene)) {
  19934. return null; // null since geometry could be something else than a sphere...
  19935. }
  19936. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19937. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19938. scene.pushGeometry(sphere, true);
  19939. return sphere;
  19940. };
  19941. var parseCylinder = function (parsedCylinder, scene) {
  19942. if (parseGeometry(parsedCylinder, scene)) {
  19943. return null; // null since geometry could be something else than a cylinder...
  19944. }
  19945. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19946. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19947. scene.pushGeometry(cylinder, true);
  19948. return cylinder;
  19949. };
  19950. var parseTorus = function (parsedTorus, scene) {
  19951. if (parseGeometry(parsedTorus, scene)) {
  19952. return null; // null since geometry could be something else than a torus...
  19953. }
  19954. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19955. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19956. scene.pushGeometry(torus, true);
  19957. return torus;
  19958. };
  19959. var parseGround = function (parsedGround, scene) {
  19960. if (parseGeometry(parsedGround, scene)) {
  19961. return null; // null since geometry could be something else than a ground...
  19962. }
  19963. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19964. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19965. scene.pushGeometry(ground, true);
  19966. return ground;
  19967. };
  19968. var parsePlane = function (parsedPlane, scene) {
  19969. if (parseGeometry(parsedPlane, scene)) {
  19970. return null; // null since geometry could be something else than a plane...
  19971. }
  19972. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19973. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19974. scene.pushGeometry(plane, true);
  19975. return plane;
  19976. };
  19977. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19978. if (parseGeometry(parsedTorusKnot, scene)) {
  19979. return null; // null since geometry could be something else than a torusKnot...
  19980. }
  19981. 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);
  19982. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19983. scene.pushGeometry(torusKnot, true);
  19984. return torusKnot;
  19985. };
  19986. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19987. if (parseGeometry(parsedVertexData, scene)) {
  19988. return null; // null since geometry could be a primitive
  19989. }
  19990. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19991. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19992. if (parsedVertexData.delayLoadingFile) {
  19993. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19994. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19995. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19996. geometry._delayInfo = [];
  19997. if (parsedVertexData.hasUVs) {
  19998. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19999. }
  20000. if (parsedVertexData.hasUVs2) {
  20001. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20002. }
  20003. if (parsedVertexData.hasUVs3) {
  20004. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20005. }
  20006. if (parsedVertexData.hasUVs4) {
  20007. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20008. }
  20009. if (parsedVertexData.hasUVs5) {
  20010. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20011. }
  20012. if (parsedVertexData.hasUVs6) {
  20013. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20014. }
  20015. if (parsedVertexData.hasColors) {
  20016. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20017. }
  20018. if (parsedVertexData.hasMatricesIndices) {
  20019. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20020. }
  20021. if (parsedVertexData.hasMatricesWeights) {
  20022. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20023. }
  20024. geometry._delayLoadingFunction = importVertexData;
  20025. }
  20026. else {
  20027. importVertexData(parsedVertexData, geometry);
  20028. }
  20029. scene.pushGeometry(geometry, true);
  20030. return geometry;
  20031. };
  20032. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20033. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20034. mesh.id = parsedMesh.id;
  20035. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20036. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20037. if (parsedMesh.rotationQuaternion) {
  20038. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20039. }
  20040. else if (parsedMesh.rotation) {
  20041. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20042. }
  20043. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20044. if (parsedMesh.localMatrix) {
  20045. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20046. }
  20047. else if (parsedMesh.pivotMatrix) {
  20048. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20049. }
  20050. mesh.setEnabled(parsedMesh.isEnabled);
  20051. mesh.isVisible = parsedMesh.isVisible;
  20052. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20053. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20054. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20055. if (parsedMesh.applyFog !== undefined) {
  20056. mesh.applyFog = parsedMesh.applyFog;
  20057. }
  20058. if (parsedMesh.pickable !== undefined) {
  20059. mesh.isPickable = parsedMesh.pickable;
  20060. }
  20061. if (parsedMesh.alphaIndex !== undefined) {
  20062. mesh.alphaIndex = parsedMesh.alphaIndex;
  20063. }
  20064. mesh.receiveShadows = parsedMesh.receiveShadows;
  20065. mesh.billboardMode = parsedMesh.billboardMode;
  20066. if (parsedMesh.visibility !== undefined) {
  20067. mesh.visibility = parsedMesh.visibility;
  20068. }
  20069. mesh.checkCollisions = parsedMesh.checkCollisions;
  20070. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20071. // freezeWorldMatrix
  20072. if (parsedMesh.freezeWorldMatrix) {
  20073. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20074. }
  20075. // Parent
  20076. if (parsedMesh.parentId) {
  20077. mesh._waitingParentId = parsedMesh.parentId;
  20078. }
  20079. // Actions
  20080. if (parsedMesh.actions !== undefined) {
  20081. mesh._waitingActions = parsedMesh.actions;
  20082. }
  20083. // Geometry
  20084. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20085. if (parsedMesh.delayLoadingFile) {
  20086. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20087. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20088. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20089. if (parsedMesh._binaryInfo) {
  20090. mesh._binaryInfo = parsedMesh._binaryInfo;
  20091. }
  20092. mesh._delayInfo = [];
  20093. if (parsedMesh.hasUVs) {
  20094. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20095. }
  20096. if (parsedMesh.hasUVs2) {
  20097. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20098. }
  20099. if (parsedMesh.hasUVs3) {
  20100. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20101. }
  20102. if (parsedMesh.hasUVs4) {
  20103. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20104. }
  20105. if (parsedMesh.hasUVs5) {
  20106. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20107. }
  20108. if (parsedMesh.hasUVs6) {
  20109. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20110. }
  20111. if (parsedMesh.hasColors) {
  20112. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20113. }
  20114. if (parsedMesh.hasMatricesIndices) {
  20115. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20116. }
  20117. if (parsedMesh.hasMatricesWeights) {
  20118. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20119. }
  20120. mesh._delayLoadingFunction = importGeometry;
  20121. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20122. mesh._checkDelayState();
  20123. }
  20124. }
  20125. else {
  20126. importGeometry(parsedMesh, mesh);
  20127. }
  20128. // Material
  20129. if (parsedMesh.materialId) {
  20130. mesh.setMaterialByID(parsedMesh.materialId);
  20131. }
  20132. else {
  20133. mesh.material = null;
  20134. }
  20135. // Skeleton
  20136. if (parsedMesh.skeletonId > -1) {
  20137. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20138. }
  20139. // Physics
  20140. if (parsedMesh.physicsImpostor) {
  20141. if (!scene.isPhysicsEnabled()) {
  20142. scene.enablePhysics();
  20143. }
  20144. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20145. }
  20146. // Animations
  20147. if (parsedMesh.animations) {
  20148. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20149. var parsedAnimation = parsedMesh.animations[animationIndex];
  20150. mesh.animations.push(parseAnimation(parsedAnimation));
  20151. }
  20152. }
  20153. if (parsedMesh.autoAnimate) {
  20154. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20155. }
  20156. // Layer Mask
  20157. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20158. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20159. }
  20160. else {
  20161. mesh.layerMask = 0x0FFFFFFF;
  20162. }
  20163. // Instances
  20164. if (parsedMesh.instances) {
  20165. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20166. var parsedInstance = parsedMesh.instances[index];
  20167. var instance = mesh.createInstance(parsedInstance.name);
  20168. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20169. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20170. if (parsedInstance.rotationQuaternion) {
  20171. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20172. }
  20173. else if (parsedInstance.rotation) {
  20174. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20175. }
  20176. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20177. instance.checkCollisions = mesh.checkCollisions;
  20178. if (parsedMesh.animations) {
  20179. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20180. parsedAnimation = parsedMesh.animations[animationIndex];
  20181. instance.animations.push(parseAnimation(parsedAnimation));
  20182. }
  20183. }
  20184. }
  20185. }
  20186. return mesh;
  20187. };
  20188. var parseActions = function (parsedActions, object, scene) {
  20189. var actionManager = new BABYLON.ActionManager(scene);
  20190. if (object === null)
  20191. scene.actionManager = actionManager;
  20192. else
  20193. object.actionManager = actionManager;
  20194. // instanciate a new object
  20195. var instanciate = function (name, params) {
  20196. var newInstance = Object.create(BABYLON[name].prototype);
  20197. newInstance.constructor.apply(newInstance, params);
  20198. return newInstance;
  20199. };
  20200. var parseParameter = function (name, value, target, propertyPath) {
  20201. if (propertyPath === null) {
  20202. // String, boolean or float
  20203. var floatValue = parseFloat(value);
  20204. if (value === "true" || value === "false")
  20205. return value === "true";
  20206. else
  20207. return isNaN(floatValue) ? value : floatValue;
  20208. }
  20209. var effectiveTarget = propertyPath.split(".");
  20210. var values = value.split(",");
  20211. // Get effective Target
  20212. for (var i = 0; i < effectiveTarget.length; i++) {
  20213. target = target[effectiveTarget[i]];
  20214. }
  20215. // Return appropriate value with its type
  20216. if (typeof (target) === "boolean")
  20217. return values[0] === "true";
  20218. if (typeof (target) === "string")
  20219. return values[0];
  20220. // Parameters with multiple values such as Vector3 etc.
  20221. var split = new Array();
  20222. for (var i = 0; i < values.length; i++)
  20223. split.push(parseFloat(values[i]));
  20224. if (target instanceof BABYLON.Vector3)
  20225. return BABYLON.Vector3.FromArray(split);
  20226. if (target instanceof BABYLON.Vector4)
  20227. return BABYLON.Vector4.FromArray(split);
  20228. if (target instanceof BABYLON.Color3)
  20229. return BABYLON.Color3.FromArray(split);
  20230. if (target instanceof BABYLON.Color4)
  20231. return BABYLON.Color4.FromArray(split);
  20232. return parseFloat(values[0]);
  20233. };
  20234. // traverse graph per trigger
  20235. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20236. if (combineArray === void 0) { combineArray = null; }
  20237. if (parsedAction.detached)
  20238. return;
  20239. var parameters = new Array();
  20240. var target = null;
  20241. var propertyPath = null;
  20242. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20243. // Parameters
  20244. if (parsedAction.type === 2)
  20245. parameters.push(actionManager);
  20246. else
  20247. parameters.push(trigger);
  20248. if (combine) {
  20249. var actions = new Array();
  20250. for (var j = 0; j < parsedAction.combine.length; j++) {
  20251. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20252. }
  20253. parameters.push(actions);
  20254. }
  20255. else {
  20256. for (var i = 0; i < parsedAction.properties.length; i++) {
  20257. var value = parsedAction.properties[i].value;
  20258. var name = parsedAction.properties[i].name;
  20259. var targetType = parsedAction.properties[i].targetType;
  20260. if (name === "target")
  20261. if (targetType !== null && targetType === "SceneProperties")
  20262. value = target = scene;
  20263. else
  20264. value = target = scene.getNodeByName(value);
  20265. else if (name === "parent")
  20266. value = scene.getNodeByName(value);
  20267. else if (name === "sound")
  20268. value = scene.getSoundByName(value);
  20269. else if (name !== "propertyPath") {
  20270. if (parsedAction.type === 2 && name === "operator")
  20271. value = BABYLON.ValueCondition[value];
  20272. else
  20273. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20274. }
  20275. else {
  20276. propertyPath = value;
  20277. }
  20278. parameters.push(value);
  20279. }
  20280. }
  20281. if (combineArray === null) {
  20282. parameters.push(condition);
  20283. }
  20284. else {
  20285. parameters.push(null);
  20286. }
  20287. // If interpolate value action
  20288. if (parsedAction.name === "InterpolateValueAction") {
  20289. var param = parameters[parameters.length - 2];
  20290. parameters[parameters.length - 1] = param;
  20291. parameters[parameters.length - 2] = condition;
  20292. }
  20293. // Action or condition(s) and not CombineAction
  20294. var newAction = instanciate(parsedAction.name, parameters);
  20295. if (combineArray === null) {
  20296. if (newAction instanceof BABYLON.Condition) {
  20297. condition = newAction;
  20298. newAction = action;
  20299. }
  20300. else {
  20301. condition = null;
  20302. if (action)
  20303. action.then(newAction);
  20304. else
  20305. actionManager.registerAction(newAction);
  20306. }
  20307. }
  20308. else {
  20309. combineArray.push(newAction);
  20310. }
  20311. for (var i = 0; i < parsedAction.children.length; i++)
  20312. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20313. };
  20314. // triggers
  20315. for (var i = 0; i < parsedActions.children.length; i++) {
  20316. var triggerParams;
  20317. var trigger = parsedActions.children[i];
  20318. if (trigger.properties.length > 0) {
  20319. var param = trigger.properties[0].value;
  20320. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20321. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20322. }
  20323. else
  20324. triggerParams = BABYLON.ActionManager[trigger.name];
  20325. for (var j = 0; j < trigger.children.length; j++) {
  20326. if (!trigger.detached)
  20327. traverse(trigger.children[j], triggerParams, null, null);
  20328. }
  20329. }
  20330. };
  20331. var parseSound = function (parsedSound, scene, rootUrl) {
  20332. var soundName = parsedSound.name;
  20333. var soundUrl = rootUrl + soundName;
  20334. var options = {
  20335. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20336. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20337. rolloffFactor: parsedSound.rolloffFactor,
  20338. refDistance: parsedSound.refDistance,
  20339. distanceModel: parsedSound.distanceModel,
  20340. playbackRate: parsedSound.playbackRate
  20341. };
  20342. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20343. scene._addPendingData(newSound);
  20344. if (parsedSound.position) {
  20345. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20346. newSound.setPosition(soundPosition);
  20347. }
  20348. if (parsedSound.isDirectional) {
  20349. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20350. if (parsedSound.localDirectionToMesh) {
  20351. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20352. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20353. }
  20354. }
  20355. if (parsedSound.connectedMeshId) {
  20356. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20357. if (connectedMesh) {
  20358. newSound.attachToMesh(connectedMesh);
  20359. }
  20360. }
  20361. };
  20362. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20363. names = (names instanceof Array) ? names : [names];
  20364. for (var i in names) {
  20365. if (mesh.name === names[i]) {
  20366. hierarchyIds.push(mesh.id);
  20367. return true;
  20368. }
  20369. }
  20370. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20371. hierarchyIds.push(mesh.id);
  20372. return true;
  20373. }
  20374. return false;
  20375. };
  20376. var importVertexData = function (parsedVertexData, geometry) {
  20377. var vertexData = new BABYLON.VertexData();
  20378. // positions
  20379. var positions = parsedVertexData.positions;
  20380. if (positions) {
  20381. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20382. }
  20383. // normals
  20384. var normals = parsedVertexData.normals;
  20385. if (normals) {
  20386. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20387. }
  20388. // uvs
  20389. var uvs = parsedVertexData.uvs;
  20390. if (uvs) {
  20391. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20392. }
  20393. // uv2s
  20394. var uv2s = parsedVertexData.uv2s;
  20395. if (uv2s) {
  20396. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20397. }
  20398. // uv3s
  20399. var uv3s = parsedVertexData.uv3s;
  20400. if (uv3s) {
  20401. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20402. }
  20403. // uv4s
  20404. var uv4s = parsedVertexData.uv4s;
  20405. if (uv4s) {
  20406. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20407. }
  20408. // uv5s
  20409. var uv5s = parsedVertexData.uv5s;
  20410. if (uv5s) {
  20411. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20412. }
  20413. // uv6s
  20414. var uv6s = parsedVertexData.uv6s;
  20415. if (uv6s) {
  20416. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20417. }
  20418. // colors
  20419. var colors = parsedVertexData.colors;
  20420. if (colors) {
  20421. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20422. }
  20423. // matricesIndices
  20424. var matricesIndices = parsedVertexData.matricesIndices;
  20425. if (matricesIndices) {
  20426. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20427. }
  20428. // matricesWeights
  20429. var matricesWeights = parsedVertexData.matricesWeights;
  20430. if (matricesWeights) {
  20431. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20432. }
  20433. // indices
  20434. var indices = parsedVertexData.indices;
  20435. if (indices) {
  20436. vertexData.indices = indices;
  20437. }
  20438. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20439. };
  20440. var importGeometry = function (parsedGeometry, mesh) {
  20441. var scene = mesh.getScene();
  20442. // Geometry
  20443. var geometryId = parsedGeometry.geometryId;
  20444. if (geometryId) {
  20445. var geometry = scene.getGeometryByID(geometryId);
  20446. if (geometry) {
  20447. geometry.applyToMesh(mesh);
  20448. }
  20449. }
  20450. else if (parsedGeometry instanceof ArrayBuffer) {
  20451. var binaryInfo = mesh._binaryInfo;
  20452. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20453. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20454. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20455. }
  20456. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20457. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20458. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20459. }
  20460. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20461. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20462. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20463. }
  20464. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20465. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20466. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20467. }
  20468. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20469. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20470. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20471. }
  20472. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20473. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20474. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20475. }
  20476. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20477. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20478. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20479. }
  20480. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20481. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20482. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20483. }
  20484. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20485. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20486. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20487. }
  20488. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20489. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20490. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20491. }
  20492. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20493. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20494. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20495. }
  20496. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20497. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20498. mesh.setIndices(indicesData);
  20499. }
  20500. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20501. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20502. mesh.subMeshes = [];
  20503. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20504. var materialIndex = subMeshesData[(i * 5) + 0];
  20505. var verticesStart = subMeshesData[(i * 5) + 1];
  20506. var verticesCount = subMeshesData[(i * 5) + 2];
  20507. var indexStart = subMeshesData[(i * 5) + 3];
  20508. var indexCount = subMeshesData[(i * 5) + 4];
  20509. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20510. }
  20511. }
  20512. }
  20513. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20514. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20515. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20516. if (parsedGeometry.uvs) {
  20517. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20518. }
  20519. if (parsedGeometry.uvs2) {
  20520. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20521. }
  20522. if (parsedGeometry.uvs3) {
  20523. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20524. }
  20525. if (parsedGeometry.uvs4) {
  20526. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20527. }
  20528. if (parsedGeometry.uvs5) {
  20529. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20530. }
  20531. if (parsedGeometry.uvs6) {
  20532. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20533. }
  20534. if (parsedGeometry.colors) {
  20535. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20536. }
  20537. if (parsedGeometry.matricesIndices) {
  20538. if (!parsedGeometry.matricesIndices._isExpanded) {
  20539. var floatIndices = [];
  20540. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20541. var matricesIndex = parsedGeometry.matricesIndices[i];
  20542. floatIndices.push(matricesIndex & 0x000000FF);
  20543. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20544. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20545. floatIndices.push(matricesIndex >> 24);
  20546. }
  20547. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20548. }
  20549. else {
  20550. delete parsedGeometry.matricesIndices._isExpanded;
  20551. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20552. }
  20553. }
  20554. if (parsedGeometry.matricesWeights) {
  20555. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20556. }
  20557. mesh.setIndices(parsedGeometry.indices);
  20558. }
  20559. // SubMeshes
  20560. if (parsedGeometry.subMeshes) {
  20561. mesh.subMeshes = [];
  20562. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20563. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20564. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20565. }
  20566. }
  20567. // Flat shading
  20568. if (mesh._shouldGenerateFlatShading) {
  20569. mesh.convertToFlatShadedMesh();
  20570. delete mesh._shouldGenerateFlatShading;
  20571. }
  20572. // Update
  20573. mesh.computeWorldMatrix(true);
  20574. // Octree
  20575. if (scene._selectionOctree) {
  20576. scene._selectionOctree.addMesh(mesh);
  20577. }
  20578. };
  20579. BABYLON.SceneLoader.RegisterPlugin({
  20580. extensions: ".babylon",
  20581. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20582. var parsedData = JSON.parse(data);
  20583. var loadedSkeletonsIds = [];
  20584. var loadedMaterialsIds = [];
  20585. var hierarchyIds = [];
  20586. for (var index = 0; index < parsedData.meshes.length; index++) {
  20587. var parsedMesh = parsedData.meshes[index];
  20588. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20589. if (meshesNames instanceof Array) {
  20590. // Remove found mesh name from list.
  20591. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20592. }
  20593. //Geometry?
  20594. if (parsedMesh.geometryId) {
  20595. //does the file contain geometries?
  20596. if (parsedData.geometries) {
  20597. //find the correct geometry and add it to the scene
  20598. var found = false;
  20599. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20600. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20601. return;
  20602. }
  20603. else {
  20604. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20605. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20606. switch (geometryType) {
  20607. case "boxes":
  20608. parseBox(parsedGeometryData, scene);
  20609. break;
  20610. case "spheres":
  20611. parseSphere(parsedGeometryData, scene);
  20612. break;
  20613. case "cylinders":
  20614. parseCylinder(parsedGeometryData, scene);
  20615. break;
  20616. case "toruses":
  20617. parseTorus(parsedGeometryData, scene);
  20618. break;
  20619. case "grounds":
  20620. parseGround(parsedGeometryData, scene);
  20621. break;
  20622. case "planes":
  20623. parsePlane(parsedGeometryData, scene);
  20624. break;
  20625. case "torusKnots":
  20626. parseTorusKnot(parsedGeometryData, scene);
  20627. break;
  20628. case "vertexData":
  20629. parseVertexData(parsedGeometryData, scene, rootUrl);
  20630. break;
  20631. }
  20632. found = true;
  20633. }
  20634. });
  20635. }
  20636. });
  20637. if (!found) {
  20638. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20639. }
  20640. }
  20641. }
  20642. // Material ?
  20643. if (parsedMesh.materialId) {
  20644. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20645. if (!materialFound && parsedData.multiMaterials) {
  20646. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20647. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20648. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20649. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20650. var subMatId = parsedMultiMaterial.materials[matIndex];
  20651. loadedMaterialsIds.push(subMatId);
  20652. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20653. }
  20654. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20655. parseMultiMaterial(parsedMultiMaterial, scene);
  20656. materialFound = true;
  20657. break;
  20658. }
  20659. }
  20660. }
  20661. if (!materialFound) {
  20662. loadedMaterialsIds.push(parsedMesh.materialId);
  20663. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20664. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20665. }
  20666. }
  20667. }
  20668. // Skeleton ?
  20669. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20670. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20671. if (!skeletonAlreadyLoaded) {
  20672. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20673. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20674. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20675. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20676. loadedSkeletonsIds.push(parsedSkeleton.id);
  20677. }
  20678. }
  20679. }
  20680. }
  20681. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20682. meshes.push(mesh);
  20683. }
  20684. }
  20685. // Connecting parents
  20686. for (index = 0; index < scene.meshes.length; index++) {
  20687. var currentMesh = scene.meshes[index];
  20688. if (currentMesh._waitingParentId) {
  20689. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20690. currentMesh._waitingParentId = undefined;
  20691. }
  20692. }
  20693. // freeze world matrix application
  20694. for (index = 0; index < scene.meshes.length; index++) {
  20695. var currentMesh = scene.meshes[index];
  20696. if (currentMesh._waitingFreezeWorldMatrix) {
  20697. currentMesh.freezeWorldMatrix();
  20698. currentMesh._waitingFreezeWorldMatrix = undefined;
  20699. }
  20700. }
  20701. // Particles
  20702. if (parsedData.particleSystems) {
  20703. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20704. var parsedParticleSystem = parsedData.particleSystems[index];
  20705. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20706. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20707. }
  20708. }
  20709. }
  20710. return true;
  20711. },
  20712. load: function (scene, data, rootUrl) {
  20713. var parsedData = JSON.parse(data);
  20714. // Scene
  20715. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20716. scene.autoClear = parsedData.autoClear;
  20717. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20718. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20719. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20720. // Fog
  20721. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20722. scene.fogMode = parsedData.fogMode;
  20723. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20724. scene.fogStart = parsedData.fogStart;
  20725. scene.fogEnd = parsedData.fogEnd;
  20726. scene.fogDensity = parsedData.fogDensity;
  20727. }
  20728. // Lights
  20729. for (var index = 0; index < parsedData.lights.length; index++) {
  20730. var parsedLight = parsedData.lights[index];
  20731. parseLight(parsedLight, scene);
  20732. }
  20733. // Materials
  20734. if (parsedData.materials) {
  20735. for (index = 0; index < parsedData.materials.length; index++) {
  20736. var parsedMaterial = parsedData.materials[index];
  20737. parseMaterial(parsedMaterial, scene, rootUrl);
  20738. }
  20739. }
  20740. if (parsedData.multiMaterials) {
  20741. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20742. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20743. parseMultiMaterial(parsedMultiMaterial, scene);
  20744. }
  20745. }
  20746. // Skeletons
  20747. if (parsedData.skeletons) {
  20748. for (index = 0; index < parsedData.skeletons.length; index++) {
  20749. var parsedSkeleton = parsedData.skeletons[index];
  20750. parseSkeleton(parsedSkeleton, scene);
  20751. }
  20752. }
  20753. // Geometries
  20754. var geometries = parsedData.geometries;
  20755. if (geometries) {
  20756. // Boxes
  20757. var boxes = geometries.boxes;
  20758. if (boxes) {
  20759. for (index = 0; index < boxes.length; index++) {
  20760. var parsedBox = boxes[index];
  20761. parseBox(parsedBox, scene);
  20762. }
  20763. }
  20764. // Spheres
  20765. var spheres = geometries.spheres;
  20766. if (spheres) {
  20767. for (index = 0; index < spheres.length; index++) {
  20768. var parsedSphere = spheres[index];
  20769. parseSphere(parsedSphere, scene);
  20770. }
  20771. }
  20772. // Cylinders
  20773. var cylinders = geometries.cylinders;
  20774. if (cylinders) {
  20775. for (index = 0; index < cylinders.length; index++) {
  20776. var parsedCylinder = cylinders[index];
  20777. parseCylinder(parsedCylinder, scene);
  20778. }
  20779. }
  20780. // Toruses
  20781. var toruses = geometries.toruses;
  20782. if (toruses) {
  20783. for (index = 0; index < toruses.length; index++) {
  20784. var parsedTorus = toruses[index];
  20785. parseTorus(parsedTorus, scene);
  20786. }
  20787. }
  20788. // Grounds
  20789. var grounds = geometries.grounds;
  20790. if (grounds) {
  20791. for (index = 0; index < grounds.length; index++) {
  20792. var parsedGround = grounds[index];
  20793. parseGround(parsedGround, scene);
  20794. }
  20795. }
  20796. // Planes
  20797. var planes = geometries.planes;
  20798. if (planes) {
  20799. for (index = 0; index < planes.length; index++) {
  20800. var parsedPlane = planes[index];
  20801. parsePlane(parsedPlane, scene);
  20802. }
  20803. }
  20804. // TorusKnots
  20805. var torusKnots = geometries.torusKnots;
  20806. if (torusKnots) {
  20807. for (index = 0; index < torusKnots.length; index++) {
  20808. var parsedTorusKnot = torusKnots[index];
  20809. parseTorusKnot(parsedTorusKnot, scene);
  20810. }
  20811. }
  20812. // VertexData
  20813. var vertexData = geometries.vertexData;
  20814. if (vertexData) {
  20815. for (index = 0; index < vertexData.length; index++) {
  20816. var parsedVertexData = vertexData[index];
  20817. parseVertexData(parsedVertexData, scene, rootUrl);
  20818. }
  20819. }
  20820. }
  20821. // Meshes
  20822. for (index = 0; index < parsedData.meshes.length; index++) {
  20823. var parsedMesh = parsedData.meshes[index];
  20824. parseMesh(parsedMesh, scene, rootUrl);
  20825. }
  20826. // Cameras
  20827. for (index = 0; index < parsedData.cameras.length; index++) {
  20828. var parsedCamera = parsedData.cameras[index];
  20829. parseCamera(parsedCamera, scene);
  20830. }
  20831. if (parsedData.activeCameraID) {
  20832. scene.setActiveCameraByID(parsedData.activeCameraID);
  20833. }
  20834. // Browsing all the graph to connect the dots
  20835. for (index = 0; index < scene.cameras.length; index++) {
  20836. var camera = scene.cameras[index];
  20837. if (camera._waitingParentId) {
  20838. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20839. camera._waitingParentId = undefined;
  20840. }
  20841. }
  20842. for (index = 0; index < scene.lights.length; index++) {
  20843. var light = scene.lights[index];
  20844. if (light._waitingParentId) {
  20845. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20846. light._waitingParentId = undefined;
  20847. }
  20848. }
  20849. // Sounds
  20850. if (parsedData.sounds) {
  20851. for (index = 0; index < parsedData.sounds.length; index++) {
  20852. var parsedSound = parsedData.sounds[index];
  20853. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20854. parseSound(parsedSound, scene, rootUrl);
  20855. }
  20856. else {
  20857. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20858. }
  20859. }
  20860. }
  20861. // Connect parents & children and parse actions
  20862. for (index = 0; index < scene.meshes.length; index++) {
  20863. var mesh = scene.meshes[index];
  20864. if (mesh._waitingParentId) {
  20865. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20866. mesh._waitingParentId = undefined;
  20867. }
  20868. if (mesh._waitingActions) {
  20869. parseActions(mesh._waitingActions, mesh, scene);
  20870. mesh._waitingActions = undefined;
  20871. }
  20872. }
  20873. // freeze world matrix application
  20874. for (index = 0; index < scene.meshes.length; index++) {
  20875. var currentMesh = scene.meshes[index];
  20876. if (currentMesh._waitingFreezeWorldMatrix) {
  20877. currentMesh.freezeWorldMatrix();
  20878. currentMesh._waitingFreezeWorldMatrix = undefined;
  20879. }
  20880. }
  20881. // Particles Systems
  20882. if (parsedData.particleSystems) {
  20883. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20884. var parsedParticleSystem = parsedData.particleSystems[index];
  20885. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20886. }
  20887. }
  20888. // Lens flares
  20889. if (parsedData.lensFlareSystems) {
  20890. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20891. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20892. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20893. }
  20894. }
  20895. // Shadows
  20896. if (parsedData.shadowGenerators) {
  20897. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20898. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20899. parseShadowGenerator(parsedShadowGenerator, scene);
  20900. }
  20901. }
  20902. // Actions (scene)
  20903. if (parsedData.actions) {
  20904. parseActions(parsedData.actions, null, scene);
  20905. }
  20906. // Finish
  20907. return true;
  20908. }
  20909. });
  20910. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20911. })(BABYLON || (BABYLON = {}));
  20912. var BABYLON;
  20913. (function (BABYLON) {
  20914. var SpriteManager = (function () {
  20915. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20916. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20917. this.name = name;
  20918. this.cellSize = cellSize;
  20919. this.sprites = new Array();
  20920. this.renderingGroupId = 0;
  20921. this.fogEnabled = true;
  20922. this._vertexDeclaration = [4, 4, 4, 4];
  20923. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20924. this._capacity = capacity;
  20925. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20926. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20927. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20928. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20929. this._scene = scene;
  20930. this._scene.spriteManagers.push(this);
  20931. // VBO
  20932. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20933. var indices = [];
  20934. var index = 0;
  20935. for (var count = 0; count < capacity; count++) {
  20936. indices.push(index);
  20937. indices.push(index + 1);
  20938. indices.push(index + 2);
  20939. indices.push(index);
  20940. indices.push(index + 2);
  20941. indices.push(index + 3);
  20942. index += 4;
  20943. }
  20944. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20945. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20946. // Effects
  20947. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20948. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20949. }
  20950. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20951. var arrayOffset = index * 16;
  20952. if (offsetX === 0)
  20953. offsetX = this._epsilon;
  20954. else if (offsetX === 1)
  20955. offsetX = 1 - this._epsilon;
  20956. if (offsetY === 0)
  20957. offsetY = this._epsilon;
  20958. else if (offsetY === 1)
  20959. offsetY = 1 - this._epsilon;
  20960. this._vertices[arrayOffset] = sprite.position.x;
  20961. this._vertices[arrayOffset + 1] = sprite.position.y;
  20962. this._vertices[arrayOffset + 2] = sprite.position.z;
  20963. this._vertices[arrayOffset + 3] = sprite.angle;
  20964. this._vertices[arrayOffset + 4] = sprite.width;
  20965. this._vertices[arrayOffset + 5] = sprite.height;
  20966. this._vertices[arrayOffset + 6] = offsetX;
  20967. this._vertices[arrayOffset + 7] = offsetY;
  20968. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20969. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20970. var offset = (sprite.cellIndex / rowSize) >> 0;
  20971. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20972. this._vertices[arrayOffset + 11] = offset;
  20973. // Color
  20974. this._vertices[arrayOffset + 12] = sprite.color.r;
  20975. this._vertices[arrayOffset + 13] = sprite.color.g;
  20976. this._vertices[arrayOffset + 14] = sprite.color.b;
  20977. this._vertices[arrayOffset + 15] = sprite.color.a;
  20978. };
  20979. SpriteManager.prototype.render = function () {
  20980. // Check
  20981. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20982. return;
  20983. var engine = this._scene.getEngine();
  20984. var baseSize = this._spriteTexture.getBaseSize();
  20985. // Sprites
  20986. var deltaTime = engine.getDeltaTime();
  20987. var max = Math.min(this._capacity, this.sprites.length);
  20988. var rowSize = baseSize.width / this.cellSize;
  20989. var offset = 0;
  20990. for (var index = 0; index < max; index++) {
  20991. var sprite = this.sprites[index];
  20992. if (!sprite) {
  20993. continue;
  20994. }
  20995. sprite._animate(deltaTime);
  20996. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20997. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20998. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20999. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  21000. }
  21001. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21002. // Render
  21003. var effect = this._effectBase;
  21004. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21005. effect = this._effectFog;
  21006. }
  21007. engine.enableEffect(effect);
  21008. var viewMatrix = this._scene.getViewMatrix();
  21009. effect.setTexture("diffuseSampler", this._spriteTexture);
  21010. effect.setMatrix("view", viewMatrix);
  21011. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21012. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  21013. // Fog
  21014. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  21015. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  21016. effect.setColor3("vFogColor", this._scene.fogColor);
  21017. }
  21018. // VBOs
  21019. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21020. // Draw order
  21021. engine.setDepthFunctionToLessOrEqual();
  21022. effect.setBool("alphaTest", true);
  21023. engine.setColorWrite(false);
  21024. engine.draw(true, 0, max * 6);
  21025. engine.setColorWrite(true);
  21026. effect.setBool("alphaTest", false);
  21027. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21028. engine.draw(true, 0, max * 6);
  21029. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21030. };
  21031. SpriteManager.prototype.dispose = function () {
  21032. if (this._vertexBuffer) {
  21033. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21034. this._vertexBuffer = null;
  21035. }
  21036. if (this._indexBuffer) {
  21037. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21038. this._indexBuffer = null;
  21039. }
  21040. if (this._spriteTexture) {
  21041. this._spriteTexture.dispose();
  21042. this._spriteTexture = null;
  21043. }
  21044. // Remove from scene
  21045. var index = this._scene.spriteManagers.indexOf(this);
  21046. this._scene.spriteManagers.splice(index, 1);
  21047. // Callback
  21048. if (this.onDispose) {
  21049. this.onDispose();
  21050. }
  21051. };
  21052. return SpriteManager;
  21053. })();
  21054. BABYLON.SpriteManager = SpriteManager;
  21055. })(BABYLON || (BABYLON = {}));
  21056. var BABYLON;
  21057. (function (BABYLON) {
  21058. var Sprite = (function () {
  21059. function Sprite(name, manager) {
  21060. this.name = name;
  21061. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21062. this.width = 1.0;
  21063. this.height = 1.0;
  21064. this.angle = 0;
  21065. this.cellIndex = 0;
  21066. this.invertU = 0;
  21067. this.invertV = 0;
  21068. this.animations = new Array();
  21069. this._animationStarted = false;
  21070. this._loopAnimation = false;
  21071. this._fromIndex = 0;
  21072. this._toIndex = 0;
  21073. this._delay = 0;
  21074. this._direction = 1;
  21075. this._frameCount = 0;
  21076. this._time = 0;
  21077. this._manager = manager;
  21078. this._manager.sprites.push(this);
  21079. this.position = BABYLON.Vector3.Zero();
  21080. }
  21081. Object.defineProperty(Sprite.prototype, "size", {
  21082. get: function () {
  21083. return this.width;
  21084. },
  21085. set: function (value) {
  21086. this.width = value;
  21087. this.height = value;
  21088. },
  21089. enumerable: true,
  21090. configurable: true
  21091. });
  21092. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21093. this._fromIndex = from;
  21094. this._toIndex = to;
  21095. this._loopAnimation = loop;
  21096. this._delay = delay;
  21097. this._animationStarted = true;
  21098. this._direction = from < to ? 1 : -1;
  21099. this.cellIndex = from;
  21100. this._time = 0;
  21101. };
  21102. Sprite.prototype.stopAnimation = function () {
  21103. this._animationStarted = false;
  21104. };
  21105. Sprite.prototype._animate = function (deltaTime) {
  21106. if (!this._animationStarted)
  21107. return;
  21108. this._time += deltaTime;
  21109. if (this._time > this._delay) {
  21110. this._time = this._time % this._delay;
  21111. this.cellIndex += this._direction;
  21112. if (this.cellIndex == this._toIndex) {
  21113. if (this._loopAnimation) {
  21114. this.cellIndex = this._fromIndex;
  21115. }
  21116. else {
  21117. this._animationStarted = false;
  21118. if (this.disposeWhenFinishedAnimating) {
  21119. this.dispose();
  21120. }
  21121. }
  21122. }
  21123. }
  21124. };
  21125. Sprite.prototype.dispose = function () {
  21126. for (var i = 0; i < this._manager.sprites.length; i++) {
  21127. if (this._manager.sprites[i] == this) {
  21128. this._manager.sprites.splice(i, 1);
  21129. }
  21130. }
  21131. };
  21132. return Sprite;
  21133. })();
  21134. BABYLON.Sprite = Sprite;
  21135. })(BABYLON || (BABYLON = {}));
  21136. var BABYLON;
  21137. (function (BABYLON) {
  21138. var Layer = (function () {
  21139. function Layer(name, imgUrl, scene, isBackground, color) {
  21140. this.name = name;
  21141. this._vertexDeclaration = [2];
  21142. this._vertexStrideSize = 2 * 4;
  21143. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21144. this.isBackground = isBackground === undefined ? true : isBackground;
  21145. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21146. this._scene = scene;
  21147. this._scene.layers.push(this);
  21148. // VBO
  21149. var vertices = [];
  21150. vertices.push(1, 1);
  21151. vertices.push(-1, 1);
  21152. vertices.push(-1, -1);
  21153. vertices.push(1, -1);
  21154. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21155. // Indices
  21156. var indices = [];
  21157. indices.push(0);
  21158. indices.push(1);
  21159. indices.push(2);
  21160. indices.push(0);
  21161. indices.push(2);
  21162. indices.push(3);
  21163. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21164. // Effects
  21165. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21166. }
  21167. Layer.prototype.render = function () {
  21168. // Check
  21169. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21170. return;
  21171. var engine = this._scene.getEngine();
  21172. // Render
  21173. engine.enableEffect(this._effect);
  21174. engine.setState(false);
  21175. // Texture
  21176. this._effect.setTexture("textureSampler", this.texture);
  21177. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21178. // Color
  21179. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21180. // VBOs
  21181. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21182. // Draw order
  21183. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21184. engine.draw(true, 0, 6);
  21185. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21186. };
  21187. Layer.prototype.dispose = function () {
  21188. if (this._vertexBuffer) {
  21189. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21190. this._vertexBuffer = null;
  21191. }
  21192. if (this._indexBuffer) {
  21193. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21194. this._indexBuffer = null;
  21195. }
  21196. if (this.texture) {
  21197. this.texture.dispose();
  21198. this.texture = null;
  21199. }
  21200. // Remove from scene
  21201. var index = this._scene.layers.indexOf(this);
  21202. this._scene.layers.splice(index, 1);
  21203. // Callback
  21204. if (this.onDispose) {
  21205. this.onDispose();
  21206. }
  21207. };
  21208. return Layer;
  21209. })();
  21210. BABYLON.Layer = Layer;
  21211. })(BABYLON || (BABYLON = {}));
  21212. var BABYLON;
  21213. (function (BABYLON) {
  21214. var Particle = (function () {
  21215. function Particle() {
  21216. this.position = BABYLON.Vector3.Zero();
  21217. this.direction = BABYLON.Vector3.Zero();
  21218. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21219. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21220. this.lifeTime = 1.0;
  21221. this.age = 0;
  21222. this.size = 0;
  21223. this.angle = 0;
  21224. this.angularSpeed = 0;
  21225. }
  21226. Particle.prototype.copyTo = function (other) {
  21227. other.position.copyFrom(this.position);
  21228. other.direction.copyFrom(this.direction);
  21229. other.color.copyFrom(this.color);
  21230. other.colorStep.copyFrom(this.colorStep);
  21231. other.lifeTime = this.lifeTime;
  21232. other.age = this.age;
  21233. other.size = this.size;
  21234. other.angle = this.angle;
  21235. other.angularSpeed = this.angularSpeed;
  21236. };
  21237. return Particle;
  21238. })();
  21239. BABYLON.Particle = Particle;
  21240. })(BABYLON || (BABYLON = {}));
  21241. var BABYLON;
  21242. (function (BABYLON) {
  21243. var randomNumber = function (min, max) {
  21244. if (min === max) {
  21245. return (min);
  21246. }
  21247. var random = Math.random();
  21248. return ((random * (max - min)) + min);
  21249. };
  21250. var ParticleSystem = (function () {
  21251. function ParticleSystem(name, capacity, scene, customEffect) {
  21252. var _this = this;
  21253. this.name = name;
  21254. this.renderingGroupId = 0;
  21255. this.emitter = null;
  21256. this.emitRate = 10;
  21257. this.manualEmitCount = -1;
  21258. this.updateSpeed = 0.01;
  21259. this.targetStopDuration = 0;
  21260. this.disposeOnStop = false;
  21261. this.minEmitPower = 1;
  21262. this.maxEmitPower = 1;
  21263. this.minLifeTime = 1;
  21264. this.maxLifeTime = 1;
  21265. this.minSize = 1;
  21266. this.maxSize = 1;
  21267. this.minAngularSpeed = 0;
  21268. this.maxAngularSpeed = 0;
  21269. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21270. this.forceDepthWrite = false;
  21271. this.gravity = BABYLON.Vector3.Zero();
  21272. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21273. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21274. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21275. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21276. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21277. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21278. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21279. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21280. this.particles = new Array();
  21281. this._vertexDeclaration = [3, 4, 4];
  21282. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21283. this._stockParticles = new Array();
  21284. this._newPartsExcess = 0;
  21285. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21286. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21287. this._scaledDirection = BABYLON.Vector3.Zero();
  21288. this._scaledGravity = BABYLON.Vector3.Zero();
  21289. this._currentRenderId = -1;
  21290. this._started = false;
  21291. this._stopped = false;
  21292. this._actualFrame = 0;
  21293. this.id = name;
  21294. this._capacity = capacity;
  21295. this._scene = scene;
  21296. this._customEffect = customEffect;
  21297. scene.particleSystems.push(this);
  21298. // VBO
  21299. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21300. var indices = [];
  21301. var index = 0;
  21302. for (var count = 0; count < capacity; count++) {
  21303. indices.push(index);
  21304. indices.push(index + 1);
  21305. indices.push(index + 2);
  21306. indices.push(index);
  21307. indices.push(index + 2);
  21308. indices.push(index + 3);
  21309. index += 4;
  21310. }
  21311. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21312. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21313. // Default behaviors
  21314. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21315. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21316. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21317. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21318. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21319. };
  21320. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21321. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21322. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21323. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21324. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21325. };
  21326. this.updateFunction = function (particles) {
  21327. for (var index = 0; index < particles.length; index++) {
  21328. var particle = particles[index];
  21329. particle.age += _this._scaledUpdateSpeed;
  21330. if (particle.age >= particle.lifeTime) {
  21331. _this.recycleParticle(particle);
  21332. index--;
  21333. continue;
  21334. }
  21335. else {
  21336. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21337. particle.color.addInPlace(_this._scaledColorStep);
  21338. if (particle.color.a < 0)
  21339. particle.color.a = 0;
  21340. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21341. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21342. particle.position.addInPlace(_this._scaledDirection);
  21343. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21344. particle.direction.addInPlace(_this._scaledGravity);
  21345. }
  21346. }
  21347. };
  21348. }
  21349. ParticleSystem.prototype.recycleParticle = function (particle) {
  21350. var lastParticle = this.particles.pop();
  21351. if (lastParticle !== particle) {
  21352. lastParticle.copyTo(particle);
  21353. this._stockParticles.push(lastParticle);
  21354. }
  21355. };
  21356. ParticleSystem.prototype.getCapacity = function () {
  21357. return this._capacity;
  21358. };
  21359. ParticleSystem.prototype.isAlive = function () {
  21360. return this._alive;
  21361. };
  21362. ParticleSystem.prototype.isStarted = function () {
  21363. return this._started;
  21364. };
  21365. ParticleSystem.prototype.start = function () {
  21366. this._started = true;
  21367. this._stopped = false;
  21368. this._actualFrame = 0;
  21369. };
  21370. ParticleSystem.prototype.stop = function () {
  21371. this._stopped = true;
  21372. };
  21373. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21374. var offset = index * 11;
  21375. this._vertices[offset] = particle.position.x;
  21376. this._vertices[offset + 1] = particle.position.y;
  21377. this._vertices[offset + 2] = particle.position.z;
  21378. this._vertices[offset + 3] = particle.color.r;
  21379. this._vertices[offset + 4] = particle.color.g;
  21380. this._vertices[offset + 5] = particle.color.b;
  21381. this._vertices[offset + 6] = particle.color.a;
  21382. this._vertices[offset + 7] = particle.angle;
  21383. this._vertices[offset + 8] = particle.size;
  21384. this._vertices[offset + 9] = offsetX;
  21385. this._vertices[offset + 10] = offsetY;
  21386. };
  21387. ParticleSystem.prototype._update = function (newParticles) {
  21388. // Update current
  21389. this._alive = this.particles.length > 0;
  21390. this.updateFunction(this.particles);
  21391. // Add new ones
  21392. var worldMatrix;
  21393. if (this.emitter.position) {
  21394. worldMatrix = this.emitter.getWorldMatrix();
  21395. }
  21396. else {
  21397. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21398. }
  21399. for (var index = 0; index < newParticles; index++) {
  21400. if (this.particles.length === this._capacity) {
  21401. break;
  21402. }
  21403. if (this._stockParticles.length !== 0) {
  21404. var particle = this._stockParticles.pop();
  21405. particle.age = 0;
  21406. }
  21407. else {
  21408. particle = new BABYLON.Particle();
  21409. }
  21410. this.particles.push(particle);
  21411. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21412. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21413. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21414. particle.size = randomNumber(this.minSize, this.maxSize);
  21415. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21416. this.startPositionFunction(worldMatrix, particle.position);
  21417. var step = randomNumber(0, 1.0);
  21418. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21419. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21420. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21421. }
  21422. };
  21423. ParticleSystem.prototype._getEffect = function () {
  21424. if (this._customEffect) {
  21425. return this._customEffect;
  21426. }
  21427. ;
  21428. var defines = [];
  21429. if (this._scene.clipPlane) {
  21430. defines.push("#define CLIPPLANE");
  21431. }
  21432. // Effect
  21433. var join = defines.join("\n");
  21434. if (this._cachedDefines !== join) {
  21435. this._cachedDefines = join;
  21436. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21437. }
  21438. return this._effect;
  21439. };
  21440. ParticleSystem.prototype.animate = function () {
  21441. if (!this._started)
  21442. return;
  21443. var effect = this._getEffect();
  21444. // Check
  21445. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21446. return;
  21447. if (this._currentRenderId === this._scene.getRenderId()) {
  21448. return;
  21449. }
  21450. this._currentRenderId = this._scene.getRenderId();
  21451. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21452. // determine the number of particles we need to create
  21453. var emitCout;
  21454. if (this.manualEmitCount > -1) {
  21455. emitCout = this.manualEmitCount;
  21456. this.manualEmitCount = 0;
  21457. }
  21458. else {
  21459. emitCout = this.emitRate;
  21460. }
  21461. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21462. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21463. if (this._newPartsExcess > 1.0) {
  21464. newParticles += this._newPartsExcess >> 0;
  21465. this._newPartsExcess -= this._newPartsExcess >> 0;
  21466. }
  21467. this._alive = false;
  21468. if (!this._stopped) {
  21469. this._actualFrame += this._scaledUpdateSpeed;
  21470. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21471. this.stop();
  21472. }
  21473. else {
  21474. newParticles = 0;
  21475. }
  21476. this._update(newParticles);
  21477. // Stopped?
  21478. if (this._stopped) {
  21479. if (!this._alive) {
  21480. this._started = false;
  21481. if (this.disposeOnStop) {
  21482. this._scene._toBeDisposed.push(this);
  21483. }
  21484. }
  21485. }
  21486. // Update VBO
  21487. var offset = 0;
  21488. for (var index = 0; index < this.particles.length; index++) {
  21489. var particle = this.particles[index];
  21490. this._appendParticleVertex(offset++, particle, 0, 0);
  21491. this._appendParticleVertex(offset++, particle, 1, 0);
  21492. this._appendParticleVertex(offset++, particle, 1, 1);
  21493. this._appendParticleVertex(offset++, particle, 0, 1);
  21494. }
  21495. var engine = this._scene.getEngine();
  21496. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21497. };
  21498. ParticleSystem.prototype.render = function () {
  21499. var effect = this._getEffect();
  21500. // Check
  21501. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21502. return 0;
  21503. var engine = this._scene.getEngine();
  21504. // Render
  21505. engine.enableEffect(effect);
  21506. engine.setState(false);
  21507. var viewMatrix = this._scene.getViewMatrix();
  21508. effect.setTexture("diffuseSampler", this.particleTexture);
  21509. effect.setMatrix("view", viewMatrix);
  21510. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21511. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21512. if (this._scene.clipPlane) {
  21513. var clipPlane = this._scene.clipPlane;
  21514. var invView = viewMatrix.clone();
  21515. invView.invert();
  21516. effect.setMatrix("invView", invView);
  21517. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21518. }
  21519. // VBOs
  21520. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21521. // Draw order
  21522. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21523. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21524. }
  21525. else {
  21526. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21527. }
  21528. if (this.forceDepthWrite) {
  21529. engine.setDepthWrite(true);
  21530. }
  21531. engine.draw(true, 0, this.particles.length * 6);
  21532. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21533. return this.particles.length;
  21534. };
  21535. ParticleSystem.prototype.dispose = function () {
  21536. if (this._vertexBuffer) {
  21537. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21538. this._vertexBuffer = null;
  21539. }
  21540. if (this._indexBuffer) {
  21541. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21542. this._indexBuffer = null;
  21543. }
  21544. if (this.particleTexture) {
  21545. this.particleTexture.dispose();
  21546. this.particleTexture = null;
  21547. }
  21548. // Remove from scene
  21549. var index = this._scene.particleSystems.indexOf(this);
  21550. this._scene.particleSystems.splice(index, 1);
  21551. // Callback
  21552. if (this.onDispose) {
  21553. this.onDispose();
  21554. }
  21555. };
  21556. // Clone
  21557. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21558. var result = new ParticleSystem(name, this._capacity, this._scene);
  21559. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21560. if (newEmitter === undefined) {
  21561. newEmitter = this.emitter;
  21562. }
  21563. result.emitter = newEmitter;
  21564. if (this.particleTexture) {
  21565. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21566. }
  21567. result.start();
  21568. return result;
  21569. };
  21570. // Statics
  21571. ParticleSystem.BLENDMODE_ONEONE = 0;
  21572. ParticleSystem.BLENDMODE_STANDARD = 1;
  21573. return ParticleSystem;
  21574. })();
  21575. BABYLON.ParticleSystem = ParticleSystem;
  21576. })(BABYLON || (BABYLON = {}));
  21577. var BABYLON;
  21578. (function (BABYLON) {
  21579. var Animation = (function () {
  21580. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21581. this.name = name;
  21582. this.targetProperty = targetProperty;
  21583. this.framePerSecond = framePerSecond;
  21584. this.dataType = dataType;
  21585. this.loopMode = loopMode;
  21586. this._offsetsCache = {};
  21587. this._highLimitsCache = {};
  21588. this._stopped = false;
  21589. this.allowMatricesInterpolation = false;
  21590. this.targetPropertyPath = targetProperty.split(".");
  21591. this.dataType = dataType;
  21592. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21593. }
  21594. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21595. var dataType = undefined;
  21596. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21597. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21598. }
  21599. else if (from instanceof BABYLON.Quaternion) {
  21600. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21601. }
  21602. else if (from instanceof BABYLON.Vector3) {
  21603. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21604. }
  21605. else if (from instanceof BABYLON.Vector2) {
  21606. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21607. }
  21608. else if (from instanceof BABYLON.Color3) {
  21609. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21610. }
  21611. if (dataType == undefined) {
  21612. return null;
  21613. }
  21614. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21615. var keys = [];
  21616. keys.push({ frame: 0, value: from });
  21617. keys.push({ frame: totalFrame, value: to });
  21618. animation.setKeys(keys);
  21619. if (easingFunction !== undefined) {
  21620. animation.setEasingFunction(easingFunction);
  21621. }
  21622. mesh.animations.push(animation);
  21623. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  21624. };
  21625. // Methods
  21626. Animation.prototype.reset = function () {
  21627. this._offsetsCache = {};
  21628. this._highLimitsCache = {};
  21629. this.currentFrame = 0;
  21630. };
  21631. Animation.prototype.isStopped = function () {
  21632. return this._stopped;
  21633. };
  21634. Animation.prototype.getKeys = function () {
  21635. return this._keys;
  21636. };
  21637. Animation.prototype.getEasingFunction = function () {
  21638. return this._easingFunction;
  21639. };
  21640. Animation.prototype.setEasingFunction = function (easingFunction) {
  21641. this._easingFunction = easingFunction;
  21642. };
  21643. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21644. return startValue + (endValue - startValue) * gradient;
  21645. };
  21646. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21647. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21648. };
  21649. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21650. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21651. };
  21652. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21653. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21654. };
  21655. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21656. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21657. };
  21658. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21659. var startScale = new BABYLON.Vector3(0, 0, 0);
  21660. var startRotation = new BABYLON.Quaternion();
  21661. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21662. startValue.decompose(startScale, startRotation, startTranslation);
  21663. var endScale = new BABYLON.Vector3(0, 0, 0);
  21664. var endRotation = new BABYLON.Quaternion();
  21665. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21666. endValue.decompose(endScale, endRotation, endTranslation);
  21667. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21668. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21669. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21670. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21671. return result;
  21672. };
  21673. Animation.prototype.clone = function () {
  21674. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21675. clone.setKeys(this._keys);
  21676. return clone;
  21677. };
  21678. Animation.prototype.setKeys = function (values) {
  21679. this._keys = values.slice(0);
  21680. this._offsetsCache = {};
  21681. this._highLimitsCache = {};
  21682. };
  21683. Animation.prototype._getKeyValue = function (value) {
  21684. if (typeof value === "function") {
  21685. return value();
  21686. }
  21687. return value;
  21688. };
  21689. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21690. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21691. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21692. }
  21693. this.currentFrame = currentFrame;
  21694. // Try to get a hash to find the right key
  21695. 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));
  21696. if (this._keys[startKey].frame >= currentFrame) {
  21697. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21698. startKey--;
  21699. }
  21700. }
  21701. for (var key = startKey; key < this._keys.length; key++) {
  21702. if (this._keys[key + 1].frame >= currentFrame) {
  21703. var startValue = this._getKeyValue(this._keys[key].value);
  21704. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21705. // gradient : percent of currentFrame between the frame inf and the frame sup
  21706. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21707. // check for easingFunction and correction of gradient
  21708. if (this._easingFunction != null) {
  21709. gradient = this._easingFunction.ease(gradient);
  21710. }
  21711. switch (this.dataType) {
  21712. // Float
  21713. case Animation.ANIMATIONTYPE_FLOAT:
  21714. switch (loopMode) {
  21715. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21716. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21717. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21718. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21719. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21720. }
  21721. break;
  21722. // Quaternion
  21723. case Animation.ANIMATIONTYPE_QUATERNION:
  21724. var quaternion = null;
  21725. switch (loopMode) {
  21726. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21727. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21728. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21729. break;
  21730. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21731. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21732. break;
  21733. }
  21734. return quaternion;
  21735. // Vector3
  21736. case Animation.ANIMATIONTYPE_VECTOR3:
  21737. switch (loopMode) {
  21738. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21739. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21740. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21741. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21742. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21743. }
  21744. // Vector2
  21745. case Animation.ANIMATIONTYPE_VECTOR2:
  21746. switch (loopMode) {
  21747. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21748. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21749. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21750. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21751. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21752. }
  21753. // Color3
  21754. case Animation.ANIMATIONTYPE_COLOR3:
  21755. switch (loopMode) {
  21756. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21757. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21758. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21759. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21760. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21761. }
  21762. // Matrix
  21763. case Animation.ANIMATIONTYPE_MATRIX:
  21764. switch (loopMode) {
  21765. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21766. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21767. if (this.allowMatricesInterpolation) {
  21768. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21769. }
  21770. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21771. return startValue;
  21772. }
  21773. default:
  21774. break;
  21775. }
  21776. break;
  21777. }
  21778. }
  21779. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21780. };
  21781. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21782. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21783. this._stopped = true;
  21784. return false;
  21785. }
  21786. var returnValue = true;
  21787. // Adding a start key at frame 0 if missing
  21788. if (this._keys[0].frame !== 0) {
  21789. var newKey = { frame: 0, value: this._keys[0].value };
  21790. this._keys.splice(0, 0, newKey);
  21791. }
  21792. // Check limits
  21793. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21794. from = this._keys[0].frame;
  21795. }
  21796. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21797. to = this._keys[this._keys.length - 1].frame;
  21798. }
  21799. // Compute ratio
  21800. var range = to - from;
  21801. var offsetValue;
  21802. // ratio represents the frame delta between from and to
  21803. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21804. var highLimitValue = 0;
  21805. if (ratio > range && !loop) {
  21806. returnValue = false;
  21807. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21808. }
  21809. else {
  21810. // Get max value if required
  21811. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21812. var keyOffset = to.toString() + from.toString();
  21813. if (!this._offsetsCache[keyOffset]) {
  21814. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21815. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21816. switch (this.dataType) {
  21817. // Float
  21818. case Animation.ANIMATIONTYPE_FLOAT:
  21819. this._offsetsCache[keyOffset] = toValue - fromValue;
  21820. break;
  21821. // Quaternion
  21822. case Animation.ANIMATIONTYPE_QUATERNION:
  21823. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21824. break;
  21825. // Vector3
  21826. case Animation.ANIMATIONTYPE_VECTOR3:
  21827. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21828. // Vector2
  21829. case Animation.ANIMATIONTYPE_VECTOR2:
  21830. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21831. // Color3
  21832. case Animation.ANIMATIONTYPE_COLOR3:
  21833. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21834. default:
  21835. break;
  21836. }
  21837. this._highLimitsCache[keyOffset] = toValue;
  21838. }
  21839. highLimitValue = this._highLimitsCache[keyOffset];
  21840. offsetValue = this._offsetsCache[keyOffset];
  21841. }
  21842. }
  21843. if (offsetValue === undefined) {
  21844. switch (this.dataType) {
  21845. // Float
  21846. case Animation.ANIMATIONTYPE_FLOAT:
  21847. offsetValue = 0;
  21848. break;
  21849. // Quaternion
  21850. case Animation.ANIMATIONTYPE_QUATERNION:
  21851. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21852. break;
  21853. // Vector3
  21854. case Animation.ANIMATIONTYPE_VECTOR3:
  21855. offsetValue = BABYLON.Vector3.Zero();
  21856. break;
  21857. // Vector2
  21858. case Animation.ANIMATIONTYPE_VECTOR2:
  21859. offsetValue = BABYLON.Vector2.Zero();
  21860. break;
  21861. // Color3
  21862. case Animation.ANIMATIONTYPE_COLOR3:
  21863. offsetValue = BABYLON.Color3.Black();
  21864. }
  21865. }
  21866. // Compute value
  21867. var repeatCount = (ratio / range) >> 0;
  21868. var currentFrame = returnValue ? from + ratio % range : to;
  21869. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21870. // Set value
  21871. if (this.targetPropertyPath.length > 1) {
  21872. var property = this._target[this.targetPropertyPath[0]];
  21873. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21874. property = property[this.targetPropertyPath[index]];
  21875. }
  21876. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21877. }
  21878. else {
  21879. this._target[this.targetPropertyPath[0]] = currentValue;
  21880. }
  21881. if (this._target.markAsDirty) {
  21882. this._target.markAsDirty(this.targetProperty);
  21883. }
  21884. if (!returnValue) {
  21885. this._stopped = true;
  21886. }
  21887. return returnValue;
  21888. };
  21889. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21890. get: function () {
  21891. return Animation._ANIMATIONTYPE_FLOAT;
  21892. },
  21893. enumerable: true,
  21894. configurable: true
  21895. });
  21896. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21897. get: function () {
  21898. return Animation._ANIMATIONTYPE_VECTOR3;
  21899. },
  21900. enumerable: true,
  21901. configurable: true
  21902. });
  21903. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21904. get: function () {
  21905. return Animation._ANIMATIONTYPE_VECTOR2;
  21906. },
  21907. enumerable: true,
  21908. configurable: true
  21909. });
  21910. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21911. get: function () {
  21912. return Animation._ANIMATIONTYPE_QUATERNION;
  21913. },
  21914. enumerable: true,
  21915. configurable: true
  21916. });
  21917. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21918. get: function () {
  21919. return Animation._ANIMATIONTYPE_MATRIX;
  21920. },
  21921. enumerable: true,
  21922. configurable: true
  21923. });
  21924. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21925. get: function () {
  21926. return Animation._ANIMATIONTYPE_COLOR3;
  21927. },
  21928. enumerable: true,
  21929. configurable: true
  21930. });
  21931. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21932. get: function () {
  21933. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21934. },
  21935. enumerable: true,
  21936. configurable: true
  21937. });
  21938. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21939. get: function () {
  21940. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21941. },
  21942. enumerable: true,
  21943. configurable: true
  21944. });
  21945. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21946. get: function () {
  21947. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21948. },
  21949. enumerable: true,
  21950. configurable: true
  21951. });
  21952. // Statics
  21953. Animation._ANIMATIONTYPE_FLOAT = 0;
  21954. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21955. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21956. Animation._ANIMATIONTYPE_MATRIX = 3;
  21957. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21958. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21959. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21960. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21961. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21962. return Animation;
  21963. })();
  21964. BABYLON.Animation = Animation;
  21965. })(BABYLON || (BABYLON = {}));
  21966. var BABYLON;
  21967. (function (BABYLON) {
  21968. var Animatable = (function () {
  21969. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21970. if (fromFrame === void 0) { fromFrame = 0; }
  21971. if (toFrame === void 0) { toFrame = 100; }
  21972. if (loopAnimation === void 0) { loopAnimation = false; }
  21973. if (speedRatio === void 0) { speedRatio = 1.0; }
  21974. this.target = target;
  21975. this.fromFrame = fromFrame;
  21976. this.toFrame = toFrame;
  21977. this.loopAnimation = loopAnimation;
  21978. this.speedRatio = speedRatio;
  21979. this.onAnimationEnd = onAnimationEnd;
  21980. this._animations = new Array();
  21981. this._paused = false;
  21982. this.animationStarted = false;
  21983. if (animations) {
  21984. this.appendAnimations(target, animations);
  21985. }
  21986. this._scene = scene;
  21987. scene._activeAnimatables.push(this);
  21988. }
  21989. // Methods
  21990. Animatable.prototype.appendAnimations = function (target, animations) {
  21991. for (var index = 0; index < animations.length; index++) {
  21992. var animation = animations[index];
  21993. animation._target = target;
  21994. this._animations.push(animation);
  21995. }
  21996. };
  21997. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21998. var animations = this._animations;
  21999. for (var index = 0; index < animations.length; index++) {
  22000. if (animations[index].targetProperty === property) {
  22001. return animations[index];
  22002. }
  22003. }
  22004. return null;
  22005. };
  22006. Animatable.prototype.reset = function () {
  22007. var animations = this._animations;
  22008. for (var index = 0; index < animations.length; index++) {
  22009. animations[index].reset();
  22010. }
  22011. this._localDelayOffset = null;
  22012. this._pausedDelay = null;
  22013. };
  22014. Animatable.prototype.pause = function () {
  22015. if (this._paused) {
  22016. return;
  22017. }
  22018. this._paused = true;
  22019. };
  22020. Animatable.prototype.restart = function () {
  22021. this._paused = false;
  22022. };
  22023. Animatable.prototype.stop = function () {
  22024. var index = this._scene._activeAnimatables.indexOf(this);
  22025. if (index > -1) {
  22026. this._scene._activeAnimatables.splice(index, 1);
  22027. }
  22028. if (this.onAnimationEnd) {
  22029. this.onAnimationEnd();
  22030. }
  22031. };
  22032. Animatable.prototype._animate = function (delay) {
  22033. if (this._paused) {
  22034. if (!this._pausedDelay) {
  22035. this._pausedDelay = delay;
  22036. }
  22037. return true;
  22038. }
  22039. if (!this._localDelayOffset) {
  22040. this._localDelayOffset = delay;
  22041. }
  22042. else if (this._pausedDelay) {
  22043. this._localDelayOffset += delay - this._pausedDelay;
  22044. this._pausedDelay = null;
  22045. }
  22046. // Animating
  22047. var running = false;
  22048. var animations = this._animations;
  22049. for (var index = 0; index < animations.length; index++) {
  22050. var animation = animations[index];
  22051. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22052. running = running || isRunning;
  22053. }
  22054. if (!running) {
  22055. // Remove from active animatables
  22056. index = this._scene._activeAnimatables.indexOf(this);
  22057. this._scene._activeAnimatables.splice(index, 1);
  22058. }
  22059. if (!running && this.onAnimationEnd) {
  22060. this.onAnimationEnd();
  22061. }
  22062. return running;
  22063. };
  22064. return Animatable;
  22065. })();
  22066. BABYLON.Animatable = Animatable;
  22067. })(BABYLON || (BABYLON = {}));
  22068. var BABYLON;
  22069. (function (BABYLON) {
  22070. var EasingFunction = (function () {
  22071. function EasingFunction() {
  22072. // Properties
  22073. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22074. }
  22075. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22076. get: function () {
  22077. return EasingFunction._EASINGMODE_EASEIN;
  22078. },
  22079. enumerable: true,
  22080. configurable: true
  22081. });
  22082. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22083. get: function () {
  22084. return EasingFunction._EASINGMODE_EASEOUT;
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22090. get: function () {
  22091. return EasingFunction._EASINGMODE_EASEINOUT;
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22097. var n = Math.min(Math.max(easingMode, 0), 2);
  22098. this._easingMode = n;
  22099. };
  22100. EasingFunction.prototype.getEasingMode = function () {
  22101. return this._easingMode;
  22102. };
  22103. EasingFunction.prototype.easeInCore = function (gradient) {
  22104. throw new Error('You must implement this method');
  22105. };
  22106. EasingFunction.prototype.ease = function (gradient) {
  22107. switch (this._easingMode) {
  22108. case EasingFunction.EASINGMODE_EASEIN:
  22109. return this.easeInCore(gradient);
  22110. case EasingFunction.EASINGMODE_EASEOUT:
  22111. return (1 - this.easeInCore(1 - gradient));
  22112. }
  22113. if (gradient >= 0.5) {
  22114. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22115. }
  22116. return (this.easeInCore(gradient * 2) * 0.5);
  22117. };
  22118. //Statics
  22119. EasingFunction._EASINGMODE_EASEIN = 0;
  22120. EasingFunction._EASINGMODE_EASEOUT = 1;
  22121. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22122. return EasingFunction;
  22123. })();
  22124. BABYLON.EasingFunction = EasingFunction;
  22125. var CircleEase = (function (_super) {
  22126. __extends(CircleEase, _super);
  22127. function CircleEase() {
  22128. _super.apply(this, arguments);
  22129. }
  22130. CircleEase.prototype.easeInCore = function (gradient) {
  22131. gradient = Math.max(0, Math.min(1, gradient));
  22132. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22133. };
  22134. return CircleEase;
  22135. })(EasingFunction);
  22136. BABYLON.CircleEase = CircleEase;
  22137. var BackEase = (function (_super) {
  22138. __extends(BackEase, _super);
  22139. function BackEase(amplitude) {
  22140. if (amplitude === void 0) { amplitude = 1; }
  22141. _super.call(this);
  22142. this.amplitude = amplitude;
  22143. }
  22144. BackEase.prototype.easeInCore = function (gradient) {
  22145. var num = Math.max(0, this.amplitude);
  22146. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22147. };
  22148. return BackEase;
  22149. })(EasingFunction);
  22150. BABYLON.BackEase = BackEase;
  22151. var BounceEase = (function (_super) {
  22152. __extends(BounceEase, _super);
  22153. function BounceEase(bounces, bounciness) {
  22154. if (bounces === void 0) { bounces = 3; }
  22155. if (bounciness === void 0) { bounciness = 2; }
  22156. _super.call(this);
  22157. this.bounces = bounces;
  22158. this.bounciness = bounciness;
  22159. }
  22160. BounceEase.prototype.easeInCore = function (gradient) {
  22161. var y = Math.max(0.0, this.bounces);
  22162. var bounciness = this.bounciness;
  22163. if (bounciness <= 1.0) {
  22164. bounciness = 1.001;
  22165. }
  22166. var num9 = Math.pow(bounciness, y);
  22167. var num5 = 1.0 - bounciness;
  22168. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22169. var num15 = gradient * num4;
  22170. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22171. var num3 = Math.floor(num65);
  22172. var num13 = num3 + 1.0;
  22173. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22174. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22175. var num7 = (num8 + num12) * 0.5;
  22176. var num6 = gradient - num7;
  22177. var num2 = num7 - num8;
  22178. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22179. };
  22180. return BounceEase;
  22181. })(EasingFunction);
  22182. BABYLON.BounceEase = BounceEase;
  22183. var CubicEase = (function (_super) {
  22184. __extends(CubicEase, _super);
  22185. function CubicEase() {
  22186. _super.apply(this, arguments);
  22187. }
  22188. CubicEase.prototype.easeInCore = function (gradient) {
  22189. return (gradient * gradient * gradient);
  22190. };
  22191. return CubicEase;
  22192. })(EasingFunction);
  22193. BABYLON.CubicEase = CubicEase;
  22194. var ElasticEase = (function (_super) {
  22195. __extends(ElasticEase, _super);
  22196. function ElasticEase(oscillations, springiness) {
  22197. if (oscillations === void 0) { oscillations = 3; }
  22198. if (springiness === void 0) { springiness = 3; }
  22199. _super.call(this);
  22200. this.oscillations = oscillations;
  22201. this.springiness = springiness;
  22202. }
  22203. ElasticEase.prototype.easeInCore = function (gradient) {
  22204. var num2;
  22205. var num3 = Math.max(0.0, this.oscillations);
  22206. var num = Math.max(0.0, this.springiness);
  22207. if (num == 0) {
  22208. num2 = gradient;
  22209. }
  22210. else {
  22211. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22212. }
  22213. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22214. };
  22215. return ElasticEase;
  22216. })(EasingFunction);
  22217. BABYLON.ElasticEase = ElasticEase;
  22218. var ExponentialEase = (function (_super) {
  22219. __extends(ExponentialEase, _super);
  22220. function ExponentialEase(exponent) {
  22221. if (exponent === void 0) { exponent = 2; }
  22222. _super.call(this);
  22223. this.exponent = exponent;
  22224. }
  22225. ExponentialEase.prototype.easeInCore = function (gradient) {
  22226. if (this.exponent <= 0) {
  22227. return gradient;
  22228. }
  22229. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22230. };
  22231. return ExponentialEase;
  22232. })(EasingFunction);
  22233. BABYLON.ExponentialEase = ExponentialEase;
  22234. var PowerEase = (function (_super) {
  22235. __extends(PowerEase, _super);
  22236. function PowerEase(power) {
  22237. if (power === void 0) { power = 2; }
  22238. _super.call(this);
  22239. this.power = power;
  22240. }
  22241. PowerEase.prototype.easeInCore = function (gradient) {
  22242. var y = Math.max(0.0, this.power);
  22243. return Math.pow(gradient, y);
  22244. };
  22245. return PowerEase;
  22246. })(EasingFunction);
  22247. BABYLON.PowerEase = PowerEase;
  22248. var QuadraticEase = (function (_super) {
  22249. __extends(QuadraticEase, _super);
  22250. function QuadraticEase() {
  22251. _super.apply(this, arguments);
  22252. }
  22253. QuadraticEase.prototype.easeInCore = function (gradient) {
  22254. return (gradient * gradient);
  22255. };
  22256. return QuadraticEase;
  22257. })(EasingFunction);
  22258. BABYLON.QuadraticEase = QuadraticEase;
  22259. var QuarticEase = (function (_super) {
  22260. __extends(QuarticEase, _super);
  22261. function QuarticEase() {
  22262. _super.apply(this, arguments);
  22263. }
  22264. QuarticEase.prototype.easeInCore = function (gradient) {
  22265. return (gradient * gradient * gradient * gradient);
  22266. };
  22267. return QuarticEase;
  22268. })(EasingFunction);
  22269. BABYLON.QuarticEase = QuarticEase;
  22270. var QuinticEase = (function (_super) {
  22271. __extends(QuinticEase, _super);
  22272. function QuinticEase() {
  22273. _super.apply(this, arguments);
  22274. }
  22275. QuinticEase.prototype.easeInCore = function (gradient) {
  22276. return (gradient * gradient * gradient * gradient * gradient);
  22277. };
  22278. return QuinticEase;
  22279. })(EasingFunction);
  22280. BABYLON.QuinticEase = QuinticEase;
  22281. var SineEase = (function (_super) {
  22282. __extends(SineEase, _super);
  22283. function SineEase() {
  22284. _super.apply(this, arguments);
  22285. }
  22286. SineEase.prototype.easeInCore = function (gradient) {
  22287. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22288. };
  22289. return SineEase;
  22290. })(EasingFunction);
  22291. BABYLON.SineEase = SineEase;
  22292. var BezierCurveEase = (function (_super) {
  22293. __extends(BezierCurveEase, _super);
  22294. function BezierCurveEase(x1, y1, x2, y2) {
  22295. if (x1 === void 0) { x1 = 0; }
  22296. if (y1 === void 0) { y1 = 0; }
  22297. if (x2 === void 0) { x2 = 1; }
  22298. if (y2 === void 0) { y2 = 1; }
  22299. _super.call(this);
  22300. this.x1 = x1;
  22301. this.y1 = y1;
  22302. this.x2 = x2;
  22303. this.y2 = y2;
  22304. }
  22305. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22306. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22307. };
  22308. return BezierCurveEase;
  22309. })(EasingFunction);
  22310. BABYLON.BezierCurveEase = BezierCurveEase;
  22311. })(BABYLON || (BABYLON = {}));
  22312. var BABYLON;
  22313. (function (BABYLON) {
  22314. var Octree = (function () {
  22315. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22316. if (maxDepth === void 0) { maxDepth = 2; }
  22317. this.maxDepth = maxDepth;
  22318. this.dynamicContent = new Array();
  22319. this._maxBlockCapacity = maxBlockCapacity || 64;
  22320. this._selectionContent = new BABYLON.SmartArray(1024);
  22321. this._creationFunc = creationFunc;
  22322. }
  22323. // Methods
  22324. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22325. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22326. };
  22327. Octree.prototype.addMesh = function (entry) {
  22328. for (var index = 0; index < this.blocks.length; index++) {
  22329. var block = this.blocks[index];
  22330. block.addEntry(entry);
  22331. }
  22332. };
  22333. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22334. this._selectionContent.reset();
  22335. for (var index = 0; index < this.blocks.length; index++) {
  22336. var block = this.blocks[index];
  22337. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22338. }
  22339. if (allowDuplicate) {
  22340. this._selectionContent.concat(this.dynamicContent);
  22341. }
  22342. else {
  22343. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22344. }
  22345. return this._selectionContent;
  22346. };
  22347. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22348. this._selectionContent.reset();
  22349. for (var index = 0; index < this.blocks.length; index++) {
  22350. var block = this.blocks[index];
  22351. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22352. }
  22353. if (allowDuplicate) {
  22354. this._selectionContent.concat(this.dynamicContent);
  22355. }
  22356. else {
  22357. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22358. }
  22359. return this._selectionContent;
  22360. };
  22361. Octree.prototype.intersectsRay = function (ray) {
  22362. this._selectionContent.reset();
  22363. for (var index = 0; index < this.blocks.length; index++) {
  22364. var block = this.blocks[index];
  22365. block.intersectsRay(ray, this._selectionContent);
  22366. }
  22367. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22368. return this._selectionContent;
  22369. };
  22370. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22371. target.blocks = new Array();
  22372. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22373. // Segmenting space
  22374. for (var x = 0; x < 2; x++) {
  22375. for (var y = 0; y < 2; y++) {
  22376. for (var z = 0; z < 2; z++) {
  22377. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22378. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22379. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22380. block.addEntries(entries);
  22381. target.blocks.push(block);
  22382. }
  22383. }
  22384. }
  22385. };
  22386. Octree.CreationFuncForMeshes = function (entry, block) {
  22387. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22388. block.entries.push(entry);
  22389. }
  22390. };
  22391. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22392. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22393. block.entries.push(entry);
  22394. }
  22395. };
  22396. return Octree;
  22397. })();
  22398. BABYLON.Octree = Octree;
  22399. })(BABYLON || (BABYLON = {}));
  22400. var BABYLON;
  22401. (function (BABYLON) {
  22402. var OctreeBlock = (function () {
  22403. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22404. this.entries = new Array();
  22405. this._boundingVectors = new Array();
  22406. this._capacity = capacity;
  22407. this._depth = depth;
  22408. this._maxDepth = maxDepth;
  22409. this._creationFunc = creationFunc;
  22410. this._minPoint = minPoint;
  22411. this._maxPoint = maxPoint;
  22412. this._boundingVectors.push(minPoint.clone());
  22413. this._boundingVectors.push(maxPoint.clone());
  22414. this._boundingVectors.push(minPoint.clone());
  22415. this._boundingVectors[2].x = maxPoint.x;
  22416. this._boundingVectors.push(minPoint.clone());
  22417. this._boundingVectors[3].y = maxPoint.y;
  22418. this._boundingVectors.push(minPoint.clone());
  22419. this._boundingVectors[4].z = maxPoint.z;
  22420. this._boundingVectors.push(maxPoint.clone());
  22421. this._boundingVectors[5].z = minPoint.z;
  22422. this._boundingVectors.push(maxPoint.clone());
  22423. this._boundingVectors[6].x = minPoint.x;
  22424. this._boundingVectors.push(maxPoint.clone());
  22425. this._boundingVectors[7].y = minPoint.y;
  22426. }
  22427. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22428. // Property
  22429. get: function () {
  22430. return this._capacity;
  22431. },
  22432. enumerable: true,
  22433. configurable: true
  22434. });
  22435. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22436. get: function () {
  22437. return this._minPoint;
  22438. },
  22439. enumerable: true,
  22440. configurable: true
  22441. });
  22442. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22443. get: function () {
  22444. return this._maxPoint;
  22445. },
  22446. enumerable: true,
  22447. configurable: true
  22448. });
  22449. // Methods
  22450. OctreeBlock.prototype.addEntry = function (entry) {
  22451. if (this.blocks) {
  22452. for (var index = 0; index < this.blocks.length; index++) {
  22453. var block = this.blocks[index];
  22454. block.addEntry(entry);
  22455. }
  22456. return;
  22457. }
  22458. this._creationFunc(entry, this);
  22459. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22460. this.createInnerBlocks();
  22461. }
  22462. };
  22463. OctreeBlock.prototype.addEntries = function (entries) {
  22464. for (var index = 0; index < entries.length; index++) {
  22465. var mesh = entries[index];
  22466. this.addEntry(mesh);
  22467. }
  22468. };
  22469. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  22470. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  22471. if (this.blocks) {
  22472. for (var index = 0; index < this.blocks.length; index++) {
  22473. var block = this.blocks[index];
  22474. block.select(frustumPlanes, selection, allowDuplicate);
  22475. }
  22476. return;
  22477. }
  22478. if (allowDuplicate) {
  22479. selection.concat(this.entries);
  22480. }
  22481. else {
  22482. selection.concatWithNoDuplicate(this.entries);
  22483. }
  22484. }
  22485. };
  22486. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  22487. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  22488. if (this.blocks) {
  22489. for (var index = 0; index < this.blocks.length; index++) {
  22490. var block = this.blocks[index];
  22491. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  22492. }
  22493. return;
  22494. }
  22495. if (allowDuplicate) {
  22496. selection.concat(this.entries);
  22497. }
  22498. else {
  22499. selection.concatWithNoDuplicate(this.entries);
  22500. }
  22501. }
  22502. };
  22503. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  22504. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  22505. if (this.blocks) {
  22506. for (var index = 0; index < this.blocks.length; index++) {
  22507. var block = this.blocks[index];
  22508. block.intersectsRay(ray, selection);
  22509. }
  22510. return;
  22511. }
  22512. selection.concatWithNoDuplicate(this.entries);
  22513. }
  22514. };
  22515. OctreeBlock.prototype.createInnerBlocks = function () {
  22516. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  22517. };
  22518. return OctreeBlock;
  22519. })();
  22520. BABYLON.OctreeBlock = OctreeBlock;
  22521. })(BABYLON || (BABYLON = {}));
  22522. var BABYLON;
  22523. (function (BABYLON) {
  22524. var Bone = (function (_super) {
  22525. __extends(Bone, _super);
  22526. function Bone(name, skeleton, parentBone, matrix) {
  22527. _super.call(this, name, skeleton.getScene());
  22528. this.name = name;
  22529. this.children = new Array();
  22530. this.animations = new Array();
  22531. this._worldTransform = new BABYLON.Matrix();
  22532. this._absoluteTransform = new BABYLON.Matrix();
  22533. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22534. this._skeleton = skeleton;
  22535. this._matrix = matrix;
  22536. this._baseMatrix = matrix;
  22537. skeleton.bones.push(this);
  22538. if (parentBone) {
  22539. this._parent = parentBone;
  22540. parentBone.children.push(this);
  22541. }
  22542. else {
  22543. this._parent = null;
  22544. }
  22545. this._updateDifferenceMatrix();
  22546. }
  22547. // Members
  22548. Bone.prototype.getParent = function () {
  22549. return this._parent;
  22550. };
  22551. Bone.prototype.getLocalMatrix = function () {
  22552. return this._matrix;
  22553. };
  22554. Bone.prototype.getBaseMatrix = function () {
  22555. return this._baseMatrix;
  22556. };
  22557. Bone.prototype.getWorldMatrix = function () {
  22558. return this._worldTransform;
  22559. };
  22560. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22561. return this._invertedAbsoluteTransform;
  22562. };
  22563. Bone.prototype.getAbsoluteMatrix = function () {
  22564. var matrix = this._matrix.clone();
  22565. var parent = this._parent;
  22566. while (parent) {
  22567. matrix = matrix.multiply(parent.getLocalMatrix());
  22568. parent = parent.getParent();
  22569. }
  22570. return matrix;
  22571. };
  22572. // Methods
  22573. Bone.prototype.updateMatrix = function (matrix) {
  22574. this._matrix = matrix;
  22575. this._skeleton._markAsDirty();
  22576. this._updateDifferenceMatrix();
  22577. };
  22578. Bone.prototype._updateDifferenceMatrix = function () {
  22579. if (this._parent) {
  22580. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22581. }
  22582. else {
  22583. this._absoluteTransform.copyFrom(this._matrix);
  22584. }
  22585. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22586. for (var index = 0; index < this.children.length; index++) {
  22587. this.children[index]._updateDifferenceMatrix();
  22588. }
  22589. };
  22590. Bone.prototype.markAsDirty = function () {
  22591. this._currentRenderId++;
  22592. this._skeleton._markAsDirty();
  22593. };
  22594. return Bone;
  22595. })(BABYLON.Node);
  22596. BABYLON.Bone = Bone;
  22597. })(BABYLON || (BABYLON = {}));
  22598. var BABYLON;
  22599. (function (BABYLON) {
  22600. var Skeleton = (function () {
  22601. function Skeleton(name, id, scene) {
  22602. this.name = name;
  22603. this.id = id;
  22604. this.bones = new Array();
  22605. this._isDirty = true;
  22606. this._identity = BABYLON.Matrix.Identity();
  22607. this.bones = [];
  22608. this._scene = scene;
  22609. scene.skeletons.push(this);
  22610. this.prepare();
  22611. //make sure it will recalculate the matrix next time prepare is called.
  22612. this._isDirty = true;
  22613. }
  22614. // Members
  22615. Skeleton.prototype.getTransformMatrices = function () {
  22616. return this._transformMatrices;
  22617. };
  22618. Skeleton.prototype.getScene = function () {
  22619. return this._scene;
  22620. };
  22621. // Methods
  22622. Skeleton.prototype._markAsDirty = function () {
  22623. this._isDirty = true;
  22624. };
  22625. Skeleton.prototype.prepare = function () {
  22626. if (!this._isDirty) {
  22627. return;
  22628. }
  22629. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22630. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22631. }
  22632. for (var index = 0; index < this.bones.length; index++) {
  22633. var bone = this.bones[index];
  22634. var parentBone = bone.getParent();
  22635. if (parentBone) {
  22636. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22637. }
  22638. else {
  22639. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22640. }
  22641. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22642. }
  22643. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22644. this._isDirty = false;
  22645. this._scene._activeBones += this.bones.length;
  22646. };
  22647. Skeleton.prototype.getAnimatables = function () {
  22648. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22649. this._animatables = [];
  22650. for (var index = 0; index < this.bones.length; index++) {
  22651. this._animatables.push(this.bones[index]);
  22652. }
  22653. }
  22654. return this._animatables;
  22655. };
  22656. Skeleton.prototype.clone = function (name, id) {
  22657. var result = new Skeleton(name, id || name, this._scene);
  22658. for (var index = 0; index < this.bones.length; index++) {
  22659. var source = this.bones[index];
  22660. var parentBone = null;
  22661. if (source.getParent()) {
  22662. var parentIndex = this.bones.indexOf(source.getParent());
  22663. parentBone = result.bones[parentIndex];
  22664. }
  22665. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22666. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22667. }
  22668. return result;
  22669. };
  22670. return Skeleton;
  22671. })();
  22672. BABYLON.Skeleton = Skeleton;
  22673. })(BABYLON || (BABYLON = {}));
  22674. var BABYLON;
  22675. (function (BABYLON) {
  22676. var PostProcess = (function () {
  22677. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22679. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22680. this.name = name;
  22681. this.width = -1;
  22682. this.height = -1;
  22683. this._reusable = false;
  22684. this._textures = new BABYLON.SmartArray(2);
  22685. this._currentRenderTextureInd = 0;
  22686. if (camera != null) {
  22687. this._camera = camera;
  22688. this._scene = camera.getScene();
  22689. camera.attachPostProcess(this);
  22690. this._engine = this._scene.getEngine();
  22691. }
  22692. else {
  22693. this._engine = engine;
  22694. }
  22695. this._renderRatio = ratio;
  22696. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22697. this._reusable = reusable || false;
  22698. this._textureType = textureType;
  22699. samplers = samplers || [];
  22700. samplers.push("textureSampler");
  22701. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22702. }
  22703. PostProcess.prototype.isReusable = function () {
  22704. return this._reusable;
  22705. };
  22706. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22707. camera = camera || this._camera;
  22708. var scene = camera.getScene();
  22709. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22710. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22711. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22712. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  22713. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  22714. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22715. if (this._textures.length > 0) {
  22716. for (var i = 0; i < this._textures.length; i++) {
  22717. this._engine._releaseTexture(this._textures.data[i]);
  22718. }
  22719. this._textures.reset();
  22720. }
  22721. this.width = desiredWidth;
  22722. this.height = desiredHeight;
  22723. 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 }));
  22724. if (this._reusable) {
  22725. 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 }));
  22726. }
  22727. if (this.onSizeChanged) {
  22728. this.onSizeChanged();
  22729. }
  22730. }
  22731. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22732. if (this.onActivate) {
  22733. this.onActivate(camera);
  22734. }
  22735. // Clear
  22736. if (this.clearColor) {
  22737. this._engine.clear(this.clearColor, true, true);
  22738. }
  22739. else {
  22740. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22741. }
  22742. if (this._reusable) {
  22743. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22744. }
  22745. };
  22746. PostProcess.prototype.apply = function () {
  22747. // Check
  22748. if (!this._effect.isReady())
  22749. return null;
  22750. // States
  22751. this._engine.enableEffect(this._effect);
  22752. this._engine.setState(false);
  22753. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22754. this._engine.setDepthBuffer(false);
  22755. this._engine.setDepthWrite(false);
  22756. // Texture
  22757. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22758. // Parameters
  22759. if (this.onApply) {
  22760. this.onApply(this._effect);
  22761. }
  22762. return this._effect;
  22763. };
  22764. PostProcess.prototype.dispose = function (camera) {
  22765. camera = camera || this._camera;
  22766. if (this._textures.length > 0) {
  22767. for (var i = 0; i < this._textures.length; i++) {
  22768. this._engine._releaseTexture(this._textures.data[i]);
  22769. }
  22770. this._textures.reset();
  22771. }
  22772. if (!camera) {
  22773. return;
  22774. }
  22775. camera.detachPostProcess(this);
  22776. var index = camera._postProcesses.indexOf(this);
  22777. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22778. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22779. }
  22780. };
  22781. return PostProcess;
  22782. })();
  22783. BABYLON.PostProcess = PostProcess;
  22784. })(BABYLON || (BABYLON = {}));
  22785. var BABYLON;
  22786. (function (BABYLON) {
  22787. var PostProcessManager = (function () {
  22788. function PostProcessManager(scene) {
  22789. this._vertexDeclaration = [2];
  22790. this._vertexStrideSize = 2 * 4;
  22791. this._scene = scene;
  22792. }
  22793. PostProcessManager.prototype._prepareBuffers = function () {
  22794. if (this._vertexBuffer) {
  22795. return;
  22796. }
  22797. // VBO
  22798. var vertices = [];
  22799. vertices.push(1, 1);
  22800. vertices.push(-1, 1);
  22801. vertices.push(-1, -1);
  22802. vertices.push(1, -1);
  22803. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22804. // Indices
  22805. var indices = [];
  22806. indices.push(0);
  22807. indices.push(1);
  22808. indices.push(2);
  22809. indices.push(0);
  22810. indices.push(2);
  22811. indices.push(3);
  22812. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22813. };
  22814. // Methods
  22815. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22816. var postProcesses = this._scene.activeCamera._postProcesses;
  22817. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22818. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22819. return false;
  22820. }
  22821. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22822. return true;
  22823. };
  22824. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22825. var engine = this._scene.getEngine();
  22826. for (var index = 0; index < postProcesses.length; index++) {
  22827. if (index < postProcesses.length - 1) {
  22828. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22829. }
  22830. else {
  22831. if (targetTexture) {
  22832. engine.bindFramebuffer(targetTexture);
  22833. }
  22834. else {
  22835. engine.restoreDefaultFramebuffer();
  22836. }
  22837. }
  22838. var pp = postProcesses[index];
  22839. var effect = pp.apply();
  22840. if (effect) {
  22841. if (pp.onBeforeRender) {
  22842. pp.onBeforeRender(effect);
  22843. }
  22844. // VBOs
  22845. this._prepareBuffers();
  22846. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22847. // Draw order
  22848. engine.draw(true, 0, 6);
  22849. if (pp.onAfterRender) {
  22850. pp.onAfterRender(effect);
  22851. }
  22852. }
  22853. }
  22854. // Restore depth buffer
  22855. engine.setDepthBuffer(true);
  22856. engine.setDepthWrite(true);
  22857. };
  22858. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22859. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22860. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22861. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22862. return;
  22863. }
  22864. var engine = this._scene.getEngine();
  22865. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22866. if (index < postProcessesTakenIndices.length - 1) {
  22867. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22868. }
  22869. else {
  22870. if (targetTexture) {
  22871. engine.bindFramebuffer(targetTexture);
  22872. }
  22873. else {
  22874. engine.restoreDefaultFramebuffer();
  22875. }
  22876. }
  22877. if (doNotPresent) {
  22878. break;
  22879. }
  22880. var pp = postProcesses[postProcessesTakenIndices[index]];
  22881. var effect = pp.apply();
  22882. if (effect) {
  22883. if (pp.onBeforeRender) {
  22884. pp.onBeforeRender(effect);
  22885. }
  22886. // VBOs
  22887. this._prepareBuffers();
  22888. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22889. // Draw order
  22890. engine.draw(true, 0, 6);
  22891. if (pp.onAfterRender) {
  22892. pp.onAfterRender(effect);
  22893. }
  22894. }
  22895. }
  22896. // Restore depth buffer
  22897. engine.setDepthBuffer(true);
  22898. engine.setDepthWrite(true);
  22899. };
  22900. PostProcessManager.prototype.dispose = function () {
  22901. if (this._vertexBuffer) {
  22902. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22903. this._vertexBuffer = null;
  22904. }
  22905. if (this._indexBuffer) {
  22906. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22907. this._indexBuffer = null;
  22908. }
  22909. };
  22910. return PostProcessManager;
  22911. })();
  22912. BABYLON.PostProcessManager = PostProcessManager;
  22913. })(BABYLON || (BABYLON = {}));
  22914. var BABYLON;
  22915. (function (BABYLON) {
  22916. var PassPostProcess = (function (_super) {
  22917. __extends(PassPostProcess, _super);
  22918. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22919. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22920. }
  22921. return PassPostProcess;
  22922. })(BABYLON.PostProcess);
  22923. BABYLON.PassPostProcess = PassPostProcess;
  22924. })(BABYLON || (BABYLON = {}));
  22925. var BABYLON;
  22926. (function (BABYLON) {
  22927. var BlurPostProcess = (function (_super) {
  22928. __extends(BlurPostProcess, _super);
  22929. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22930. var _this = this;
  22931. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22932. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22933. this.direction = direction;
  22934. this.blurWidth = blurWidth;
  22935. this.onApply = function (effect) {
  22936. effect.setFloat2("screenSize", _this.width, _this.height);
  22937. effect.setVector2("direction", _this.direction);
  22938. effect.setFloat("blurWidth", _this.blurWidth);
  22939. };
  22940. }
  22941. return BlurPostProcess;
  22942. })(BABYLON.PostProcess);
  22943. BABYLON.BlurPostProcess = BlurPostProcess;
  22944. })(BABYLON || (BABYLON = {}));
  22945. var BABYLON;
  22946. (function (BABYLON) {
  22947. var RefractionPostProcess = (function (_super) {
  22948. __extends(RefractionPostProcess, _super);
  22949. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22950. var _this = this;
  22951. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22952. this.color = color;
  22953. this.depth = depth;
  22954. this.colorLevel = colorLevel;
  22955. this.onActivate = function (cam) {
  22956. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22957. };
  22958. this.onApply = function (effect) {
  22959. effect.setColor3("baseColor", _this.color);
  22960. effect.setFloat("depth", _this.depth);
  22961. effect.setFloat("colorLevel", _this.colorLevel);
  22962. effect.setTexture("refractionSampler", _this._refRexture);
  22963. };
  22964. }
  22965. // Methods
  22966. RefractionPostProcess.prototype.dispose = function (camera) {
  22967. if (this._refRexture) {
  22968. this._refRexture.dispose();
  22969. }
  22970. _super.prototype.dispose.call(this, camera);
  22971. };
  22972. return RefractionPostProcess;
  22973. })(BABYLON.PostProcess);
  22974. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22975. })(BABYLON || (BABYLON = {}));
  22976. var BABYLON;
  22977. (function (BABYLON) {
  22978. var BlackAndWhitePostProcess = (function (_super) {
  22979. __extends(BlackAndWhitePostProcess, _super);
  22980. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22981. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22982. }
  22983. return BlackAndWhitePostProcess;
  22984. })(BABYLON.PostProcess);
  22985. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22986. })(BABYLON || (BABYLON = {}));
  22987. var BABYLON;
  22988. (function (BABYLON) {
  22989. var ConvolutionPostProcess = (function (_super) {
  22990. __extends(ConvolutionPostProcess, _super);
  22991. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22992. var _this = this;
  22993. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22994. this.kernel = kernel;
  22995. this.onApply = function (effect) {
  22996. effect.setFloat2("screenSize", _this.width, _this.height);
  22997. effect.setArray("kernel", _this.kernel);
  22998. };
  22999. }
  23000. // Statics
  23001. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  23002. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  23003. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  23004. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  23005. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  23006. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  23007. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  23008. return ConvolutionPostProcess;
  23009. })(BABYLON.PostProcess);
  23010. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  23011. })(BABYLON || (BABYLON = {}));
  23012. var BABYLON;
  23013. (function (BABYLON) {
  23014. var FilterPostProcess = (function (_super) {
  23015. __extends(FilterPostProcess, _super);
  23016. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  23017. var _this = this;
  23018. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23019. this.kernelMatrix = kernelMatrix;
  23020. this.onApply = function (effect) {
  23021. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23022. };
  23023. }
  23024. return FilterPostProcess;
  23025. })(BABYLON.PostProcess);
  23026. BABYLON.FilterPostProcess = FilterPostProcess;
  23027. })(BABYLON || (BABYLON = {}));
  23028. var BABYLON;
  23029. (function (BABYLON) {
  23030. var FxaaPostProcess = (function (_super) {
  23031. __extends(FxaaPostProcess, _super);
  23032. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23033. var _this = this;
  23034. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23035. this.onSizeChanged = function () {
  23036. _this.texelWidth = 1.0 / _this.width;
  23037. _this.texelHeight = 1.0 / _this.height;
  23038. };
  23039. this.onApply = function (effect) {
  23040. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23041. };
  23042. }
  23043. return FxaaPostProcess;
  23044. })(BABYLON.PostProcess);
  23045. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23046. })(BABYLON || (BABYLON = {}));
  23047. var BABYLON;
  23048. (function (BABYLON) {
  23049. var StereoscopicInterlacePostProcess = (function (_super) {
  23050. __extends(StereoscopicInterlacePostProcess, _super);
  23051. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23052. var _this = this;
  23053. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23054. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23055. this.onSizeChanged = function () {
  23056. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23057. };
  23058. this.onApply = function (effect) {
  23059. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23060. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23061. };
  23062. }
  23063. return StereoscopicInterlacePostProcess;
  23064. })(BABYLON.PostProcess);
  23065. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23066. })(BABYLON || (BABYLON = {}));
  23067. var BABYLON;
  23068. (function (BABYLON) {
  23069. var LensFlare = (function () {
  23070. function LensFlare(size, position, color, imgUrl, system) {
  23071. this.size = size;
  23072. this.position = position;
  23073. this.dispose = function () {
  23074. if (this.texture) {
  23075. this.texture.dispose();
  23076. }
  23077. // Remove from scene
  23078. var index = this._system.lensFlares.indexOf(this);
  23079. this._system.lensFlares.splice(index, 1);
  23080. };
  23081. this.color = color || new BABYLON.Color3(1, 1, 1);
  23082. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23083. this._system = system;
  23084. system.lensFlares.push(this);
  23085. }
  23086. return LensFlare;
  23087. })();
  23088. BABYLON.LensFlare = LensFlare;
  23089. })(BABYLON || (BABYLON = {}));
  23090. var BABYLON;
  23091. (function (BABYLON) {
  23092. var LensFlareSystem = (function () {
  23093. function LensFlareSystem(name, emitter, scene) {
  23094. this.name = name;
  23095. this.lensFlares = new Array();
  23096. this.borderLimit = 300;
  23097. this._vertexDeclaration = [2];
  23098. this._vertexStrideSize = 2 * 4;
  23099. this._isEnabled = true;
  23100. this._scene = scene;
  23101. this._emitter = emitter;
  23102. scene.lensFlareSystems.push(this);
  23103. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23104. // VBO
  23105. var vertices = [];
  23106. vertices.push(1, 1);
  23107. vertices.push(-1, 1);
  23108. vertices.push(-1, -1);
  23109. vertices.push(1, -1);
  23110. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23111. // Indices
  23112. var indices = [];
  23113. indices.push(0);
  23114. indices.push(1);
  23115. indices.push(2);
  23116. indices.push(0);
  23117. indices.push(2);
  23118. indices.push(3);
  23119. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23120. // Effects
  23121. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23122. }
  23123. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23124. get: function () {
  23125. return this._isEnabled;
  23126. },
  23127. set: function (value) {
  23128. this._isEnabled = value;
  23129. },
  23130. enumerable: true,
  23131. configurable: true
  23132. });
  23133. LensFlareSystem.prototype.getScene = function () {
  23134. return this._scene;
  23135. };
  23136. LensFlareSystem.prototype.getEmitter = function () {
  23137. return this._emitter;
  23138. };
  23139. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23140. this._emitter = newEmitter;
  23141. };
  23142. LensFlareSystem.prototype.getEmitterPosition = function () {
  23143. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23144. };
  23145. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23146. var position = this.getEmitterPosition();
  23147. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23148. this._positionX = position.x;
  23149. this._positionY = position.y;
  23150. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23151. if (position.z > 0) {
  23152. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23153. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23154. return true;
  23155. }
  23156. }
  23157. return false;
  23158. };
  23159. LensFlareSystem.prototype._isVisible = function () {
  23160. if (!this._isEnabled) {
  23161. return false;
  23162. }
  23163. var emitterPosition = this.getEmitterPosition();
  23164. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23165. var distance = direction.length();
  23166. direction.normalize();
  23167. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23168. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23169. return !pickInfo.hit || pickInfo.distance > distance;
  23170. };
  23171. LensFlareSystem.prototype.render = function () {
  23172. if (!this._effect.isReady())
  23173. return false;
  23174. var engine = this._scene.getEngine();
  23175. var viewport = this._scene.activeCamera.viewport;
  23176. var globalViewport = viewport.toGlobal(engine);
  23177. // Position
  23178. if (!this.computeEffectivePosition(globalViewport)) {
  23179. return false;
  23180. }
  23181. // Visibility
  23182. if (!this._isVisible()) {
  23183. return false;
  23184. }
  23185. // Intensity
  23186. var awayX;
  23187. var awayY;
  23188. if (this._positionX < this.borderLimit + globalViewport.x) {
  23189. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23190. }
  23191. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23192. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23193. }
  23194. else {
  23195. awayX = 0;
  23196. }
  23197. if (this._positionY < this.borderLimit + globalViewport.y) {
  23198. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23199. }
  23200. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23201. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23202. }
  23203. else {
  23204. awayY = 0;
  23205. }
  23206. var away = (awayX > awayY) ? awayX : awayY;
  23207. if (away > this.borderLimit) {
  23208. away = this.borderLimit;
  23209. }
  23210. var intensity = 1.0 - (away / this.borderLimit);
  23211. if (intensity < 0) {
  23212. return false;
  23213. }
  23214. if (intensity > 1.0) {
  23215. intensity = 1.0;
  23216. }
  23217. // Position
  23218. var centerX = globalViewport.x + globalViewport.width / 2;
  23219. var centerY = globalViewport.y + globalViewport.height / 2;
  23220. var distX = centerX - this._positionX;
  23221. var distY = centerY - this._positionY;
  23222. // Effects
  23223. engine.enableEffect(this._effect);
  23224. engine.setState(false);
  23225. engine.setDepthBuffer(false);
  23226. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23227. // VBOs
  23228. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23229. // Flares
  23230. for (var index = 0; index < this.lensFlares.length; index++) {
  23231. var flare = this.lensFlares[index];
  23232. var x = centerX - (distX * flare.position);
  23233. var y = centerY - (distY * flare.position);
  23234. var cw = flare.size;
  23235. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23236. var cx = 2 * (x / globalViewport.width) - 1.0;
  23237. var cy = 1.0 - 2 * (y / globalViewport.height);
  23238. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23239. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23240. // Texture
  23241. this._effect.setTexture("textureSampler", flare.texture);
  23242. // Color
  23243. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23244. // Draw order
  23245. engine.draw(true, 0, 6);
  23246. }
  23247. engine.setDepthBuffer(true);
  23248. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23249. return true;
  23250. };
  23251. LensFlareSystem.prototype.dispose = function () {
  23252. if (this._vertexBuffer) {
  23253. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23254. this._vertexBuffer = null;
  23255. }
  23256. if (this._indexBuffer) {
  23257. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23258. this._indexBuffer = null;
  23259. }
  23260. while (this.lensFlares.length) {
  23261. this.lensFlares[0].dispose();
  23262. }
  23263. // Remove from scene
  23264. var index = this._scene.lensFlareSystems.indexOf(this);
  23265. this._scene.lensFlareSystems.splice(index, 1);
  23266. };
  23267. return LensFlareSystem;
  23268. })();
  23269. BABYLON.LensFlareSystem = LensFlareSystem;
  23270. })(BABYLON || (BABYLON = {}));
  23271. var BABYLON;
  23272. (function (BABYLON) {
  23273. var CannonJSPlugin = (function () {
  23274. function CannonJSPlugin() {
  23275. this._registeredMeshes = [];
  23276. this._physicsMaterials = [];
  23277. this.updateBodyPosition = function (mesh) {
  23278. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23279. var registeredMesh = this._registeredMeshes[index];
  23280. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23281. var body = registeredMesh.body;
  23282. var center = mesh.getBoundingInfo().boundingBox.center;
  23283. body.position.set(center.x, center.z, center.y);
  23284. body.quaternion.x = mesh.rotationQuaternion.x;
  23285. body.quaternion.z = mesh.rotationQuaternion.y;
  23286. body.quaternion.y = mesh.rotationQuaternion.z;
  23287. body.quaternion.w = -mesh.rotationQuaternion.w;
  23288. return;
  23289. }
  23290. }
  23291. };
  23292. }
  23293. CannonJSPlugin.prototype.initialize = function (iterations) {
  23294. if (iterations === void 0) { iterations = 10; }
  23295. this._world = new CANNON.World();
  23296. this._world.broadphase = new CANNON.NaiveBroadphase();
  23297. this._world.solver.iterations = iterations;
  23298. };
  23299. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23300. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23301. };
  23302. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23303. this._world.step(delta);
  23304. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23305. var registeredMesh = this._registeredMeshes[index];
  23306. if (registeredMesh.isChild) {
  23307. continue;
  23308. }
  23309. // Body position
  23310. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23311. var deltaPos = registeredMesh.delta;
  23312. if (deltaPos) {
  23313. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23314. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23315. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23316. }
  23317. else {
  23318. registeredMesh.mesh.position.x = bodyX;
  23319. registeredMesh.mesh.position.y = bodyZ;
  23320. registeredMesh.mesh.position.z = bodyY;
  23321. }
  23322. if (!registeredMesh.mesh.rotationQuaternion) {
  23323. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23324. }
  23325. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23326. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23327. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23328. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23329. }
  23330. };
  23331. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23332. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23333. };
  23334. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23335. this.unregisterMesh(mesh);
  23336. mesh.computeWorldMatrix(true);
  23337. switch (impostor) {
  23338. case BABYLON.PhysicsEngine.SphereImpostor:
  23339. var bbox = mesh.getBoundingInfo().boundingBox;
  23340. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23341. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23342. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23343. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23344. case BABYLON.PhysicsEngine.BoxImpostor:
  23345. bbox = mesh.getBoundingInfo().boundingBox;
  23346. var min = bbox.minimumWorld;
  23347. var max = bbox.maximumWorld;
  23348. var box = max.subtract(min).scale(0.5);
  23349. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23350. case BABYLON.PhysicsEngine.PlaneImpostor:
  23351. return this._createPlane(mesh, options);
  23352. case BABYLON.PhysicsEngine.MeshImpostor:
  23353. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23354. var rawFaces = mesh.getIndices();
  23355. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23356. }
  23357. return null;
  23358. };
  23359. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23360. var shape = new CANNON.Sphere(radius);
  23361. if (!options) {
  23362. return shape;
  23363. }
  23364. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23365. };
  23366. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23367. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23368. if (!options) {
  23369. return shape;
  23370. }
  23371. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23372. };
  23373. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23374. var shape = new CANNON.Plane();
  23375. if (!options) {
  23376. return shape;
  23377. }
  23378. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23379. };
  23380. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23381. var verts = [], faces = [];
  23382. mesh.computeWorldMatrix(true);
  23383. // Get vertices
  23384. for (var i = 0; i < rawVerts.length; i += 3) {
  23385. var transformed = BABYLON.Vector3.Zero();
  23386. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23387. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23388. }
  23389. // Get faces
  23390. for (var j = 0; j < rawFaces.length; j += 3) {
  23391. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23392. }
  23393. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23394. if (!options) {
  23395. return shape;
  23396. }
  23397. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23398. };
  23399. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23400. var index;
  23401. var mat;
  23402. for (index = 0; index < this._physicsMaterials.length; index++) {
  23403. mat = this._physicsMaterials[index];
  23404. if (mat.friction === friction && mat.restitution === restitution) {
  23405. return mat;
  23406. }
  23407. }
  23408. var currentMat = new CANNON.Material();
  23409. currentMat.friction = friction;
  23410. currentMat.restitution = restitution;
  23411. this._physicsMaterials.push(currentMat);
  23412. for (index = 0; index < this._physicsMaterials.length; index++) {
  23413. mat = this._physicsMaterials[index];
  23414. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23415. contactMaterial.contactEquationStiffness = 1e10;
  23416. contactMaterial.contactEquationRegularizationTime = 10;
  23417. this._world.addContactMaterial(contactMaterial);
  23418. }
  23419. return currentMat;
  23420. };
  23421. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23422. var initialRotation = null;
  23423. if (mesh.rotationQuaternion) {
  23424. initialRotation = mesh.rotationQuaternion.clone();
  23425. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23426. }
  23427. // The delta between the mesh position and the mesh bounding box center
  23428. var bbox = mesh.getBoundingInfo().boundingBox;
  23429. var deltaPosition = mesh.position.subtract(bbox.center);
  23430. var material = this._addMaterial(friction, restitution);
  23431. var body = new CANNON.RigidBody(mass, shape, material);
  23432. if (initialRotation) {
  23433. body.quaternion.x = initialRotation.x;
  23434. body.quaternion.z = initialRotation.y;
  23435. body.quaternion.y = initialRotation.z;
  23436. body.quaternion.w = -initialRotation.w;
  23437. }
  23438. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23439. this._world.add(body);
  23440. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23441. return body;
  23442. };
  23443. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23444. var compoundShape = new CANNON.Compound();
  23445. for (var index = 0; index < parts.length; index++) {
  23446. var mesh = parts[index].mesh;
  23447. var shape = this.registerMesh(mesh, parts[index].impostor);
  23448. if (index == 0) {
  23449. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23450. }
  23451. else {
  23452. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23453. }
  23454. }
  23455. var initialMesh = parts[0].mesh;
  23456. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23457. body.parts = parts;
  23458. return body;
  23459. };
  23460. CannonJSPlugin.prototype._unbindBody = function (body) {
  23461. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23462. var registeredMesh = this._registeredMeshes[index];
  23463. if (registeredMesh.body === body) {
  23464. registeredMesh.body = null;
  23465. registeredMesh.delta = 0;
  23466. }
  23467. }
  23468. };
  23469. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23470. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23471. var registeredMesh = this._registeredMeshes[index];
  23472. if (registeredMesh.mesh === mesh) {
  23473. // Remove body
  23474. if (registeredMesh.body) {
  23475. this._world.remove(registeredMesh.body);
  23476. this._unbindBody(registeredMesh.body);
  23477. }
  23478. this._registeredMeshes.splice(index, 1);
  23479. return;
  23480. }
  23481. }
  23482. };
  23483. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23484. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23485. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23486. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23487. var registeredMesh = this._registeredMeshes[index];
  23488. if (registeredMesh.mesh === mesh) {
  23489. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23490. return;
  23491. }
  23492. }
  23493. };
  23494. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23495. var body1 = null, body2 = null;
  23496. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23497. var registeredMesh = this._registeredMeshes[index];
  23498. if (registeredMesh.mesh === mesh1) {
  23499. body1 = registeredMesh.body;
  23500. }
  23501. else if (registeredMesh.mesh === mesh2) {
  23502. body2 = registeredMesh.body;
  23503. }
  23504. }
  23505. if (!body1 || !body2) {
  23506. return false;
  23507. }
  23508. 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));
  23509. this._world.addConstraint(constraint);
  23510. return true;
  23511. };
  23512. CannonJSPlugin.prototype.dispose = function () {
  23513. while (this._registeredMeshes.length) {
  23514. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23515. }
  23516. };
  23517. CannonJSPlugin.prototype.isSupported = function () {
  23518. return window.CANNON !== undefined;
  23519. };
  23520. return CannonJSPlugin;
  23521. })();
  23522. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23523. })(BABYLON || (BABYLON = {}));
  23524. var BABYLON;
  23525. (function (BABYLON) {
  23526. var OimoJSPlugin = (function () {
  23527. function OimoJSPlugin() {
  23528. this._registeredMeshes = [];
  23529. /**
  23530. * Update the body position according to the mesh position
  23531. * @param mesh
  23532. */
  23533. this.updateBodyPosition = function (mesh) {
  23534. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23535. var registeredMesh = this._registeredMeshes[index];
  23536. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23537. var body = registeredMesh.body.body;
  23538. mesh.computeWorldMatrix(true);
  23539. var center = mesh.getBoundingInfo().boundingBox.center;
  23540. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  23541. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  23542. body.sleeping = false;
  23543. return;
  23544. }
  23545. // Case where the parent has been updated
  23546. if (registeredMesh.mesh.parent === mesh) {
  23547. mesh.computeWorldMatrix(true);
  23548. registeredMesh.mesh.computeWorldMatrix(true);
  23549. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  23550. var absoluteRotation = mesh.rotation;
  23551. body = registeredMesh.body.body;
  23552. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  23553. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  23554. body.sleeping = false;
  23555. return;
  23556. }
  23557. }
  23558. };
  23559. }
  23560. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  23561. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23562. };
  23563. OimoJSPlugin.prototype.initialize = function (iterations) {
  23564. this._world = new OIMO.World();
  23565. this._world.clear();
  23566. };
  23567. OimoJSPlugin.prototype.setGravity = function (gravity) {
  23568. this._world.gravity = gravity;
  23569. };
  23570. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23571. var body = null;
  23572. this.unregisterMesh(mesh);
  23573. mesh.computeWorldMatrix(true);
  23574. var initialRotation = null;
  23575. if (mesh.rotationQuaternion) {
  23576. initialRotation = mesh.rotationQuaternion.clone();
  23577. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23578. mesh.computeWorldMatrix(true);
  23579. }
  23580. var bbox = mesh.getBoundingInfo().boundingBox;
  23581. // The delta between the mesh position and the mesh bounding box center
  23582. var deltaPosition = mesh.position.subtract(bbox.center);
  23583. // Transform delta position with the rotation
  23584. if (initialRotation) {
  23585. var m = new BABYLON.Matrix();
  23586. initialRotation.toRotationMatrix(m);
  23587. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  23588. }
  23589. // register mesh
  23590. switch (impostor) {
  23591. case BABYLON.PhysicsEngine.SphereImpostor:
  23592. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23593. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23594. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23595. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23596. body = new OIMO.Body({
  23597. type: 'sphere',
  23598. size: [size],
  23599. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23600. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23601. move: options.mass != 0,
  23602. config: [options.mass, options.friction, options.restitution],
  23603. world: this._world
  23604. });
  23605. break;
  23606. case BABYLON.PhysicsEngine.PlaneImpostor:
  23607. //Oimo "fakes" a cylinder as a box, so why don't we!
  23608. case BABYLON.PhysicsEngine.CylinderImpostor:
  23609. case BABYLON.PhysicsEngine.BoxImpostor:
  23610. var min = bbox.minimumWorld;
  23611. var max = bbox.maximumWorld;
  23612. var box = max.subtract(min);
  23613. var sizeX = this._checkWithEpsilon(box.x);
  23614. var sizeY = this._checkWithEpsilon(box.y);
  23615. var sizeZ = this._checkWithEpsilon(box.z);
  23616. body = new OIMO.Body({
  23617. type: 'box',
  23618. size: [sizeX, sizeY, sizeZ],
  23619. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23620. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23621. move: options.mass != 0,
  23622. config: [options.mass, options.friction, options.restitution],
  23623. world: this._world
  23624. });
  23625. break;
  23626. }
  23627. //If quaternion was set as the rotation of the object
  23628. if (initialRotation) {
  23629. //We have to access the rigid body's properties to set the quaternion.
  23630. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  23631. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  23632. //update the internal rotation matrix
  23633. body.body.syncShapes();
  23634. }
  23635. this._registeredMeshes.push({
  23636. mesh: mesh,
  23637. body: body,
  23638. delta: deltaPosition
  23639. });
  23640. return body;
  23641. };
  23642. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23643. var types = [], sizes = [], positions = [], rotations = [];
  23644. var initialMesh = parts[0].mesh;
  23645. for (var index = 0; index < parts.length; index++) {
  23646. var part = parts[index];
  23647. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  23648. types.push(bodyParameters.type);
  23649. sizes.push.apply(sizes, bodyParameters.size);
  23650. positions.push.apply(positions, bodyParameters.pos);
  23651. rotations.push.apply(rotations, bodyParameters.rot);
  23652. }
  23653. var body = new OIMO.Body({
  23654. type: types,
  23655. size: sizes,
  23656. pos: positions,
  23657. rot: rotations,
  23658. move: options.mass != 0,
  23659. config: [options.mass, options.friction, options.restitution],
  23660. world: this._world
  23661. });
  23662. this._registeredMeshes.push({
  23663. mesh: initialMesh,
  23664. body: body
  23665. });
  23666. return body;
  23667. };
  23668. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  23669. var bodyParameters = null;
  23670. var mesh = part.mesh;
  23671. // We need the bounding box/sphere info to compute the physics body
  23672. mesh.computeWorldMatrix();
  23673. switch (part.impostor) {
  23674. case BABYLON.PhysicsEngine.SphereImpostor:
  23675. var bbox = mesh.getBoundingInfo().boundingBox;
  23676. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23677. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23678. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23679. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23680. bodyParameters = {
  23681. type: 'sphere',
  23682. /* bug with oimo : sphere needs 3 sizes in this case */
  23683. size: [size, -1, -1],
  23684. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  23685. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23686. };
  23687. break;
  23688. case BABYLON.PhysicsEngine.PlaneImpostor:
  23689. case BABYLON.PhysicsEngine.BoxImpostor:
  23690. bbox = mesh.getBoundingInfo().boundingBox;
  23691. var min = bbox.minimumWorld;
  23692. var max = bbox.maximumWorld;
  23693. var box = max.subtract(min);
  23694. var sizeX = this._checkWithEpsilon(box.x);
  23695. var sizeY = this._checkWithEpsilon(box.y);
  23696. var sizeZ = this._checkWithEpsilon(box.z);
  23697. var relativePosition = mesh.position;
  23698. bodyParameters = {
  23699. type: 'box',
  23700. size: [sizeX, sizeY, sizeZ],
  23701. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  23702. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23703. };
  23704. break;
  23705. }
  23706. return bodyParameters;
  23707. };
  23708. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  23709. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23710. var registeredMesh = this._registeredMeshes[index];
  23711. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23712. if (registeredMesh.body) {
  23713. this._world.removeRigidBody(registeredMesh.body.body);
  23714. this._unbindBody(registeredMesh.body);
  23715. }
  23716. this._registeredMeshes.splice(index, 1);
  23717. return;
  23718. }
  23719. }
  23720. };
  23721. OimoJSPlugin.prototype._unbindBody = function (body) {
  23722. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23723. var registeredMesh = this._registeredMeshes[index];
  23724. if (registeredMesh.body === body) {
  23725. registeredMesh.body = null;
  23726. }
  23727. }
  23728. };
  23729. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23730. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23731. var registeredMesh = this._registeredMeshes[index];
  23732. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23733. // Get object mass to have a behaviour similar to cannon.js
  23734. var mass = registeredMesh.body.body.massInfo.mass;
  23735. // The force is scaled with the mass of object
  23736. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  23737. return;
  23738. }
  23739. }
  23740. };
  23741. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23742. var body1 = null, body2 = null;
  23743. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23744. var registeredMesh = this._registeredMeshes[index];
  23745. if (registeredMesh.mesh === mesh1) {
  23746. body1 = registeredMesh.body.body;
  23747. }
  23748. else if (registeredMesh.mesh === mesh2) {
  23749. body2 = registeredMesh.body.body;
  23750. }
  23751. }
  23752. if (!body1 || !body2) {
  23753. return false;
  23754. }
  23755. if (!options) {
  23756. options = {};
  23757. }
  23758. new OIMO.Link({
  23759. type: options.type,
  23760. body1: body1,
  23761. body2: body2,
  23762. min: options.min,
  23763. max: options.max,
  23764. axe1: options.axe1,
  23765. axe2: options.axe2,
  23766. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23767. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23768. collision: options.collision,
  23769. spring: options.spring,
  23770. world: this._world
  23771. });
  23772. return true;
  23773. };
  23774. OimoJSPlugin.prototype.dispose = function () {
  23775. this._world.clear();
  23776. while (this._registeredMeshes.length) {
  23777. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23778. }
  23779. };
  23780. OimoJSPlugin.prototype.isSupported = function () {
  23781. return OIMO !== undefined;
  23782. };
  23783. OimoJSPlugin.prototype._getLastShape = function (body) {
  23784. var lastShape = body.shapes;
  23785. while (lastShape.next) {
  23786. lastShape = lastShape.next;
  23787. }
  23788. return lastShape;
  23789. };
  23790. OimoJSPlugin.prototype.runOneStep = function (time) {
  23791. this._world.step();
  23792. // Update the position of all registered meshes
  23793. var i = this._registeredMeshes.length;
  23794. var m;
  23795. while (i--) {
  23796. var body = this._registeredMeshes[i].body.body;
  23797. var mesh = this._registeredMeshes[i].mesh;
  23798. var delta = this._registeredMeshes[i].delta;
  23799. if (!body.sleeping) {
  23800. if (body.shapes.next) {
  23801. var parentShape = this._getLastShape(body);
  23802. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23803. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23804. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23805. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23806. if (!mesh.rotationQuaternion) {
  23807. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23808. }
  23809. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23810. mesh.computeWorldMatrix();
  23811. }
  23812. else {
  23813. m = body.getMatrix();
  23814. mtx = BABYLON.Matrix.FromArray(m);
  23815. // Body position
  23816. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23817. if (!delta) {
  23818. mesh.position.x = bodyX;
  23819. mesh.position.y = bodyY;
  23820. mesh.position.z = bodyZ;
  23821. }
  23822. else {
  23823. mesh.position.x = bodyX + delta.x;
  23824. mesh.position.y = bodyY + delta.y;
  23825. mesh.position.z = bodyZ + delta.z;
  23826. }
  23827. if (!mesh.rotationQuaternion) {
  23828. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23829. }
  23830. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23831. mesh.computeWorldMatrix();
  23832. }
  23833. }
  23834. }
  23835. };
  23836. return OimoJSPlugin;
  23837. })();
  23838. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23839. })(BABYLON || (BABYLON = {}));
  23840. var BABYLON;
  23841. (function (BABYLON) {
  23842. var PhysicsEngine = (function () {
  23843. function PhysicsEngine(plugin) {
  23844. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23845. }
  23846. PhysicsEngine.prototype._initialize = function (gravity) {
  23847. this._currentPlugin.initialize();
  23848. this._setGravity(gravity);
  23849. };
  23850. PhysicsEngine.prototype._runOneStep = function (delta) {
  23851. if (delta > 0.1) {
  23852. delta = 0.1;
  23853. }
  23854. else if (delta <= 0) {
  23855. delta = 1.0 / 60.0;
  23856. }
  23857. this._currentPlugin.runOneStep(delta);
  23858. };
  23859. PhysicsEngine.prototype._setGravity = function (gravity) {
  23860. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23861. this._currentPlugin.setGravity(this.gravity);
  23862. };
  23863. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23864. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23865. };
  23866. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23867. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23868. };
  23869. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23870. this._currentPlugin.unregisterMesh(mesh);
  23871. };
  23872. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23873. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23874. };
  23875. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23876. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23877. };
  23878. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23879. this._currentPlugin.updateBodyPosition(mesh);
  23880. };
  23881. PhysicsEngine.prototype.dispose = function () {
  23882. this._currentPlugin.dispose();
  23883. };
  23884. PhysicsEngine.prototype.isSupported = function () {
  23885. return this._currentPlugin.isSupported();
  23886. };
  23887. // Statics
  23888. PhysicsEngine.NoImpostor = 0;
  23889. PhysicsEngine.SphereImpostor = 1;
  23890. PhysicsEngine.BoxImpostor = 2;
  23891. PhysicsEngine.PlaneImpostor = 3;
  23892. PhysicsEngine.MeshImpostor = 4;
  23893. PhysicsEngine.CapsuleImpostor = 5;
  23894. PhysicsEngine.ConeImpostor = 6;
  23895. PhysicsEngine.CylinderImpostor = 7;
  23896. PhysicsEngine.ConvexHullImpostor = 8;
  23897. PhysicsEngine.Epsilon = 0.001;
  23898. return PhysicsEngine;
  23899. })();
  23900. BABYLON.PhysicsEngine = PhysicsEngine;
  23901. })(BABYLON || (BABYLON = {}));
  23902. var BABYLON;
  23903. (function (BABYLON) {
  23904. var serializeLight = function (light) {
  23905. var serializationObject = {};
  23906. serializationObject.name = light.name;
  23907. serializationObject.id = light.id;
  23908. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23909. if (light instanceof BABYLON.PointLight) {
  23910. serializationObject.type = 0;
  23911. serializationObject.position = light.position.asArray();
  23912. }
  23913. else if (light instanceof BABYLON.DirectionalLight) {
  23914. serializationObject.type = 1;
  23915. var directionalLight = light;
  23916. serializationObject.position = directionalLight.position.asArray();
  23917. serializationObject.direction = directionalLight.direction.asArray();
  23918. }
  23919. else if (light instanceof BABYLON.SpotLight) {
  23920. serializationObject.type = 2;
  23921. var spotLight = light;
  23922. serializationObject.position = spotLight.position.asArray();
  23923. serializationObject.direction = spotLight.position.asArray();
  23924. serializationObject.angle = spotLight.angle;
  23925. serializationObject.exponent = spotLight.exponent;
  23926. }
  23927. else if (light instanceof BABYLON.HemisphericLight) {
  23928. serializationObject.type = 3;
  23929. var hemisphericLight = light;
  23930. serializationObject.direction = hemisphericLight.direction.asArray();
  23931. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23932. }
  23933. if (light.intensity) {
  23934. serializationObject.intensity = light.intensity;
  23935. }
  23936. serializationObject.range = light.range;
  23937. serializationObject.diffuse = light.diffuse.asArray();
  23938. serializationObject.specular = light.specular.asArray();
  23939. return serializationObject;
  23940. };
  23941. var serializeFresnelParameter = function (fresnelParameter) {
  23942. var serializationObject = {};
  23943. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23944. serializationObject.leftColor = fresnelParameter.leftColor;
  23945. serializationObject.rightColor = fresnelParameter.rightColor;
  23946. serializationObject.bias = fresnelParameter.bias;
  23947. serializationObject.power = fresnelParameter.power;
  23948. return serializationObject;
  23949. };
  23950. var appendAnimations = function (source, destination) {
  23951. if (source.animations) {
  23952. destination.animations = [];
  23953. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23954. var animation = source.animations[animationIndex];
  23955. destination.animations.push(serializeAnimation(animation));
  23956. }
  23957. }
  23958. };
  23959. var serializeCamera = function (camera) {
  23960. var serializationObject = {};
  23961. serializationObject.name = camera.name;
  23962. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23963. serializationObject.id = camera.id;
  23964. serializationObject.position = camera.position.asArray();
  23965. // Parent
  23966. if (camera.parent) {
  23967. serializationObject.parentId = camera.parent.id;
  23968. }
  23969. serializationObject.fov = camera.fov;
  23970. serializationObject.minZ = camera.minZ;
  23971. serializationObject.maxZ = camera.maxZ;
  23972. serializationObject.inertia = camera.inertia;
  23973. //setting the type
  23974. if (camera instanceof BABYLON.FreeCamera) {
  23975. serializationObject.type = "FreeCamera";
  23976. }
  23977. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23978. serializationObject.type = "ArcRotateCamera";
  23979. }
  23980. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23981. serializationObject.type = "AnaglyphArcRotateCamera";
  23982. }
  23983. else if (camera instanceof BABYLON.GamepadCamera) {
  23984. serializationObject.type = "GamepadCamera";
  23985. }
  23986. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23987. serializationObject.type = "AnaglyphFreeCamera";
  23988. }
  23989. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23990. serializationObject.type = "DeviceOrientationCamera";
  23991. }
  23992. else if (camera instanceof BABYLON.FollowCamera) {
  23993. serializationObject.type = "FollowCamera";
  23994. }
  23995. else if (camera instanceof BABYLON.TouchCamera) {
  23996. serializationObject.type = "TouchCamera";
  23997. }
  23998. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23999. serializationObject.type = "VirtualJoysticksCamera";
  24000. }
  24001. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  24002. serializationObject.type = "WebVRFreeCamera";
  24003. }
  24004. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  24005. serializationObject.type = "VRDeviceOrientationFreeCamera";
  24006. }
  24007. //special properties of specific cameras
  24008. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24009. var arcCamera = camera;
  24010. serializationObject.alpha = arcCamera.alpha;
  24011. serializationObject.beta = arcCamera.beta;
  24012. serializationObject.radius = arcCamera.radius;
  24013. if (arcCamera.target && arcCamera.target.id) {
  24014. serializationObject.lockedTargetId = arcCamera.target.id;
  24015. }
  24016. }
  24017. else if (camera instanceof BABYLON.FollowCamera) {
  24018. var followCam = camera;
  24019. serializationObject.radius = followCam.radius;
  24020. serializationObject.heightOffset = followCam.heightOffset;
  24021. serializationObject.rotationOffset = followCam.rotationOffset;
  24022. }
  24023. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24024. //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.
  24025. if (camera['_interaxialDistance'] !== undefined) {
  24026. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24027. }
  24028. }
  24029. //general properties that not all cameras have. The [] is due to typescript's type safety
  24030. if (camera['speed'] !== undefined) {
  24031. serializationObject.speed = camera['speed'];
  24032. }
  24033. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24034. serializationObject.target = camera['target'].asArray();
  24035. }
  24036. // Target
  24037. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24038. serializationObject.rotation = camera['rotation'].asArray();
  24039. }
  24040. // Locked target
  24041. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24042. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24043. }
  24044. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24045. serializationObject.applyGravity = camera['applyGravity'] || false;
  24046. if (camera['ellipsoid']) {
  24047. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24048. }
  24049. // Animations
  24050. appendAnimations(camera, serializationObject);
  24051. // Layer mask
  24052. serializationObject.layerMask = camera.layerMask;
  24053. return serializationObject;
  24054. };
  24055. var serializeAnimation = function (animation) {
  24056. var serializationObject = {};
  24057. serializationObject.name = animation.name;
  24058. serializationObject.property = animation.targetProperty;
  24059. serializationObject.framePerSecond = animation.framePerSecond;
  24060. serializationObject.dataType = animation.dataType;
  24061. serializationObject.loopBehavior = animation.loopMode;
  24062. var dataType = animation.dataType;
  24063. serializationObject.keys = [];
  24064. var keys = animation.getKeys();
  24065. for (var index = 0; index < keys.length; index++) {
  24066. var animationKey = keys[index];
  24067. var key = {};
  24068. key.frame = animationKey.frame;
  24069. switch (dataType) {
  24070. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24071. key.values = [animationKey.value];
  24072. break;
  24073. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24074. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24075. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24076. key.values = animationKey.value.asArray();
  24077. break;
  24078. }
  24079. serializationObject.keys.push(key);
  24080. }
  24081. return serializationObject;
  24082. };
  24083. var serializeMultiMaterial = function (material) {
  24084. var serializationObject = {};
  24085. serializationObject.name = material.name;
  24086. serializationObject.id = material.id;
  24087. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24088. serializationObject.materials = [];
  24089. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24090. var subMat = material.subMaterials[matIndex];
  24091. if (subMat) {
  24092. serializationObject.materials.push(subMat.id);
  24093. }
  24094. else {
  24095. serializationObject.materials.push(null);
  24096. }
  24097. }
  24098. return serializationObject;
  24099. };
  24100. var serializeMaterial = function (material) {
  24101. var serializationObject = {};
  24102. serializationObject.name = material.name;
  24103. serializationObject.ambient = material.ambientColor.asArray();
  24104. serializationObject.diffuse = material.diffuseColor.asArray();
  24105. serializationObject.specular = material.specularColor.asArray();
  24106. serializationObject.specularPower = material.specularPower;
  24107. serializationObject.emissive = material.emissiveColor.asArray();
  24108. serializationObject.alpha = material.alpha;
  24109. serializationObject.id = material.id;
  24110. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24111. serializationObject.backFaceCulling = material.backFaceCulling;
  24112. if (material.diffuseTexture) {
  24113. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24114. }
  24115. if (material.diffuseFresnelParameters) {
  24116. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24117. }
  24118. if (material.ambientTexture) {
  24119. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24120. }
  24121. if (material.opacityTexture) {
  24122. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24123. }
  24124. if (material.opacityFresnelParameters) {
  24125. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24126. }
  24127. if (material.reflectionTexture) {
  24128. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24129. }
  24130. if (material.reflectionFresnelParameters) {
  24131. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24132. }
  24133. if (material.emissiveTexture) {
  24134. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24135. }
  24136. if (material.emissiveFresnelParameters) {
  24137. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24138. }
  24139. if (material.specularTexture) {
  24140. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24141. }
  24142. if (material.bumpTexture) {
  24143. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24144. }
  24145. return serializationObject;
  24146. };
  24147. var serializeTexture = function (texture) {
  24148. var serializationObject = {};
  24149. if (!texture.name) {
  24150. return null;
  24151. }
  24152. if (texture instanceof BABYLON.CubeTexture) {
  24153. serializationObject.name = texture.name;
  24154. serializationObject.hasAlpha = texture.hasAlpha;
  24155. serializationObject.isCube = true;
  24156. serializationObject.level = texture.level;
  24157. serializationObject.coordinatesMode = texture.coordinatesMode;
  24158. return serializationObject;
  24159. }
  24160. if (texture instanceof BABYLON.MirrorTexture) {
  24161. var mirrorTexture = texture;
  24162. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24163. serializationObject.renderList = [];
  24164. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  24165. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24166. }
  24167. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24168. }
  24169. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24170. var renderTargetTexture = texture;
  24171. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24172. serializationObject.renderList = [];
  24173. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24174. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24175. }
  24176. }
  24177. var regularTexture = texture;
  24178. serializationObject.name = texture.name;
  24179. serializationObject.hasAlpha = texture.hasAlpha;
  24180. serializationObject.level = texture.level;
  24181. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24182. serializationObject.coordinatesMode = texture.coordinatesMode;
  24183. serializationObject.uOffset = regularTexture.uOffset;
  24184. serializationObject.vOffset = regularTexture.vOffset;
  24185. serializationObject.uScale = regularTexture.uScale;
  24186. serializationObject.vScale = regularTexture.vScale;
  24187. serializationObject.uAng = regularTexture.uAng;
  24188. serializationObject.vAng = regularTexture.vAng;
  24189. serializationObject.wAng = regularTexture.wAng;
  24190. serializationObject.wrapU = texture.wrapU;
  24191. serializationObject.wrapV = texture.wrapV;
  24192. // Animations
  24193. appendAnimations(texture, serializationObject);
  24194. return serializationObject;
  24195. };
  24196. var serializeSkeleton = function (skeleton) {
  24197. var serializationObject = {};
  24198. serializationObject.name = skeleton.name;
  24199. serializationObject.id = skeleton.id;
  24200. serializationObject.bones = [];
  24201. for (var index = 0; index < skeleton.bones.length; index++) {
  24202. var bone = skeleton.bones[index];
  24203. var serializedBone = {
  24204. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24205. name: bone.name,
  24206. matrix: bone.getLocalMatrix().toArray()
  24207. };
  24208. serializationObject.bones.push(serializedBone);
  24209. if (bone.animations && bone.animations.length > 0) {
  24210. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24211. }
  24212. }
  24213. return serializationObject;
  24214. };
  24215. var serializeParticleSystem = function (particleSystem) {
  24216. var serializationObject = {};
  24217. serializationObject.emitterId = particleSystem.emitter.id;
  24218. serializationObject.capacity = particleSystem.getCapacity();
  24219. if (particleSystem.particleTexture) {
  24220. serializationObject.textureName = particleSystem.particleTexture.name;
  24221. }
  24222. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24223. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24224. serializationObject.minSize = particleSystem.minSize;
  24225. serializationObject.maxSize = particleSystem.maxSize;
  24226. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24227. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24228. serializationObject.emitRate = particleSystem.emitRate;
  24229. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24230. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24231. serializationObject.gravity = particleSystem.gravity.asArray();
  24232. serializationObject.direction1 = particleSystem.direction1.asArray();
  24233. serializationObject.direction2 = particleSystem.direction2.asArray();
  24234. serializationObject.color1 = particleSystem.color1.asArray();
  24235. serializationObject.color2 = particleSystem.color2.asArray();
  24236. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24237. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24238. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24239. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24240. serializationObject.blendMode = particleSystem.blendMode;
  24241. return serializationObject;
  24242. };
  24243. var serializeLensFlareSystem = function (lensFlareSystem) {
  24244. var serializationObject = {};
  24245. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24246. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24247. serializationObject.flares = [];
  24248. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24249. var flare = lensFlareSystem.lensFlares[index];
  24250. serializationObject.flares.push({
  24251. size: flare.size,
  24252. position: flare.position,
  24253. color: flare.color.asArray(),
  24254. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24255. });
  24256. }
  24257. return serializationObject;
  24258. };
  24259. var serializeShadowGenerator = function (light) {
  24260. var serializationObject = {};
  24261. var shadowGenerator = light.getShadowGenerator();
  24262. serializationObject.lightId = light.id;
  24263. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24264. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24265. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24266. serializationObject.renderList = [];
  24267. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24268. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24269. serializationObject.renderList.push(mesh.id);
  24270. }
  24271. return serializationObject;
  24272. };
  24273. var serializedGeometries = [];
  24274. var serializeGeometry = function (geometry, serializationGeometries) {
  24275. if (serializedGeometries[geometry.id]) {
  24276. return;
  24277. }
  24278. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24279. serializationGeometries.boxes.push(serializeBox(geometry));
  24280. }
  24281. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24282. serializationGeometries.spheres.push(serializeSphere(geometry));
  24283. }
  24284. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24285. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24286. }
  24287. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24288. serializationGeometries.toruses.push(serializeTorus(geometry));
  24289. }
  24290. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24291. serializationGeometries.grounds.push(serializeGround(geometry));
  24292. }
  24293. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24294. serializationGeometries.planes.push(serializePlane(geometry));
  24295. }
  24296. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24297. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24298. }
  24299. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24300. throw new Error("Unknown primitive type");
  24301. }
  24302. else {
  24303. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24304. }
  24305. serializedGeometries[geometry.id] = true;
  24306. };
  24307. var serializeGeometryBase = function (geometry) {
  24308. var serializationObject = {};
  24309. serializationObject.id = geometry.id;
  24310. if (BABYLON.Tags.HasTags(geometry)) {
  24311. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24312. }
  24313. return serializationObject;
  24314. };
  24315. var serializeVertexData = function (vertexData) {
  24316. var serializationObject = serializeGeometryBase(vertexData);
  24317. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24318. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24319. }
  24320. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24321. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24322. }
  24323. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24324. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24325. }
  24326. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24327. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24328. }
  24329. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24330. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24331. }
  24332. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24333. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24334. }
  24335. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24336. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24337. }
  24338. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24339. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24340. }
  24341. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24342. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24343. }
  24344. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24345. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24346. serializationObject.matricesIndices._isExpanded = true;
  24347. }
  24348. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24349. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24350. }
  24351. serializationObject.indices = vertexData.getIndices();
  24352. return serializationObject;
  24353. };
  24354. var serializePrimitive = function (primitive) {
  24355. var serializationObject = serializeGeometryBase(primitive);
  24356. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24357. return serializationObject;
  24358. };
  24359. var serializeBox = function (box) {
  24360. var serializationObject = serializePrimitive(box);
  24361. serializationObject.size = box.size;
  24362. return serializationObject;
  24363. };
  24364. var serializeSphere = function (sphere) {
  24365. var serializationObject = serializePrimitive(sphere);
  24366. serializationObject.segments = sphere.segments;
  24367. serializationObject.diameter = sphere.diameter;
  24368. return serializationObject;
  24369. };
  24370. var serializeCylinder = function (cylinder) {
  24371. var serializationObject = serializePrimitive(cylinder);
  24372. serializationObject.height = cylinder.height;
  24373. serializationObject.diameterTop = cylinder.diameterTop;
  24374. serializationObject.diameterBottom = cylinder.diameterBottom;
  24375. serializationObject.tessellation = cylinder.tessellation;
  24376. return serializationObject;
  24377. };
  24378. var serializeTorus = function (torus) {
  24379. var serializationObject = serializePrimitive(torus);
  24380. serializationObject.diameter = torus.diameter;
  24381. serializationObject.thickness = torus.thickness;
  24382. serializationObject.tessellation = torus.tessellation;
  24383. return serializationObject;
  24384. };
  24385. var serializeGround = function (ground) {
  24386. var serializationObject = serializePrimitive(ground);
  24387. serializationObject.width = ground.width;
  24388. serializationObject.height = ground.height;
  24389. serializationObject.subdivisions = ground.subdivisions;
  24390. return serializationObject;
  24391. };
  24392. var serializePlane = function (plane) {
  24393. var serializationObject = serializePrimitive(plane);
  24394. serializationObject.size = plane.size;
  24395. return serializationObject;
  24396. };
  24397. var serializeTorusKnot = function (torusKnot) {
  24398. var serializationObject = serializePrimitive(torusKnot);
  24399. serializationObject.radius = torusKnot.radius;
  24400. serializationObject.tube = torusKnot.tube;
  24401. serializationObject.radialSegments = torusKnot.radialSegments;
  24402. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24403. serializationObject.p = torusKnot.p;
  24404. serializationObject.q = torusKnot.q;
  24405. return serializationObject;
  24406. };
  24407. var serializeMesh = function (mesh, serializationScene) {
  24408. var serializationObject = {};
  24409. serializationObject.name = mesh.name;
  24410. serializationObject.id = mesh.id;
  24411. if (BABYLON.Tags.HasTags(mesh)) {
  24412. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24413. }
  24414. serializationObject.position = mesh.position.asArray();
  24415. if (mesh.rotationQuaternion) {
  24416. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24417. }
  24418. else if (mesh.rotation) {
  24419. serializationObject.rotation = mesh.rotation.asArray();
  24420. }
  24421. serializationObject.scaling = mesh.scaling.asArray();
  24422. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24423. serializationObject.isEnabled = mesh.isEnabled();
  24424. serializationObject.isVisible = mesh.isVisible;
  24425. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24426. serializationObject.pickable = mesh.isPickable;
  24427. serializationObject.receiveShadows = mesh.receiveShadows;
  24428. serializationObject.billboardMode = mesh.billboardMode;
  24429. serializationObject.visibility = mesh.visibility;
  24430. serializationObject.checkCollisions = mesh.checkCollisions;
  24431. // Parent
  24432. if (mesh.parent) {
  24433. serializationObject.parentId = mesh.parent.id;
  24434. }
  24435. // Geometry
  24436. var geometry = mesh._geometry;
  24437. if (geometry) {
  24438. var geometryId = geometry.id;
  24439. serializationObject.geometryId = geometryId;
  24440. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24441. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize to be able to reload the mesh with its geometry
  24442. serializeGeometry(geometry, serializationScene.geometries);
  24443. }
  24444. // SubMeshes
  24445. serializationObject.subMeshes = [];
  24446. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24447. var subMesh = mesh.subMeshes[subIndex];
  24448. serializationObject.subMeshes.push({
  24449. materialIndex: subMesh.materialIndex,
  24450. verticesStart: subMesh.verticesStart,
  24451. verticesCount: subMesh.verticesCount,
  24452. indexStart: subMesh.indexStart,
  24453. indexCount: subMesh.indexCount
  24454. });
  24455. }
  24456. }
  24457. // Material
  24458. if (mesh.material) {
  24459. serializationObject.materialId = mesh.material.id;
  24460. }
  24461. else {
  24462. mesh.material = null;
  24463. }
  24464. // Skeleton
  24465. if (mesh.skeleton) {
  24466. serializationObject.skeletonId = mesh.skeleton.id;
  24467. }
  24468. // Physics
  24469. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  24470. serializationObject.physicsMass = mesh.getPhysicsMass();
  24471. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  24472. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  24473. switch (mesh.getPhysicsImpostor()) {
  24474. case BABYLON.PhysicsEngine.BoxImpostor:
  24475. serializationObject.physicsImpostor = 1;
  24476. break;
  24477. case BABYLON.PhysicsEngine.SphereImpostor:
  24478. serializationObject.physicsImpostor = 2;
  24479. break;
  24480. }
  24481. }
  24482. // Instances
  24483. serializationObject.instances = [];
  24484. for (var index = 0; index < mesh.instances.length; index++) {
  24485. var instance = mesh.instances[index];
  24486. var serializationInstance = {
  24487. name: instance.name,
  24488. position: instance.position,
  24489. rotation: instance.rotation,
  24490. rotationQuaternion: instance.rotationQuaternion,
  24491. scaling: instance.scaling
  24492. };
  24493. serializationObject.instances.push(serializationInstance);
  24494. // Animations
  24495. appendAnimations(instance, serializationInstance);
  24496. }
  24497. // Animations
  24498. appendAnimations(mesh, serializationObject);
  24499. // Layer mask
  24500. serializationObject.layerMask = mesh.layerMask;
  24501. return serializationObject;
  24502. };
  24503. var finalizeSingleMesh = function (mesh, serializationObject) {
  24504. //only works if the mesh is already loaded
  24505. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24506. //serialize material
  24507. if (mesh.material) {
  24508. if (mesh.material instanceof BABYLON.StandardMaterial) {
  24509. serializationObject.materials = serializationObject.materials || [];
  24510. if (!serializationObject.materials.some(function (mat) {
  24511. return mat.id == mesh.material.id;
  24512. })) {
  24513. serializationObject.materials.push(serializeMaterial(mesh.material));
  24514. }
  24515. }
  24516. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  24517. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  24518. if (!serializationObject.multiMaterials.some(function (mat) {
  24519. return mat.id == mesh.material.id;
  24520. })) {
  24521. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  24522. }
  24523. }
  24524. }
  24525. //serialize geometry
  24526. var geometry = mesh._geometry;
  24527. if (geometry) {
  24528. if (!serializationObject.geometries) {
  24529. serializationObject.geometries = {};
  24530. serializationObject.geometries.boxes = [];
  24531. serializationObject.geometries.spheres = [];
  24532. serializationObject.geometries.cylinders = [];
  24533. serializationObject.geometries.toruses = [];
  24534. serializationObject.geometries.grounds = [];
  24535. serializationObject.geometries.planes = [];
  24536. serializationObject.geometries.torusKnots = [];
  24537. serializationObject.geometries.vertexData = [];
  24538. }
  24539. serializeGeometry(geometry, serializationObject.geometries);
  24540. }
  24541. // Skeletons
  24542. if (mesh.skeleton) {
  24543. serializationObject.skeletons = serializationObject.skeletons || [];
  24544. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  24545. }
  24546. //serialize the actual mesh
  24547. serializationObject.meshes = serializationObject.meshes || [];
  24548. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24549. }
  24550. };
  24551. var SceneSerializer = (function () {
  24552. function SceneSerializer() {
  24553. }
  24554. SceneSerializer.Serialize = function (scene) {
  24555. var serializationObject = {};
  24556. // Scene
  24557. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  24558. serializationObject.autoClear = scene.autoClear;
  24559. serializationObject.clearColor = scene.clearColor.asArray();
  24560. serializationObject.ambientColor = scene.ambientColor.asArray();
  24561. serializationObject.gravity = scene.gravity.asArray();
  24562. // Fog
  24563. if (scene.fogMode && scene.fogMode !== 0) {
  24564. serializationObject.fogMode = scene.fogMode;
  24565. serializationObject.fogColor = scene.fogColor.asArray();
  24566. serializationObject.fogStart = scene.fogStart;
  24567. serializationObject.fogEnd = scene.fogEnd;
  24568. serializationObject.fogDensity = scene.fogDensity;
  24569. }
  24570. // Lights
  24571. serializationObject.lights = [];
  24572. for (var index = 0; index < scene.lights.length; index++) {
  24573. var light = scene.lights[index];
  24574. serializationObject.lights.push(serializeLight(light));
  24575. }
  24576. // Cameras
  24577. serializationObject.cameras = [];
  24578. for (index = 0; index < scene.cameras.length; index++) {
  24579. var camera = scene.cameras[index];
  24580. serializationObject.cameras.push(serializeCamera(camera));
  24581. }
  24582. if (scene.activeCamera) {
  24583. serializationObject.activeCameraID = scene.activeCamera.id;
  24584. }
  24585. // Materials
  24586. serializationObject.materials = [];
  24587. serializationObject.multiMaterials = [];
  24588. for (index = 0; index < scene.materials.length; index++) {
  24589. var material = scene.materials[index];
  24590. if (material instanceof BABYLON.StandardMaterial) {
  24591. serializationObject.materials.push(serializeMaterial(material));
  24592. }
  24593. else if (material instanceof BABYLON.MultiMaterial) {
  24594. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  24595. }
  24596. }
  24597. // Skeletons
  24598. serializationObject.skeletons = [];
  24599. for (index = 0; index < scene.skeletons.length; index++) {
  24600. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  24601. }
  24602. // Geometries
  24603. serializationObject.geometries = {};
  24604. serializationObject.geometries.boxes = [];
  24605. serializationObject.geometries.spheres = [];
  24606. serializationObject.geometries.cylinders = [];
  24607. serializationObject.geometries.toruses = [];
  24608. serializationObject.geometries.grounds = [];
  24609. serializationObject.geometries.planes = [];
  24610. serializationObject.geometries.torusKnots = [];
  24611. serializationObject.geometries.vertexData = [];
  24612. serializedGeometries = [];
  24613. var geometries = scene.getGeometries();
  24614. for (index = 0; index < geometries.length; index++) {
  24615. var geometry = geometries[index];
  24616. if (geometry.isReady()) {
  24617. serializeGeometry(geometry, serializationObject.geometries);
  24618. }
  24619. }
  24620. // Meshes
  24621. serializationObject.meshes = [];
  24622. for (index = 0; index < scene.meshes.length; index++) {
  24623. var abstractMesh = scene.meshes[index];
  24624. if (abstractMesh instanceof BABYLON.Mesh) {
  24625. var mesh = abstractMesh;
  24626. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24627. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24628. }
  24629. }
  24630. }
  24631. // Particles Systems
  24632. serializationObject.particleSystems = [];
  24633. for (index = 0; index < scene.particleSystems.length; index++) {
  24634. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  24635. }
  24636. // Lens flares
  24637. serializationObject.lensFlareSystems = [];
  24638. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  24639. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  24640. }
  24641. // Shadows
  24642. serializationObject.shadowGenerators = [];
  24643. for (index = 0; index < scene.lights.length; index++) {
  24644. light = scene.lights[index];
  24645. if (light.getShadowGenerator()) {
  24646. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  24647. }
  24648. }
  24649. return serializationObject;
  24650. };
  24651. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  24652. if (withParents === void 0) { withParents = false; }
  24653. if (withChildren === void 0) { withChildren = false; }
  24654. var serializationObject = {};
  24655. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  24656. if (withParents || withChildren) {
  24657. //deliberate for loop! not for each, appended should be processed as well.
  24658. for (var i = 0; i < toSerialize.length; ++i) {
  24659. if (withChildren) {
  24660. toSerialize[i].getDescendants().forEach(function (node) {
  24661. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  24662. toSerialize.push(node);
  24663. }
  24664. });
  24665. }
  24666. //make sure the array doesn't contain the object already
  24667. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  24668. toSerialize.push(toSerialize[i].parent);
  24669. }
  24670. }
  24671. }
  24672. toSerialize.forEach(function (mesh) {
  24673. finalizeSingleMesh(mesh, serializationObject);
  24674. });
  24675. return serializationObject;
  24676. };
  24677. return SceneSerializer;
  24678. })();
  24679. BABYLON.SceneSerializer = SceneSerializer;
  24680. })(BABYLON || (BABYLON = {}));
  24681. var BABYLON;
  24682. (function (BABYLON) {
  24683. // Unique ID when we import meshes from Babylon to CSG
  24684. var currentCSGMeshId = 0;
  24685. // # class Vertex
  24686. // Represents a vertex of a polygon. Use your own vertex class instead of this
  24687. // one to provide additional features like texture coordinates and vertex
  24688. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  24689. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  24690. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  24691. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  24692. // is not used anywhere else.
  24693. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  24694. var Vertex = (function () {
  24695. function Vertex(pos, normal, uv) {
  24696. this.pos = pos;
  24697. this.normal = normal;
  24698. this.uv = uv;
  24699. }
  24700. Vertex.prototype.clone = function () {
  24701. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  24702. };
  24703. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  24704. // orientation of a polygon is flipped.
  24705. Vertex.prototype.flip = function () {
  24706. this.normal = this.normal.scale(-1);
  24707. };
  24708. // Create a new vertex between this vertex and `other` by linearly
  24709. // interpolating all properties using a parameter of `t`. Subclasses should
  24710. // override this to interpolate additional properties.
  24711. Vertex.prototype.interpolate = function (other, t) {
  24712. 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));
  24713. };
  24714. return Vertex;
  24715. })();
  24716. // # class Plane
  24717. // Represents a plane in 3D space.
  24718. var Plane = (function () {
  24719. function Plane(normal, w) {
  24720. this.normal = normal;
  24721. this.w = w;
  24722. }
  24723. Plane.FromPoints = function (a, b, c) {
  24724. var v0 = c.subtract(a);
  24725. var v1 = b.subtract(a);
  24726. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  24727. return null;
  24728. }
  24729. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  24730. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  24731. };
  24732. Plane.prototype.clone = function () {
  24733. return new Plane(this.normal.clone(), this.w);
  24734. };
  24735. Plane.prototype.flip = function () {
  24736. this.normal.scaleInPlace(-1);
  24737. this.w = -this.w;
  24738. };
  24739. // Split `polygon` by this plane if needed, then put the polygon or polygon
  24740. // fragments in the appropriate lists. Coplanar polygons go into either
  24741. // `coplanarFront` or `coplanarBack` depending on their orientation with
  24742. // respect to this plane. Polygons in front or in back of this plane go into
  24743. // either `front` or `back`.
  24744. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  24745. var COPLANAR = 0;
  24746. var FRONT = 1;
  24747. var BACK = 2;
  24748. var SPANNING = 3;
  24749. // Classify each point as well as the entire polygon into one of the above
  24750. // four classes.
  24751. var polygonType = 0;
  24752. var types = [];
  24753. for (var i = 0; i < polygon.vertices.length; i++) {
  24754. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  24755. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  24756. polygonType |= type;
  24757. types.push(type);
  24758. }
  24759. // Put the polygon in the correct list, splitting it when necessary.
  24760. switch (polygonType) {
  24761. case COPLANAR:
  24762. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  24763. break;
  24764. case FRONT:
  24765. front.push(polygon);
  24766. break;
  24767. case BACK:
  24768. back.push(polygon);
  24769. break;
  24770. case SPANNING:
  24771. var f = [], b = [];
  24772. for (i = 0; i < polygon.vertices.length; i++) {
  24773. var j = (i + 1) % polygon.vertices.length;
  24774. var ti = types[i], tj = types[j];
  24775. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  24776. if (ti != BACK)
  24777. f.push(vi);
  24778. if (ti != FRONT)
  24779. b.push(ti != BACK ? vi.clone() : vi);
  24780. if ((ti | tj) == SPANNING) {
  24781. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  24782. var v = vi.interpolate(vj, t);
  24783. f.push(v);
  24784. b.push(v.clone());
  24785. }
  24786. }
  24787. if (f.length >= 3) {
  24788. var poly = new Polygon(f, polygon.shared);
  24789. if (poly.plane)
  24790. front.push(poly);
  24791. }
  24792. if (b.length >= 3) {
  24793. poly = new Polygon(b, polygon.shared);
  24794. if (poly.plane)
  24795. back.push(poly);
  24796. }
  24797. break;
  24798. }
  24799. };
  24800. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  24801. // point is on the plane.
  24802. Plane.EPSILON = 1e-5;
  24803. return Plane;
  24804. })();
  24805. // # class Polygon
  24806. // Represents a convex polygon. The vertices used to initialize a polygon must
  24807. // be coplanar and form a convex loop.
  24808. //
  24809. // Each convex polygon has a `shared` property, which is shared between all
  24810. // polygons that are clones of each other or were split from the same polygon.
  24811. // This can be used to define per-polygon properties (such as surface color).
  24812. var Polygon = (function () {
  24813. function Polygon(vertices, shared) {
  24814. this.vertices = vertices;
  24815. this.shared = shared;
  24816. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  24817. }
  24818. Polygon.prototype.clone = function () {
  24819. var vertices = this.vertices.map(function (v) { return v.clone(); });
  24820. return new Polygon(vertices, this.shared);
  24821. };
  24822. Polygon.prototype.flip = function () {
  24823. this.vertices.reverse().map(function (v) { v.flip(); });
  24824. this.plane.flip();
  24825. };
  24826. return Polygon;
  24827. })();
  24828. // # class Node
  24829. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  24830. // by picking a polygon to split along. That polygon (and all other coplanar
  24831. // polygons) are added directly to that node and the other polygons are added to
  24832. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  24833. // no distinction between internal and leaf nodes.
  24834. var Node = (function () {
  24835. function Node(polygons) {
  24836. this.plane = null;
  24837. this.front = null;
  24838. this.back = null;
  24839. this.polygons = [];
  24840. if (polygons) {
  24841. this.build(polygons);
  24842. }
  24843. }
  24844. Node.prototype.clone = function () {
  24845. var node = new Node();
  24846. node.plane = this.plane && this.plane.clone();
  24847. node.front = this.front && this.front.clone();
  24848. node.back = this.back && this.back.clone();
  24849. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24850. return node;
  24851. };
  24852. // Convert solid space to empty space and empty space to solid space.
  24853. Node.prototype.invert = function () {
  24854. for (var i = 0; i < this.polygons.length; i++) {
  24855. this.polygons[i].flip();
  24856. }
  24857. if (this.plane) {
  24858. this.plane.flip();
  24859. }
  24860. if (this.front) {
  24861. this.front.invert();
  24862. }
  24863. if (this.back) {
  24864. this.back.invert();
  24865. }
  24866. var temp = this.front;
  24867. this.front = this.back;
  24868. this.back = temp;
  24869. };
  24870. // Recursively remove all polygons in `polygons` that are inside this BSP
  24871. // tree.
  24872. Node.prototype.clipPolygons = function (polygons) {
  24873. if (!this.plane)
  24874. return polygons.slice();
  24875. var front = [], back = [];
  24876. for (var i = 0; i < polygons.length; i++) {
  24877. this.plane.splitPolygon(polygons[i], front, back, front, back);
  24878. }
  24879. if (this.front) {
  24880. front = this.front.clipPolygons(front);
  24881. }
  24882. if (this.back) {
  24883. back = this.back.clipPolygons(back);
  24884. }
  24885. else {
  24886. back = [];
  24887. }
  24888. return front.concat(back);
  24889. };
  24890. // Remove all polygons in this BSP tree that are inside the other BSP tree
  24891. // `bsp`.
  24892. Node.prototype.clipTo = function (bsp) {
  24893. this.polygons = bsp.clipPolygons(this.polygons);
  24894. if (this.front)
  24895. this.front.clipTo(bsp);
  24896. if (this.back)
  24897. this.back.clipTo(bsp);
  24898. };
  24899. // Return a list of all polygons in this BSP tree.
  24900. Node.prototype.allPolygons = function () {
  24901. var polygons = this.polygons.slice();
  24902. if (this.front)
  24903. polygons = polygons.concat(this.front.allPolygons());
  24904. if (this.back)
  24905. polygons = polygons.concat(this.back.allPolygons());
  24906. return polygons;
  24907. };
  24908. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  24909. // new polygons are filtered down to the bottom of the tree and become new
  24910. // nodes there. Each set of polygons is partitioned using the first polygon
  24911. // (no heuristic is used to pick a good split).
  24912. Node.prototype.build = function (polygons) {
  24913. if (!polygons.length)
  24914. return;
  24915. if (!this.plane)
  24916. this.plane = polygons[0].plane.clone();
  24917. var front = [], back = [];
  24918. for (var i = 0; i < polygons.length; i++) {
  24919. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  24920. }
  24921. if (front.length) {
  24922. if (!this.front)
  24923. this.front = new Node();
  24924. this.front.build(front);
  24925. }
  24926. if (back.length) {
  24927. if (!this.back)
  24928. this.back = new Node();
  24929. this.back.build(back);
  24930. }
  24931. };
  24932. return Node;
  24933. })();
  24934. var CSG = (function () {
  24935. function CSG() {
  24936. this.polygons = new Array();
  24937. }
  24938. // Convert BABYLON.Mesh to BABYLON.CSG
  24939. CSG.FromMesh = function (mesh) {
  24940. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  24941. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  24942. if (mesh instanceof BABYLON.Mesh) {
  24943. mesh.computeWorldMatrix(true);
  24944. matrix = mesh.getWorldMatrix();
  24945. meshPosition = mesh.position.clone();
  24946. meshRotation = mesh.rotation.clone();
  24947. if (mesh.rotationQuaternion) {
  24948. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  24949. }
  24950. meshScaling = mesh.scaling.clone();
  24951. }
  24952. else {
  24953. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  24954. }
  24955. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24956. var subMeshes = mesh.subMeshes;
  24957. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  24958. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  24959. vertices = [];
  24960. for (var j = 0; j < 3; j++) {
  24961. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  24962. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  24963. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  24964. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  24965. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  24966. vertex = new Vertex(position, normal, uv);
  24967. vertices.push(vertex);
  24968. }
  24969. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  24970. // To handle the case of degenerated triangle
  24971. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  24972. if (polygon.plane)
  24973. polygons.push(polygon);
  24974. }
  24975. }
  24976. var csg = CSG.FromPolygons(polygons);
  24977. csg.matrix = matrix;
  24978. csg.position = meshPosition;
  24979. csg.rotation = meshRotation;
  24980. csg.scaling = meshScaling;
  24981. csg.rotationQuaternion = meshRotationQuaternion;
  24982. currentCSGMeshId++;
  24983. return csg;
  24984. };
  24985. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  24986. CSG.FromPolygons = function (polygons) {
  24987. var csg = new CSG();
  24988. csg.polygons = polygons;
  24989. return csg;
  24990. };
  24991. CSG.prototype.clone = function () {
  24992. var csg = new CSG();
  24993. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  24994. csg.copyTransformAttributes(this);
  24995. return csg;
  24996. };
  24997. CSG.prototype.toPolygons = function () {
  24998. return this.polygons;
  24999. };
  25000. CSG.prototype.union = function (csg) {
  25001. var a = new Node(this.clone().polygons);
  25002. var b = new Node(csg.clone().polygons);
  25003. a.clipTo(b);
  25004. b.clipTo(a);
  25005. b.invert();
  25006. b.clipTo(a);
  25007. b.invert();
  25008. a.build(b.allPolygons());
  25009. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25010. };
  25011. CSG.prototype.unionInPlace = function (csg) {
  25012. var a = new Node(this.polygons);
  25013. var b = new Node(csg.polygons);
  25014. a.clipTo(b);
  25015. b.clipTo(a);
  25016. b.invert();
  25017. b.clipTo(a);
  25018. b.invert();
  25019. a.build(b.allPolygons());
  25020. this.polygons = a.allPolygons();
  25021. };
  25022. CSG.prototype.subtract = function (csg) {
  25023. var a = new Node(this.clone().polygons);
  25024. var b = new Node(csg.clone().polygons);
  25025. a.invert();
  25026. a.clipTo(b);
  25027. b.clipTo(a);
  25028. b.invert();
  25029. b.clipTo(a);
  25030. b.invert();
  25031. a.build(b.allPolygons());
  25032. a.invert();
  25033. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25034. };
  25035. CSG.prototype.subtractInPlace = function (csg) {
  25036. var a = new Node(this.polygons);
  25037. var b = new Node(csg.polygons);
  25038. a.invert();
  25039. a.clipTo(b);
  25040. b.clipTo(a);
  25041. b.invert();
  25042. b.clipTo(a);
  25043. b.invert();
  25044. a.build(b.allPolygons());
  25045. a.invert();
  25046. this.polygons = a.allPolygons();
  25047. };
  25048. CSG.prototype.intersect = function (csg) {
  25049. var a = new Node(this.clone().polygons);
  25050. var b = new Node(csg.clone().polygons);
  25051. a.invert();
  25052. b.clipTo(a);
  25053. b.invert();
  25054. a.clipTo(b);
  25055. b.clipTo(a);
  25056. a.build(b.allPolygons());
  25057. a.invert();
  25058. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25059. };
  25060. CSG.prototype.intersectInPlace = function (csg) {
  25061. var a = new Node(this.polygons);
  25062. var b = new Node(csg.polygons);
  25063. a.invert();
  25064. b.clipTo(a);
  25065. b.invert();
  25066. a.clipTo(b);
  25067. b.clipTo(a);
  25068. a.build(b.allPolygons());
  25069. a.invert();
  25070. this.polygons = a.allPolygons();
  25071. };
  25072. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25073. // not modified.
  25074. CSG.prototype.inverse = function () {
  25075. var csg = this.clone();
  25076. csg.inverseInPlace();
  25077. return csg;
  25078. };
  25079. CSG.prototype.inverseInPlace = function () {
  25080. this.polygons.map(function (p) { p.flip(); });
  25081. };
  25082. // This is used to keep meshes transformations so they can be restored
  25083. // when we build back a Babylon Mesh
  25084. // NB : All CSG operations are performed in world coordinates
  25085. CSG.prototype.copyTransformAttributes = function (csg) {
  25086. this.matrix = csg.matrix;
  25087. this.position = csg.position;
  25088. this.rotation = csg.rotation;
  25089. this.scaling = csg.scaling;
  25090. this.rotationQuaternion = csg.rotationQuaternion;
  25091. return this;
  25092. };
  25093. // Build Raw mesh from CSG
  25094. // Coordinates here are in world space
  25095. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25096. var matrix = this.matrix.clone();
  25097. matrix.invert();
  25098. 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;
  25099. if (keepSubMeshes) {
  25100. // Sort Polygons, since subMeshes are indices range
  25101. polygons.sort(function (a, b) {
  25102. if (a.shared.meshId === b.shared.meshId) {
  25103. return a.shared.subMeshId - b.shared.subMeshId;
  25104. }
  25105. else {
  25106. return a.shared.meshId - b.shared.meshId;
  25107. }
  25108. });
  25109. }
  25110. for (var i = 0, il = polygons.length; i < il; i++) {
  25111. polygon = polygons[i];
  25112. // Building SubMeshes
  25113. if (!subMesh_dict[polygon.shared.meshId]) {
  25114. subMesh_dict[polygon.shared.meshId] = {};
  25115. }
  25116. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25117. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25118. indexStart: +Infinity,
  25119. indexEnd: -Infinity,
  25120. materialIndex: polygon.shared.materialIndex
  25121. };
  25122. }
  25123. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25124. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25125. polygonIndices[0] = 0;
  25126. polygonIndices[1] = j - 1;
  25127. polygonIndices[2] = j;
  25128. for (var k = 0; k < 3; k++) {
  25129. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25130. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25131. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25132. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25133. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25134. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25135. // Check if 2 points can be merged
  25136. if (!(typeof vertex_idx !== 'undefined' &&
  25137. normals[vertex_idx * 3] === localNormal.x &&
  25138. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25139. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25140. uvs[vertex_idx * 2] === uv.x &&
  25141. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25142. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25143. uvs.push(uv.x, uv.y);
  25144. normals.push(normal.x, normal.y, normal.z);
  25145. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25146. }
  25147. indices.push(vertex_idx);
  25148. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25149. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25150. currentIndex++;
  25151. }
  25152. }
  25153. }
  25154. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25155. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25156. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25157. mesh.setIndices(indices);
  25158. if (keepSubMeshes) {
  25159. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25160. var materialIndexOffset = 0, materialMaxIndex;
  25161. mesh.subMeshes.length = 0;
  25162. for (var m in subMesh_dict) {
  25163. materialMaxIndex = -1;
  25164. for (var sm in subMesh_dict[m]) {
  25165. subMesh_obj = subMesh_dict[m][sm];
  25166. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25167. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25168. }
  25169. materialIndexOffset += ++materialMaxIndex;
  25170. }
  25171. }
  25172. return mesh;
  25173. };
  25174. // Build Mesh from CSG taking material and transforms into account
  25175. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25176. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25177. mesh.material = material;
  25178. mesh.position.copyFrom(this.position);
  25179. mesh.rotation.copyFrom(this.rotation);
  25180. if (this.rotationQuaternion) {
  25181. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25182. }
  25183. mesh.scaling.copyFrom(this.scaling);
  25184. mesh.computeWorldMatrix(true);
  25185. return mesh;
  25186. };
  25187. return CSG;
  25188. })();
  25189. BABYLON.CSG = CSG;
  25190. })(BABYLON || (BABYLON = {}));
  25191. var BABYLON;
  25192. (function (BABYLON) {
  25193. var VRDistortionCorrectionPostProcess = (function (_super) {
  25194. __extends(VRDistortionCorrectionPostProcess, _super);
  25195. //ANY
  25196. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25197. var _this = this;
  25198. _super.call(this, name, "vrDistortionCorrection", [
  25199. 'LensCenter',
  25200. 'Scale',
  25201. 'ScaleIn',
  25202. 'HmdWarpParam'
  25203. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25204. this._isRightEye = isRightEye;
  25205. this._distortionFactors = vrMetrics.distortionK;
  25206. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25207. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25208. this.onSizeChanged = function () {
  25209. _this.aspectRatio = _this.width * .5 / _this.height;
  25210. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25211. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25212. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25213. };
  25214. this.onApply = function (effect) {
  25215. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25216. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25217. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25218. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25219. };
  25220. }
  25221. return VRDistortionCorrectionPostProcess;
  25222. })(BABYLON.PostProcess);
  25223. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25224. })(BABYLON || (BABYLON = {}));
  25225. // Mainly based on these 2 articles :
  25226. // 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
  25227. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25228. var BABYLON;
  25229. (function (BABYLON) {
  25230. (function (JoystickAxis) {
  25231. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25232. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25233. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25234. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25235. var JoystickAxis = BABYLON.JoystickAxis;
  25236. var VirtualJoystick = (function () {
  25237. function VirtualJoystick(leftJoystick) {
  25238. var _this = this;
  25239. if (leftJoystick) {
  25240. this._leftJoystick = true;
  25241. }
  25242. else {
  25243. this._leftJoystick = false;
  25244. }
  25245. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25246. VirtualJoystick._globalJoystickIndex++;
  25247. // By default left & right arrow keys are moving the X
  25248. // and up & down keys are moving the Y
  25249. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25250. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25251. this.reverseLeftRight = false;
  25252. this.reverseUpDown = false;
  25253. // collections of pointers
  25254. this._touches = new BABYLON.SmartCollection();
  25255. this.deltaPosition = BABYLON.Vector3.Zero();
  25256. this._joystickSensibility = 25;
  25257. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25258. this._rotationSpeed = 25;
  25259. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25260. this._rotateOnAxisRelativeToMesh = false;
  25261. this._onResize = function (evt) {
  25262. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25263. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25264. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25265. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25266. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25267. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25268. };
  25269. // injecting a canvas element on top of the canvas 3D game
  25270. if (!VirtualJoystick.vjCanvas) {
  25271. window.addEventListener("resize", this._onResize, false);
  25272. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25273. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25274. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25275. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25276. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25277. VirtualJoystick.vjCanvas.style.width = "100%";
  25278. VirtualJoystick.vjCanvas.style.height = "100%";
  25279. VirtualJoystick.vjCanvas.style.position = "absolute";
  25280. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25281. VirtualJoystick.vjCanvas.style.top = "0px";
  25282. VirtualJoystick.vjCanvas.style.left = "0px";
  25283. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25284. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25285. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25286. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25287. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25288. document.body.appendChild(VirtualJoystick.vjCanvas);
  25289. }
  25290. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25291. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25292. this.pressed = false;
  25293. // default joystick color
  25294. this._joystickColor = "cyan";
  25295. this._joystickPointerID = -1;
  25296. // current joystick position
  25297. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25298. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25299. // origin joystick position
  25300. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25301. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25302. this._onPointerDownHandlerRef = function (evt) {
  25303. _this._onPointerDown(evt);
  25304. };
  25305. this._onPointerMoveHandlerRef = function (evt) {
  25306. _this._onPointerMove(evt);
  25307. };
  25308. this._onPointerOutHandlerRef = function (evt) {
  25309. _this._onPointerUp(evt);
  25310. };
  25311. this._onPointerUpHandlerRef = function (evt) {
  25312. _this._onPointerUp(evt);
  25313. };
  25314. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25315. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25316. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25317. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25318. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25319. evt.preventDefault(); // Disables system menu
  25320. }, false);
  25321. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25322. }
  25323. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25324. this._joystickSensibility = newJoystickSensibility;
  25325. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25326. };
  25327. VirtualJoystick.prototype._onPointerDown = function (e) {
  25328. var positionOnScreenCondition;
  25329. e.preventDefault();
  25330. if (this._leftJoystick === true) {
  25331. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25332. }
  25333. else {
  25334. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25335. }
  25336. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25337. // First contact will be dedicated to the virtual joystick
  25338. this._joystickPointerID = e.pointerId;
  25339. this._joystickPointerStartPos.x = e.clientX;
  25340. this._joystickPointerStartPos.y = e.clientY;
  25341. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25342. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25343. this._deltaJoystickVector.x = 0;
  25344. this._deltaJoystickVector.y = 0;
  25345. this.pressed = true;
  25346. this._touches.add(e.pointerId.toString(), e);
  25347. }
  25348. else {
  25349. // You can only trigger the action buttons with a joystick declared
  25350. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25351. this._action();
  25352. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25353. }
  25354. }
  25355. };
  25356. VirtualJoystick.prototype._onPointerMove = function (e) {
  25357. // If the current pointer is the one associated to the joystick (first touch contact)
  25358. if (this._joystickPointerID == e.pointerId) {
  25359. this._joystickPointerPos.x = e.clientX;
  25360. this._joystickPointerPos.y = e.clientY;
  25361. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25362. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25363. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25364. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25365. switch (this._axisTargetedByLeftAndRight) {
  25366. case JoystickAxis.X:
  25367. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25368. break;
  25369. case JoystickAxis.Y:
  25370. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25371. break;
  25372. case JoystickAxis.Z:
  25373. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25374. break;
  25375. }
  25376. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25377. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25378. switch (this._axisTargetedByUpAndDown) {
  25379. case JoystickAxis.X:
  25380. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25381. break;
  25382. case JoystickAxis.Y:
  25383. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25384. break;
  25385. case JoystickAxis.Z:
  25386. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25387. break;
  25388. }
  25389. }
  25390. else {
  25391. if (this._touches.item(e.pointerId.toString())) {
  25392. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25393. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25394. }
  25395. }
  25396. };
  25397. VirtualJoystick.prototype._onPointerUp = function (e) {
  25398. if (this._joystickPointerID == e.pointerId) {
  25399. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25400. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25401. this._joystickPointerID = -1;
  25402. this.pressed = false;
  25403. }
  25404. else {
  25405. var touch = this._touches.item(e.pointerId.toString());
  25406. if (touch) {
  25407. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25408. }
  25409. }
  25410. this._deltaJoystickVector.x = 0;
  25411. this._deltaJoystickVector.y = 0;
  25412. this._touches.remove(e.pointerId.toString());
  25413. };
  25414. /**
  25415. * Change the color of the virtual joystick
  25416. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25417. */
  25418. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25419. this._joystickColor = newColor;
  25420. };
  25421. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25422. this._action = action;
  25423. };
  25424. // Define which axis you'd like to control for left & right
  25425. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25426. switch (axis) {
  25427. case JoystickAxis.X:
  25428. case JoystickAxis.Y:
  25429. case JoystickAxis.Z:
  25430. this._axisTargetedByLeftAndRight = axis;
  25431. break;
  25432. default:
  25433. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25434. break;
  25435. }
  25436. };
  25437. // Define which axis you'd like to control for up & down
  25438. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  25439. switch (axis) {
  25440. case JoystickAxis.X:
  25441. case JoystickAxis.Y:
  25442. case JoystickAxis.Z:
  25443. this._axisTargetedByUpAndDown = axis;
  25444. break;
  25445. default:
  25446. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25447. break;
  25448. }
  25449. };
  25450. VirtualJoystick.prototype._clearCanvas = function () {
  25451. if (this._leftJoystick) {
  25452. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  25453. }
  25454. else {
  25455. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  25456. }
  25457. };
  25458. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  25459. var _this = this;
  25460. if (this.pressed) {
  25461. this._touches.forEach(function (touch) {
  25462. if (touch.pointerId === _this._joystickPointerID) {
  25463. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  25464. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  25465. VirtualJoystick.vjCanvasContext.beginPath();
  25466. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25467. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25468. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  25469. VirtualJoystick.vjCanvasContext.stroke();
  25470. VirtualJoystick.vjCanvasContext.closePath();
  25471. VirtualJoystick.vjCanvasContext.beginPath();
  25472. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25473. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25474. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  25475. VirtualJoystick.vjCanvasContext.stroke();
  25476. VirtualJoystick.vjCanvasContext.closePath();
  25477. VirtualJoystick.vjCanvasContext.beginPath();
  25478. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25479. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  25480. VirtualJoystick.vjCanvasContext.stroke();
  25481. VirtualJoystick.vjCanvasContext.closePath();
  25482. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  25483. }
  25484. else {
  25485. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25486. VirtualJoystick.vjCanvasContext.beginPath();
  25487. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  25488. VirtualJoystick.vjCanvasContext.beginPath();
  25489. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  25490. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25491. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  25492. VirtualJoystick.vjCanvasContext.stroke();
  25493. VirtualJoystick.vjCanvasContext.closePath();
  25494. touch.prevX = touch.x;
  25495. touch.prevY = touch.y;
  25496. }
  25497. ;
  25498. });
  25499. }
  25500. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25501. };
  25502. VirtualJoystick.prototype.releaseCanvas = function () {
  25503. if (VirtualJoystick.vjCanvas) {
  25504. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  25505. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  25506. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  25507. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  25508. window.removeEventListener("resize", this._onResize);
  25509. document.body.removeChild(VirtualJoystick.vjCanvas);
  25510. VirtualJoystick.vjCanvas = null;
  25511. }
  25512. };
  25513. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  25514. VirtualJoystick._globalJoystickIndex = 0;
  25515. return VirtualJoystick;
  25516. })();
  25517. BABYLON.VirtualJoystick = VirtualJoystick;
  25518. })(BABYLON || (BABYLON = {}));
  25519. var BABYLON;
  25520. (function (BABYLON) {
  25521. // We're mainly based on the logic defined into the FreeCamera code
  25522. var VirtualJoysticksCamera = (function (_super) {
  25523. __extends(VirtualJoysticksCamera, _super);
  25524. function VirtualJoysticksCamera(name, position, scene) {
  25525. _super.call(this, name, position, scene);
  25526. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  25527. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  25528. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  25529. this._leftjoystick.setJoystickSensibility(0.15);
  25530. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  25531. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  25532. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  25533. this._rightjoystick.reverseUpDown = true;
  25534. this._rightjoystick.setJoystickSensibility(0.05);
  25535. this._rightjoystick.setJoystickColor("yellow");
  25536. }
  25537. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  25538. return this._leftjoystick;
  25539. };
  25540. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  25541. return this._rightjoystick;
  25542. };
  25543. VirtualJoysticksCamera.prototype._checkInputs = function () {
  25544. var speed = this._computeLocalCameraSpeed() * 50;
  25545. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25546. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  25547. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25548. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  25549. if (!this._leftjoystick.pressed) {
  25550. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  25551. }
  25552. if (!this._rightjoystick.pressed) {
  25553. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  25554. }
  25555. _super.prototype._checkInputs.call(this);
  25556. };
  25557. VirtualJoysticksCamera.prototype.dispose = function () {
  25558. this._leftjoystick.releaseCanvas();
  25559. _super.prototype.dispose.call(this);
  25560. };
  25561. return VirtualJoysticksCamera;
  25562. })(BABYLON.FreeCamera);
  25563. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  25564. })(BABYLON || (BABYLON = {}));
  25565. var BABYLON;
  25566. (function (BABYLON) {
  25567. var ShaderMaterial = (function (_super) {
  25568. __extends(ShaderMaterial, _super);
  25569. function ShaderMaterial(name, scene, shaderPath, options) {
  25570. _super.call(this, name, scene);
  25571. this._textures = new Array();
  25572. this._floats = new Array();
  25573. this._floatsArrays = {};
  25574. this._colors3 = new Array();
  25575. this._colors4 = new Array();
  25576. this._vectors2 = new Array();
  25577. this._vectors3 = new Array();
  25578. this._vectors4 = new Array();
  25579. this._matrices = new Array();
  25580. this._matrices3x3 = new Array();
  25581. this._matrices2x2 = new Array();
  25582. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  25583. this._shaderPath = shaderPath;
  25584. options.needAlphaBlending = options.needAlphaBlending || false;
  25585. options.needAlphaTesting = options.needAlphaTesting || false;
  25586. options.attributes = options.attributes || ["position", "normal", "uv"];
  25587. options.uniforms = options.uniforms || ["worldViewProjection"];
  25588. options.samplers = options.samplers || [];
  25589. options.defines = options.defines || [];
  25590. this._options = options;
  25591. }
  25592. ShaderMaterial.prototype.needAlphaBlending = function () {
  25593. return this._options.needAlphaBlending;
  25594. };
  25595. ShaderMaterial.prototype.needAlphaTesting = function () {
  25596. return this._options.needAlphaTesting;
  25597. };
  25598. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  25599. if (this._options.uniforms.indexOf(uniformName) === -1) {
  25600. this._options.uniforms.push(uniformName);
  25601. }
  25602. };
  25603. ShaderMaterial.prototype.setTexture = function (name, texture) {
  25604. if (this._options.samplers.indexOf(name) === -1) {
  25605. this._options.samplers.push(name);
  25606. }
  25607. this._textures[name] = texture;
  25608. return this;
  25609. };
  25610. ShaderMaterial.prototype.setFloat = function (name, value) {
  25611. this._checkUniform(name);
  25612. this._floats[name] = value;
  25613. return this;
  25614. };
  25615. ShaderMaterial.prototype.setFloats = function (name, value) {
  25616. this._checkUniform(name);
  25617. this._floatsArrays[name] = value;
  25618. return this;
  25619. };
  25620. ShaderMaterial.prototype.setColor3 = function (name, value) {
  25621. this._checkUniform(name);
  25622. this._colors3[name] = value;
  25623. return this;
  25624. };
  25625. ShaderMaterial.prototype.setColor4 = function (name, value) {
  25626. this._checkUniform(name);
  25627. this._colors4[name] = value;
  25628. return this;
  25629. };
  25630. ShaderMaterial.prototype.setVector2 = function (name, value) {
  25631. this._checkUniform(name);
  25632. this._vectors2[name] = value;
  25633. return this;
  25634. };
  25635. ShaderMaterial.prototype.setVector3 = function (name, value) {
  25636. this._checkUniform(name);
  25637. this._vectors3[name] = value;
  25638. return this;
  25639. };
  25640. ShaderMaterial.prototype.setVector4 = function (name, value) {
  25641. this._checkUniform(name);
  25642. this._vectors4[name] = value;
  25643. return this;
  25644. };
  25645. ShaderMaterial.prototype.setMatrix = function (name, value) {
  25646. this._checkUniform(name);
  25647. this._matrices[name] = value;
  25648. return this;
  25649. };
  25650. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  25651. this._checkUniform(name);
  25652. this._matrices3x3[name] = value;
  25653. return this;
  25654. };
  25655. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  25656. this._checkUniform(name);
  25657. this._matrices2x2[name] = value;
  25658. return this;
  25659. };
  25660. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  25661. var scene = this.getScene();
  25662. var engine = scene.getEngine();
  25663. if (!this.checkReadyOnEveryCall) {
  25664. if (this._renderId === scene.getRenderId()) {
  25665. return true;
  25666. }
  25667. }
  25668. // Instances
  25669. var defines = [];
  25670. var fallbacks = new BABYLON.EffectFallbacks();
  25671. if (useInstances) {
  25672. defines.push("#define INSTANCES");
  25673. }
  25674. for (var index = 0; index < this._options.defines.length; index++) {
  25675. defines.push(this._options.defines[index]);
  25676. }
  25677. // Bones
  25678. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25679. defines.push("#define BONES");
  25680. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25681. defines.push("#define BONES4");
  25682. fallbacks.addFallback(0, "BONES4");
  25683. }
  25684. // Alpha test
  25685. if (engine.getAlphaTesting()) {
  25686. defines.push("#define ALPHATEST");
  25687. }
  25688. var previousEffect = this._effect;
  25689. var join = defines.join("\n");
  25690. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  25691. if (!this._effect.isReady()) {
  25692. return false;
  25693. }
  25694. if (previousEffect !== this._effect) {
  25695. scene.resetCachedMaterial();
  25696. }
  25697. this._renderId = scene.getRenderId();
  25698. return true;
  25699. };
  25700. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25701. var scene = this.getScene();
  25702. if (this._options.uniforms.indexOf("world") !== -1) {
  25703. this._effect.setMatrix("world", world);
  25704. }
  25705. if (this._options.uniforms.indexOf("worldView") !== -1) {
  25706. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  25707. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  25708. }
  25709. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  25710. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  25711. }
  25712. };
  25713. ShaderMaterial.prototype.bind = function (world, mesh) {
  25714. // Std values
  25715. this.bindOnlyWorldMatrix(world);
  25716. if (this.getScene().getCachedMaterial() !== this) {
  25717. if (this._options.uniforms.indexOf("view") !== -1) {
  25718. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  25719. }
  25720. if (this._options.uniforms.indexOf("projection") !== -1) {
  25721. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  25722. }
  25723. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  25724. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25725. }
  25726. // Bones
  25727. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25728. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25729. }
  25730. // Texture
  25731. for (var name in this._textures) {
  25732. this._effect.setTexture(name, this._textures[name]);
  25733. }
  25734. // Float
  25735. for (name in this._floats) {
  25736. this._effect.setFloat(name, this._floats[name]);
  25737. }
  25738. // Float s
  25739. for (name in this._floatsArrays) {
  25740. this._effect.setArray(name, this._floatsArrays[name]);
  25741. }
  25742. // Color3
  25743. for (name in this._colors3) {
  25744. this._effect.setColor3(name, this._colors3[name]);
  25745. }
  25746. // Color4
  25747. for (name in this._colors4) {
  25748. var color = this._colors4[name];
  25749. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25750. }
  25751. // Vector2
  25752. for (name in this._vectors2) {
  25753. this._effect.setVector2(name, this._vectors2[name]);
  25754. }
  25755. // Vector3
  25756. for (name in this._vectors3) {
  25757. this._effect.setVector3(name, this._vectors3[name]);
  25758. }
  25759. // Vector4
  25760. for (name in this._vectors4) {
  25761. this._effect.setVector4(name, this._vectors4[name]);
  25762. }
  25763. // Matrix
  25764. for (name in this._matrices) {
  25765. this._effect.setMatrix(name, this._matrices[name]);
  25766. }
  25767. // Matrix 3x3
  25768. for (name in this._matrices3x3) {
  25769. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  25770. }
  25771. // Matrix 2x2
  25772. for (name in this._matrices2x2) {
  25773. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  25774. }
  25775. }
  25776. _super.prototype.bind.call(this, world, mesh);
  25777. };
  25778. ShaderMaterial.prototype.clone = function (name) {
  25779. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  25780. return newShaderMaterial;
  25781. };
  25782. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  25783. for (var name in this._textures) {
  25784. this._textures[name].dispose();
  25785. }
  25786. this._textures = [];
  25787. _super.prototype.dispose.call(this, forceDisposeEffect);
  25788. };
  25789. return ShaderMaterial;
  25790. })(BABYLON.Material);
  25791. BABYLON.ShaderMaterial = ShaderMaterial;
  25792. })(BABYLON || (BABYLON = {}));
  25793. var BABYLON;
  25794. (function (BABYLON) {
  25795. var VertexData = (function () {
  25796. function VertexData() {
  25797. }
  25798. VertexData.prototype.set = function (data, kind) {
  25799. switch (kind) {
  25800. case BABYLON.VertexBuffer.PositionKind:
  25801. this.positions = data;
  25802. break;
  25803. case BABYLON.VertexBuffer.NormalKind:
  25804. this.normals = data;
  25805. break;
  25806. case BABYLON.VertexBuffer.UVKind:
  25807. this.uvs = data;
  25808. break;
  25809. case BABYLON.VertexBuffer.UV2Kind:
  25810. this.uvs2 = data;
  25811. break;
  25812. case BABYLON.VertexBuffer.UV3Kind:
  25813. this.uvs3 = data;
  25814. break;
  25815. case BABYLON.VertexBuffer.UV4Kind:
  25816. this.uvs4 = data;
  25817. break;
  25818. case BABYLON.VertexBuffer.UV5Kind:
  25819. this.uvs5 = data;
  25820. break;
  25821. case BABYLON.VertexBuffer.UV6Kind:
  25822. this.uvs6 = data;
  25823. break;
  25824. case BABYLON.VertexBuffer.ColorKind:
  25825. this.colors = data;
  25826. break;
  25827. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25828. this.matricesIndices = data;
  25829. break;
  25830. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25831. this.matricesWeights = data;
  25832. break;
  25833. }
  25834. };
  25835. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25836. this._applyTo(mesh, updatable);
  25837. };
  25838. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25839. this._applyTo(geometry, updatable);
  25840. };
  25841. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25842. this._update(mesh);
  25843. };
  25844. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25845. this._update(geometry);
  25846. };
  25847. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25848. if (this.positions) {
  25849. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25850. }
  25851. if (this.normals) {
  25852. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25853. }
  25854. if (this.uvs) {
  25855. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25856. }
  25857. if (this.uvs2) {
  25858. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25859. }
  25860. if (this.uvs3) {
  25861. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25862. }
  25863. if (this.uvs4) {
  25864. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25865. }
  25866. if (this.uvs5) {
  25867. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25868. }
  25869. if (this.uvs6) {
  25870. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25871. }
  25872. if (this.colors) {
  25873. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25874. }
  25875. if (this.matricesIndices) {
  25876. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25877. }
  25878. if (this.matricesWeights) {
  25879. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25880. }
  25881. if (this.indices) {
  25882. meshOrGeometry.setIndices(this.indices);
  25883. }
  25884. };
  25885. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25886. if (this.positions) {
  25887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25888. }
  25889. if (this.normals) {
  25890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25891. }
  25892. if (this.uvs) {
  25893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25894. }
  25895. if (this.uvs2) {
  25896. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25897. }
  25898. if (this.uvs3) {
  25899. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25900. }
  25901. if (this.uvs4) {
  25902. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25903. }
  25904. if (this.uvs5) {
  25905. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25906. }
  25907. if (this.uvs6) {
  25908. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25909. }
  25910. if (this.colors) {
  25911. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25912. }
  25913. if (this.matricesIndices) {
  25914. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25915. }
  25916. if (this.matricesWeights) {
  25917. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25918. }
  25919. if (this.indices) {
  25920. meshOrGeometry.setIndices(this.indices);
  25921. }
  25922. };
  25923. VertexData.prototype.transform = function (matrix) {
  25924. var transformed = BABYLON.Vector3.Zero();
  25925. var index;
  25926. if (this.positions) {
  25927. var position = BABYLON.Vector3.Zero();
  25928. for (index = 0; index < this.positions.length; index += 3) {
  25929. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25930. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25931. this.positions[index] = transformed.x;
  25932. this.positions[index + 1] = transformed.y;
  25933. this.positions[index + 2] = transformed.z;
  25934. }
  25935. }
  25936. if (this.normals) {
  25937. var normal = BABYLON.Vector3.Zero();
  25938. for (index = 0; index < this.normals.length; index += 3) {
  25939. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25940. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25941. this.normals[index] = transformed.x;
  25942. this.normals[index + 1] = transformed.y;
  25943. this.normals[index + 2] = transformed.z;
  25944. }
  25945. }
  25946. };
  25947. VertexData.prototype.merge = function (other) {
  25948. var index;
  25949. if (other.indices) {
  25950. if (!this.indices) {
  25951. this.indices = [];
  25952. }
  25953. var offset = this.positions ? this.positions.length / 3 : 0;
  25954. for (index = 0; index < other.indices.length; index++) {
  25955. this.indices.push(other.indices[index] + offset);
  25956. }
  25957. }
  25958. if (other.positions) {
  25959. if (!this.positions) {
  25960. this.positions = [];
  25961. }
  25962. for (index = 0; index < other.positions.length; index++) {
  25963. this.positions.push(other.positions[index]);
  25964. }
  25965. }
  25966. if (other.normals) {
  25967. if (!this.normals) {
  25968. this.normals = [];
  25969. }
  25970. for (index = 0; index < other.normals.length; index++) {
  25971. this.normals.push(other.normals[index]);
  25972. }
  25973. }
  25974. if (other.uvs) {
  25975. if (!this.uvs) {
  25976. this.uvs = [];
  25977. }
  25978. for (index = 0; index < other.uvs.length; index++) {
  25979. this.uvs.push(other.uvs[index]);
  25980. }
  25981. }
  25982. if (other.uvs2) {
  25983. if (!this.uvs2) {
  25984. this.uvs2 = [];
  25985. }
  25986. for (index = 0; index < other.uvs2.length; index++) {
  25987. this.uvs2.push(other.uvs2[index]);
  25988. }
  25989. }
  25990. if (other.uvs3) {
  25991. if (!this.uvs3) {
  25992. this.uvs3 = [];
  25993. }
  25994. for (index = 0; index < other.uvs3.length; index++) {
  25995. this.uvs3.push(other.uvs3[index]);
  25996. }
  25997. }
  25998. if (other.uvs4) {
  25999. if (!this.uvs4) {
  26000. this.uvs4 = [];
  26001. }
  26002. for (index = 0; index < other.uvs4.length; index++) {
  26003. this.uvs4.push(other.uvs4[index]);
  26004. }
  26005. }
  26006. if (other.uvs5) {
  26007. if (!this.uvs5) {
  26008. this.uvs5 = [];
  26009. }
  26010. for (index = 0; index < other.uvs5.length; index++) {
  26011. this.uvs5.push(other.uvs5[index]);
  26012. }
  26013. }
  26014. if (other.uvs6) {
  26015. if (!this.uvs6) {
  26016. this.uvs6 = [];
  26017. }
  26018. for (index = 0; index < other.uvs6.length; index++) {
  26019. this.uvs6.push(other.uvs6[index]);
  26020. }
  26021. }
  26022. if (other.matricesIndices) {
  26023. if (!this.matricesIndices) {
  26024. this.matricesIndices = [];
  26025. }
  26026. for (index = 0; index < other.matricesIndices.length; index++) {
  26027. this.matricesIndices.push(other.matricesIndices[index]);
  26028. }
  26029. }
  26030. if (other.matricesWeights) {
  26031. if (!this.matricesWeights) {
  26032. this.matricesWeights = [];
  26033. }
  26034. for (index = 0; index < other.matricesWeights.length; index++) {
  26035. this.matricesWeights.push(other.matricesWeights[index]);
  26036. }
  26037. }
  26038. if (other.colors) {
  26039. if (!this.colors) {
  26040. this.colors = [];
  26041. }
  26042. for (index = 0; index < other.colors.length; index++) {
  26043. this.colors.push(other.colors[index]);
  26044. }
  26045. }
  26046. };
  26047. // Statics
  26048. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26049. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26050. };
  26051. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26052. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26053. };
  26054. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26055. var result = new VertexData();
  26056. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26057. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26058. }
  26059. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26060. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26061. }
  26062. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26063. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26064. }
  26065. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26066. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26067. }
  26068. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26069. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26070. }
  26071. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26072. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26073. }
  26074. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26075. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26076. }
  26077. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26078. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26079. }
  26080. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26081. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26082. }
  26083. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26084. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26085. }
  26086. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26087. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26088. }
  26089. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26090. return result;
  26091. };
  26092. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  26093. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26094. closeArray = closeArray || false;
  26095. closePath = closePath || false;
  26096. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26097. offset = offset || defaultOffset;
  26098. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26099. var positions = [];
  26100. var indices = [];
  26101. var normals = [];
  26102. var uvs = [];
  26103. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26104. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26105. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26106. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26107. var minlg; // minimal length among all paths from pathArray
  26108. var lg = []; // array of path lengths : nb of vertex per path
  26109. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26110. var p; // path iterator
  26111. var i; // point iterator
  26112. var j; // point iterator
  26113. // if single path in pathArray
  26114. if (pathArray.length < 2) {
  26115. var ar1 = [];
  26116. var ar2 = [];
  26117. for (i = 0; i < pathArray[0].length - offset; i++) {
  26118. ar1.push(pathArray[0][i]);
  26119. ar2.push(pathArray[0][i + offset]);
  26120. }
  26121. pathArray = [ar1, ar2];
  26122. }
  26123. // positions and horizontal distances (u)
  26124. var idc = 0;
  26125. var closePathCorr = (closePath) ? 1 : 0;
  26126. var path;
  26127. var l;
  26128. minlg = pathArray[0].length;
  26129. var vectlg;
  26130. var dist;
  26131. for (p = 0; p < pathArray.length; p++) {
  26132. uTotalDistance[p] = 0;
  26133. us[p] = [0];
  26134. path = pathArray[p];
  26135. l = path.length;
  26136. minlg = (minlg < l) ? minlg : l;
  26137. j = 0;
  26138. while (j < l) {
  26139. positions.push(path[j].x, path[j].y, path[j].z);
  26140. if (j > 0) {
  26141. vectlg = path[j].subtract(path[j - 1]).length();
  26142. dist = vectlg + uTotalDistance[p];
  26143. us[p].push(dist);
  26144. uTotalDistance[p] = dist;
  26145. }
  26146. j++;
  26147. }
  26148. if (closePath) {
  26149. j--;
  26150. positions.push(path[0].x, path[0].y, path[0].z);
  26151. vectlg = path[j].subtract(path[0]).length();
  26152. dist = vectlg + uTotalDistance[p];
  26153. us[p].push(dist);
  26154. uTotalDistance[p] = dist;
  26155. }
  26156. lg[p] = l + closePathCorr;
  26157. idx[p] = idc;
  26158. idc += (l + closePathCorr);
  26159. }
  26160. // vertical distances (v)
  26161. var path1;
  26162. var path2;
  26163. var vertex1;
  26164. var vertex2;
  26165. for (i = 0; i < minlg + closePathCorr; i++) {
  26166. vTotalDistance[i] = 0;
  26167. vs[i] = [0];
  26168. for (p = 0; p < pathArray.length - 1; p++) {
  26169. path1 = pathArray[p];
  26170. path2 = pathArray[p + 1];
  26171. if (i === minlg) {
  26172. vertex1 = path1[0];
  26173. vertex2 = path2[0];
  26174. }
  26175. else {
  26176. vertex1 = path1[i];
  26177. vertex2 = path2[i];
  26178. }
  26179. vectlg = vertex2.subtract(vertex1).length();
  26180. dist = vectlg + vTotalDistance[i];
  26181. vs[i].push(dist);
  26182. vTotalDistance[i] = dist;
  26183. }
  26184. if (closeArray) {
  26185. path1 = pathArray[p];
  26186. path2 = pathArray[0];
  26187. vectlg = path2[i].subtract(path1[i]).length();
  26188. dist = vectlg + vTotalDistance[i];
  26189. vTotalDistance[i] = dist;
  26190. }
  26191. }
  26192. // uvs
  26193. var u;
  26194. var v;
  26195. for (p = 0; p < pathArray.length; p++) {
  26196. for (i = 0; i < minlg + closePathCorr; i++) {
  26197. u = us[p][i] / uTotalDistance[p];
  26198. v = vs[i][p] / vTotalDistance[i];
  26199. uvs.push(u, v);
  26200. }
  26201. }
  26202. // indices
  26203. p = 0; // path index
  26204. var pi = 0; // positions array index
  26205. var l1 = lg[p] - 1; // path1 length
  26206. var l2 = lg[p + 1] - 1; // path2 length
  26207. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26208. var shft = idx[1] - idx[0]; // shift
  26209. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26210. while (pi <= min && p < path1nb) {
  26211. // 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
  26212. indices.push(pi, pi + shft, pi + 1);
  26213. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26214. pi += 1;
  26215. if (pi === min) {
  26216. p++;
  26217. if (p === lg.length - 1) {
  26218. shft = idx[0] - idx[p];
  26219. l1 = lg[p] - 1;
  26220. l2 = lg[0] - 1;
  26221. }
  26222. else {
  26223. shft = idx[p + 1] - idx[p];
  26224. l1 = lg[p] - 1;
  26225. l2 = lg[p + 1] - 1;
  26226. }
  26227. pi = idx[p];
  26228. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26229. }
  26230. }
  26231. // normals
  26232. VertexData.ComputeNormals(positions, indices, normals);
  26233. if (closePath) {
  26234. var indexFirst = 0;
  26235. var indexLast = 0;
  26236. for (p = 0; p < pathArray.length; p++) {
  26237. indexFirst = idx[p] * 3;
  26238. if (p + 1 < pathArray.length) {
  26239. indexLast = (idx[p + 1] - 1) * 3;
  26240. }
  26241. else {
  26242. indexLast = normals.length - 3;
  26243. }
  26244. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26245. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26246. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26247. normals[indexLast] = normals[indexFirst];
  26248. normals[indexLast + 1] = normals[indexFirst + 1];
  26249. normals[indexLast + 2] = normals[indexFirst + 2];
  26250. }
  26251. }
  26252. // sides
  26253. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26254. // Result
  26255. var vertexData = new VertexData();
  26256. vertexData.indices = indices;
  26257. vertexData.positions = positions;
  26258. vertexData.normals = normals;
  26259. vertexData.uvs = uvs;
  26260. if (closePath) {
  26261. vertexData._idx = idx;
  26262. }
  26263. return vertexData;
  26264. };
  26265. VertexData.CreateBox = function (options, sideOrientation) {
  26266. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26267. var normalsSource = [
  26268. new BABYLON.Vector3(0, 0, 1),
  26269. new BABYLON.Vector3(0, 0, -1),
  26270. new BABYLON.Vector3(1, 0, 0),
  26271. new BABYLON.Vector3(-1, 0, 0),
  26272. new BABYLON.Vector3(0, 1, 0),
  26273. new BABYLON.Vector3(0, -1, 0)
  26274. ];
  26275. var indices = [];
  26276. var positions = [];
  26277. var normals = [];
  26278. var uvs = [];
  26279. var width = 1;
  26280. var height = 1;
  26281. var depth = 1;
  26282. if (options.width !== undefined) {
  26283. width = options.width || 1;
  26284. height = options.height || 1;
  26285. depth = options.depth || 1;
  26286. }
  26287. else {
  26288. width = options || 1;
  26289. height = options || 1;
  26290. depth = options || 1;
  26291. }
  26292. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26293. // Create each face in turn.
  26294. for (var index = 0; index < normalsSource.length; index++) {
  26295. var normal = normalsSource[index];
  26296. // Get two vectors perpendicular to the face normal and to each other.
  26297. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26298. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26299. // Six indices (two triangles) per face.
  26300. var verticesLength = positions.length / 3;
  26301. indices.push(verticesLength);
  26302. indices.push(verticesLength + 1);
  26303. indices.push(verticesLength + 2);
  26304. indices.push(verticesLength);
  26305. indices.push(verticesLength + 2);
  26306. indices.push(verticesLength + 3);
  26307. // Four vertices per face.
  26308. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26309. positions.push(vertex.x, vertex.y, vertex.z);
  26310. normals.push(normal.x, normal.y, normal.z);
  26311. uvs.push(1.0, 1.0);
  26312. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26313. positions.push(vertex.x, vertex.y, vertex.z);
  26314. normals.push(normal.x, normal.y, normal.z);
  26315. uvs.push(0.0, 1.0);
  26316. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26317. positions.push(vertex.x, vertex.y, vertex.z);
  26318. normals.push(normal.x, normal.y, normal.z);
  26319. uvs.push(0.0, 0.0);
  26320. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26321. positions.push(vertex.x, vertex.y, vertex.z);
  26322. normals.push(normal.x, normal.y, normal.z);
  26323. uvs.push(1.0, 0.0);
  26324. }
  26325. // sides
  26326. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26327. // Result
  26328. var vertexData = new VertexData();
  26329. vertexData.indices = indices;
  26330. vertexData.positions = positions;
  26331. vertexData.normals = normals;
  26332. vertexData.uvs = uvs;
  26333. return vertexData;
  26334. };
  26335. VertexData.CreateSphere = function (options, diameter, sideOrientation) {
  26336. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26337. var segments;
  26338. var diameterX;
  26339. var diameterY;
  26340. var diameterZ;
  26341. if (options.segments) {
  26342. segments = options.segments || 32;
  26343. diameterX = options.diameterX || 1;
  26344. diameterY = options.diameterY || 1;
  26345. diameterZ = options.diameterZ || 1;
  26346. }
  26347. else {
  26348. segments = options || 32;
  26349. diameterX = diameter || 1;
  26350. diameterY = diameterX;
  26351. diameterZ = diameterX;
  26352. }
  26353. sideOrientation = sideOrientation || options.sideOrientation;
  26354. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26355. var totalZRotationSteps = 2 + segments;
  26356. var totalYRotationSteps = 2 * totalZRotationSteps;
  26357. var indices = [];
  26358. var positions = [];
  26359. var normals = [];
  26360. var uvs = [];
  26361. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26362. var normalizedZ = zRotationStep / totalZRotationSteps;
  26363. var angleZ = (normalizedZ * Math.PI);
  26364. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26365. var normalizedY = yRotationStep / totalYRotationSteps;
  26366. var angleY = normalizedY * Math.PI * 2;
  26367. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26368. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26369. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26370. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26371. var vertex = complete.multiply(radius);
  26372. var normal = BABYLON.Vector3.Normalize(vertex);
  26373. positions.push(vertex.x, vertex.y, vertex.z);
  26374. normals.push(normal.x, normal.y, normal.z);
  26375. uvs.push(normalizedZ, normalizedY);
  26376. }
  26377. if (zRotationStep > 0) {
  26378. var verticesCount = positions.length / 3;
  26379. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26380. indices.push((firstIndex));
  26381. indices.push((firstIndex + 1));
  26382. indices.push(firstIndex + totalYRotationSteps + 1);
  26383. indices.push((firstIndex + totalYRotationSteps + 1));
  26384. indices.push((firstIndex + 1));
  26385. indices.push((firstIndex + totalYRotationSteps + 2));
  26386. }
  26387. }
  26388. }
  26389. // Sides
  26390. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26391. // Result
  26392. var vertexData = new VertexData();
  26393. vertexData.indices = indices;
  26394. vertexData.positions = positions;
  26395. vertexData.normals = normals;
  26396. vertexData.uvs = uvs;
  26397. return vertexData;
  26398. };
  26399. // Cylinder and cone (made using ribbons)
  26400. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  26401. if (subdivisions === void 0) { subdivisions = 1; }
  26402. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26403. var indices = [];
  26404. var positions = [];
  26405. var normals = [];
  26406. var uvs = [];
  26407. var angle_step = Math.PI * 2 / tessellation;
  26408. var angle;
  26409. var h;
  26410. var radius;
  26411. var tan = (diameterBottom - diameterTop) / 2 / height;
  26412. var ringVertex = BABYLON.Vector3.Zero();
  26413. var ringNormal = BABYLON.Vector3.Zero();
  26414. // positions, normals, uvs
  26415. var i;
  26416. var j;
  26417. for (i = 0; i <= subdivisions; i++) {
  26418. h = i / subdivisions;
  26419. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  26420. for (j = 0; j <= tessellation; j++) {
  26421. angle = j * angle_step;
  26422. ringVertex.x = Math.cos(-angle) * radius;
  26423. ringVertex.y = -height / 2 + h * height;
  26424. ringVertex.z = Math.sin(-angle) * radius;
  26425. if (diameterTop === 0 && i === subdivisions) {
  26426. // if no top cap, reuse former normals
  26427. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  26428. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  26429. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  26430. }
  26431. else {
  26432. ringNormal.x = ringVertex.x;
  26433. ringNormal.z = ringVertex.z;
  26434. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  26435. ringNormal.normalize();
  26436. }
  26437. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  26438. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  26439. uvs.push(j / tessellation, 1 - h);
  26440. }
  26441. }
  26442. // indices
  26443. for (i = 0; i < subdivisions; i++) {
  26444. for (j = 0; j < tessellation; j++) {
  26445. var i0 = i * (tessellation + 1) + j;
  26446. var i1 = (i + 1) * (tessellation + 1) + j;
  26447. var i2 = i * (tessellation + 1) + (j + 1);
  26448. var i3 = (i + 1) * (tessellation + 1) + (j + 1);
  26449. indices.push(i0, i1, i2);
  26450. indices.push(i3, i2, i1);
  26451. }
  26452. }
  26453. // Caps
  26454. var createCylinderCap = function (isTop) {
  26455. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26456. if (radius === 0) {
  26457. return;
  26458. }
  26459. var vbase = positions.length / 3;
  26460. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  26461. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26462. // Cap positions, normals & uvs
  26463. var angle;
  26464. var circleVector;
  26465. var i;
  26466. for (i = 0; i < tessellation; i++) {
  26467. angle = Math.PI * 2 * i / tessellation;
  26468. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26469. var position = circleVector.scale(radius).add(offset);
  26470. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  26471. positions.push(position.x, position.y, position.z);
  26472. normals.push(0, isTop ? 1 : -1, 0);
  26473. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26474. }
  26475. // Cap indices
  26476. for (i = 0; i < tessellation - 2; i++) {
  26477. if (!isTop) {
  26478. indices.push(vbase);
  26479. indices.push(vbase + (i + 1) % tessellation);
  26480. indices.push(vbase + (i + 2) % tessellation);
  26481. }
  26482. else {
  26483. indices.push(vbase);
  26484. indices.push(vbase + (i + 2) % tessellation);
  26485. indices.push(vbase + (i + 1) % tessellation);
  26486. }
  26487. }
  26488. };
  26489. // add caps to geometry
  26490. createCylinderCap(true);
  26491. createCylinderCap(false);
  26492. // Sides
  26493. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26494. var vertexData = new VertexData();
  26495. vertexData.indices = indices;
  26496. vertexData.positions = positions;
  26497. vertexData.normals = normals;
  26498. vertexData.uvs = uvs;
  26499. return vertexData;
  26500. };
  26501. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  26502. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26503. var indices = [];
  26504. var positions = [];
  26505. var normals = [];
  26506. var uvs = [];
  26507. diameter = diameter || 1;
  26508. thickness = thickness || 0.5;
  26509. tessellation = tessellation || 16;
  26510. var stride = tessellation + 1;
  26511. for (var i = 0; i <= tessellation; i++) {
  26512. var u = i / tessellation;
  26513. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26514. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26515. for (var j = 0; j <= tessellation; j++) {
  26516. var v = 1 - j / tessellation;
  26517. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26518. var dx = Math.cos(innerAngle);
  26519. var dy = Math.sin(innerAngle);
  26520. // Create a vertex.
  26521. var normal = new BABYLON.Vector3(dx, dy, 0);
  26522. var position = normal.scale(thickness / 2);
  26523. var textureCoordinate = new BABYLON.Vector2(u, v);
  26524. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26525. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26526. positions.push(position.x, position.y, position.z);
  26527. normals.push(normal.x, normal.y, normal.z);
  26528. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26529. // And create indices for two triangles.
  26530. var nextI = (i + 1) % stride;
  26531. var nextJ = (j + 1) % stride;
  26532. indices.push(i * stride + j);
  26533. indices.push(i * stride + nextJ);
  26534. indices.push(nextI * stride + j);
  26535. indices.push(i * stride + nextJ);
  26536. indices.push(nextI * stride + nextJ);
  26537. indices.push(nextI * stride + j);
  26538. }
  26539. }
  26540. // Sides
  26541. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26542. // Result
  26543. var vertexData = new VertexData();
  26544. vertexData.indices = indices;
  26545. vertexData.positions = positions;
  26546. vertexData.normals = normals;
  26547. vertexData.uvs = uvs;
  26548. return vertexData;
  26549. };
  26550. VertexData.CreateLines = function (points) {
  26551. var indices = [];
  26552. var positions = [];
  26553. for (var index = 0; index < points.length; index++) {
  26554. positions.push(points[index].x, points[index].y, points[index].z);
  26555. if (index > 0) {
  26556. indices.push(index - 1);
  26557. indices.push(index);
  26558. }
  26559. }
  26560. // Result
  26561. var vertexData = new VertexData();
  26562. vertexData.indices = indices;
  26563. vertexData.positions = positions;
  26564. return vertexData;
  26565. };
  26566. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  26567. dashSize = dashSize || 3;
  26568. gapSize = gapSize || 1;
  26569. dashNb = dashNb || 200;
  26570. var positions = new Array();
  26571. var indices = new Array();
  26572. var curvect = BABYLON.Vector3.Zero();
  26573. var lg = 0;
  26574. var nb = 0;
  26575. var shft = 0;
  26576. var dashshft = 0;
  26577. var curshft = 0;
  26578. var idx = 0;
  26579. var i = 0;
  26580. for (i = 0; i < points.length - 1; i++) {
  26581. points[i + 1].subtractToRef(points[i], curvect);
  26582. lg += curvect.length();
  26583. }
  26584. shft = lg / dashNb;
  26585. dashshft = dashSize * shft / (dashSize + gapSize);
  26586. for (i = 0; i < points.length - 1; i++) {
  26587. points[i + 1].subtractToRef(points[i], curvect);
  26588. nb = Math.floor(curvect.length() / shft);
  26589. curvect.normalize();
  26590. for (var j = 0; j < nb; j++) {
  26591. curshft = shft * j;
  26592. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26593. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26594. indices.push(idx, idx + 1);
  26595. idx += 2;
  26596. }
  26597. }
  26598. // Result
  26599. var vertexData = new VertexData();
  26600. vertexData.positions = positions;
  26601. vertexData.indices = indices;
  26602. return vertexData;
  26603. };
  26604. VertexData.CreateGround = function (width, height, subdivisions) {
  26605. var indices = [];
  26606. var positions = [];
  26607. var normals = [];
  26608. var uvs = [];
  26609. var row, col;
  26610. width = width || 1;
  26611. height = height || 1;
  26612. subdivisions = subdivisions || 1;
  26613. for (row = 0; row <= subdivisions; row++) {
  26614. for (col = 0; col <= subdivisions; col++) {
  26615. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26616. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26617. positions.push(position.x, position.y, position.z);
  26618. normals.push(normal.x, normal.y, normal.z);
  26619. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26620. }
  26621. }
  26622. for (row = 0; row < subdivisions; row++) {
  26623. for (col = 0; col < subdivisions; col++) {
  26624. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26625. indices.push(col + 1 + row * (subdivisions + 1));
  26626. indices.push(col + row * (subdivisions + 1));
  26627. indices.push(col + (row + 1) * (subdivisions + 1));
  26628. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26629. indices.push(col + row * (subdivisions + 1));
  26630. }
  26631. }
  26632. // Result
  26633. var vertexData = new VertexData();
  26634. vertexData.indices = indices;
  26635. vertexData.positions = positions;
  26636. vertexData.normals = normals;
  26637. vertexData.uvs = uvs;
  26638. return vertexData;
  26639. };
  26640. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  26641. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  26642. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  26643. var indices = [];
  26644. var positions = [];
  26645. var normals = [];
  26646. var uvs = [];
  26647. var row, col, tileRow, tileCol;
  26648. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26649. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26650. precision.w = (precision.w < 1) ? 1 : precision.w;
  26651. precision.h = (precision.h < 1) ? 1 : precision.h;
  26652. var tileSize = {
  26653. 'w': (xmax - xmin) / subdivisions.w,
  26654. 'h': (zmax - zmin) / subdivisions.h
  26655. };
  26656. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26657. // Indices
  26658. var base = positions.length / 3;
  26659. var rowLength = precision.w + 1;
  26660. for (row = 0; row < precision.h; row++) {
  26661. for (col = 0; col < precision.w; col++) {
  26662. var square = [
  26663. base + col + row * rowLength,
  26664. base + (col + 1) + row * rowLength,
  26665. base + (col + 1) + (row + 1) * rowLength,
  26666. base + col + (row + 1) * rowLength
  26667. ];
  26668. indices.push(square[1]);
  26669. indices.push(square[2]);
  26670. indices.push(square[3]);
  26671. indices.push(square[0]);
  26672. indices.push(square[1]);
  26673. indices.push(square[3]);
  26674. }
  26675. }
  26676. // Position, normals and uvs
  26677. var position = BABYLON.Vector3.Zero();
  26678. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26679. for (row = 0; row <= precision.h; row++) {
  26680. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26681. for (col = 0; col <= precision.w; col++) {
  26682. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26683. position.y = 0;
  26684. positions.push(position.x, position.y, position.z);
  26685. normals.push(normal.x, normal.y, normal.z);
  26686. uvs.push(col / precision.w, row / precision.h);
  26687. }
  26688. }
  26689. }
  26690. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26691. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26692. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26693. }
  26694. }
  26695. // Result
  26696. var vertexData = new VertexData();
  26697. vertexData.indices = indices;
  26698. vertexData.positions = positions;
  26699. vertexData.normals = normals;
  26700. vertexData.uvs = uvs;
  26701. return vertexData;
  26702. };
  26703. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  26704. var indices = [];
  26705. var positions = [];
  26706. var normals = [];
  26707. var uvs = [];
  26708. var row, col;
  26709. // Vertices
  26710. for (row = 0; row <= subdivisions; row++) {
  26711. for (col = 0; col <= subdivisions; col++) {
  26712. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26713. // Compute height
  26714. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  26715. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  26716. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  26717. var r = buffer[pos] / 255.0;
  26718. var g = buffer[pos + 1] / 255.0;
  26719. var b = buffer[pos + 2] / 255.0;
  26720. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26721. position.y = minHeight + (maxHeight - minHeight) * gradient;
  26722. // Add vertex
  26723. positions.push(position.x, position.y, position.z);
  26724. normals.push(0, 0, 0);
  26725. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26726. }
  26727. }
  26728. // Indices
  26729. for (row = 0; row < subdivisions; row++) {
  26730. for (col = 0; col < subdivisions; col++) {
  26731. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26732. indices.push(col + 1 + row * (subdivisions + 1));
  26733. indices.push(col + row * (subdivisions + 1));
  26734. indices.push(col + (row + 1) * (subdivisions + 1));
  26735. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26736. indices.push(col + row * (subdivisions + 1));
  26737. }
  26738. }
  26739. // Normals
  26740. VertexData.ComputeNormals(positions, indices, normals);
  26741. // Result
  26742. var vertexData = new VertexData();
  26743. vertexData.indices = indices;
  26744. vertexData.positions = positions;
  26745. vertexData.normals = normals;
  26746. vertexData.uvs = uvs;
  26747. return vertexData;
  26748. };
  26749. VertexData.CreatePlane = function (size, sideOrientation) {
  26750. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26751. var indices = [];
  26752. var positions = [];
  26753. var normals = [];
  26754. var uvs = [];
  26755. size = size || 1;
  26756. // Vertices
  26757. var halfSize = size / 2.0;
  26758. positions.push(-halfSize, -halfSize, 0);
  26759. normals.push(0, 0, -1.0);
  26760. uvs.push(0.0, 0.0);
  26761. positions.push(halfSize, -halfSize, 0);
  26762. normals.push(0, 0, -1.0);
  26763. uvs.push(1.0, 0.0);
  26764. positions.push(halfSize, halfSize, 0);
  26765. normals.push(0, 0, -1.0);
  26766. uvs.push(1.0, 1.0);
  26767. positions.push(-halfSize, halfSize, 0);
  26768. normals.push(0, 0, -1.0);
  26769. uvs.push(0.0, 1.0);
  26770. // Indices
  26771. indices.push(0);
  26772. indices.push(1);
  26773. indices.push(2);
  26774. indices.push(0);
  26775. indices.push(2);
  26776. indices.push(3);
  26777. // Sides
  26778. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26779. // Result
  26780. var vertexData = new VertexData();
  26781. vertexData.indices = indices;
  26782. vertexData.positions = positions;
  26783. vertexData.normals = normals;
  26784. vertexData.uvs = uvs;
  26785. return vertexData;
  26786. };
  26787. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  26788. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26789. var positions = [];
  26790. var indices = [];
  26791. var normals = [];
  26792. var uvs = [];
  26793. // positions and uvs
  26794. positions.push(0, 0, 0); // disc center first
  26795. uvs.push(0.5, 0.5);
  26796. var step = Math.PI * 2 / tessellation;
  26797. for (var a = 0; a < Math.PI * 2; a += step) {
  26798. var x = Math.cos(a);
  26799. var y = Math.sin(a);
  26800. var u = (x + 1) / 2;
  26801. var v = (1 - y) / 2;
  26802. positions.push(radius * x, radius * y, 0);
  26803. uvs.push(u, v);
  26804. }
  26805. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26806. uvs.push(uvs[2], uvs[3]);
  26807. //indices
  26808. var vertexNb = positions.length / 3;
  26809. for (var i = 1; i < vertexNb - 1; i++) {
  26810. indices.push(i + 1, 0, i);
  26811. }
  26812. // result
  26813. VertexData.ComputeNormals(positions, indices, normals);
  26814. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26815. var vertexData = new VertexData();
  26816. vertexData.indices = indices;
  26817. vertexData.positions = positions;
  26818. vertexData.normals = normals;
  26819. vertexData.uvs = uvs;
  26820. return vertexData;
  26821. };
  26822. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26823. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  26824. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26825. var indices = [];
  26826. var positions = [];
  26827. var normals = [];
  26828. var uvs = [];
  26829. radius = radius || 2;
  26830. tube = tube || 0.5;
  26831. radialSegments = radialSegments || 32;
  26832. tubularSegments = tubularSegments || 32;
  26833. p = p || 2;
  26834. q = q || 3;
  26835. // Helper
  26836. var getPos = function (angle) {
  26837. var cu = Math.cos(angle);
  26838. var su = Math.sin(angle);
  26839. var quOverP = q / p * angle;
  26840. var cs = Math.cos(quOverP);
  26841. var tx = radius * (2 + cs) * 0.5 * cu;
  26842. var ty = radius * (2 + cs) * su * 0.5;
  26843. var tz = radius * Math.sin(quOverP) * 0.5;
  26844. return new BABYLON.Vector3(tx, ty, tz);
  26845. };
  26846. // Vertices
  26847. var i;
  26848. var j;
  26849. for (i = 0; i <= radialSegments; i++) {
  26850. var modI = i % radialSegments;
  26851. var u = modI / radialSegments * 2 * p * Math.PI;
  26852. var p1 = getPos(u);
  26853. var p2 = getPos(u + 0.01);
  26854. var tang = p2.subtract(p1);
  26855. var n = p2.add(p1);
  26856. var bitan = BABYLON.Vector3.Cross(tang, n);
  26857. n = BABYLON.Vector3.Cross(bitan, tang);
  26858. bitan.normalize();
  26859. n.normalize();
  26860. for (j = 0; j < tubularSegments; j++) {
  26861. var modJ = j % tubularSegments;
  26862. var v = modJ / tubularSegments * 2 * Math.PI;
  26863. var cx = -tube * Math.cos(v);
  26864. var cy = tube * Math.sin(v);
  26865. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26866. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26867. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26868. uvs.push(i / radialSegments);
  26869. uvs.push(j / tubularSegments);
  26870. }
  26871. }
  26872. for (i = 0; i < radialSegments; i++) {
  26873. for (j = 0; j < tubularSegments; j++) {
  26874. var jNext = (j + 1) % tubularSegments;
  26875. var a = i * tubularSegments + j;
  26876. var b = (i + 1) * tubularSegments + j;
  26877. var c = (i + 1) * tubularSegments + jNext;
  26878. var d = i * tubularSegments + jNext;
  26879. indices.push(d);
  26880. indices.push(b);
  26881. indices.push(a);
  26882. indices.push(d);
  26883. indices.push(c);
  26884. indices.push(b);
  26885. }
  26886. }
  26887. // Normals
  26888. VertexData.ComputeNormals(positions, indices, normals);
  26889. // Sides
  26890. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26891. // Result
  26892. var vertexData = new VertexData();
  26893. vertexData.indices = indices;
  26894. vertexData.positions = positions;
  26895. vertexData.normals = normals;
  26896. vertexData.uvs = uvs;
  26897. return vertexData;
  26898. };
  26899. // Tools
  26900. /**
  26901. * @param {any} - positions (number[] or Float32Array)
  26902. * @param {any} - indices (number[] or Uint16Array)
  26903. * @param {any} - normals (number[] or Float32Array)
  26904. */
  26905. VertexData.ComputeNormals = function (positions, indices, normals) {
  26906. var index = 0;
  26907. // temp Vector3
  26908. var p1p2 = BABYLON.Vector3.Zero();
  26909. var p3p2 = BABYLON.Vector3.Zero();
  26910. var faceNormal = BABYLON.Vector3.Zero();
  26911. var vertexNormali1 = BABYLON.Vector3.Zero();
  26912. for (index = 0; index < positions.length; index++) {
  26913. normals[index] = 0.0;
  26914. }
  26915. // indice triplet = 1 face
  26916. var nbFaces = indices.length / 3;
  26917. for (index = 0; index < nbFaces; index++) {
  26918. var i1 = indices[index * 3];
  26919. var i2 = indices[index * 3 + 1];
  26920. var i3 = indices[index * 3 + 2];
  26921. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  26922. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  26923. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  26924. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  26925. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  26926. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  26927. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  26928. faceNormal.normalize();
  26929. normals[i1 * 3] += faceNormal.x;
  26930. normals[i1 * 3 + 1] += faceNormal.y;
  26931. normals[i1 * 3 + 2] += faceNormal.z;
  26932. normals[i2 * 3] += faceNormal.x;
  26933. normals[i2 * 3 + 1] += faceNormal.y;
  26934. normals[i2 * 3 + 2] += faceNormal.z;
  26935. normals[i3 * 3] += faceNormal.x;
  26936. normals[i3 * 3 + 1] += faceNormal.y;
  26937. normals[i3 * 3 + 2] += faceNormal.z;
  26938. }
  26939. // last normalization
  26940. for (index = 0; index < normals.length / 3; index++) {
  26941. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  26942. vertexNormali1.normalize();
  26943. normals[index * 3] = vertexNormali1.x;
  26944. normals[index * 3 + 1] = vertexNormali1.y;
  26945. normals[index * 3 + 2] = vertexNormali1.z;
  26946. }
  26947. };
  26948. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26949. var li = indices.length;
  26950. var ln = normals.length;
  26951. var i;
  26952. var n;
  26953. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26954. switch (sideOrientation) {
  26955. case BABYLON.Mesh.FRONTSIDE:
  26956. // nothing changed
  26957. break;
  26958. case BABYLON.Mesh.BACKSIDE:
  26959. var tmp;
  26960. // indices
  26961. for (i = 0; i < li; i += 3) {
  26962. tmp = indices[i];
  26963. indices[i] = indices[i + 2];
  26964. indices[i + 2] = tmp;
  26965. }
  26966. // normals
  26967. for (n = 0; n < ln; n++) {
  26968. normals[n] = -normals[n];
  26969. }
  26970. break;
  26971. case BABYLON.Mesh.DOUBLESIDE:
  26972. // positions
  26973. var lp = positions.length;
  26974. var l = lp / 3;
  26975. for (var p = 0; p < lp; p++) {
  26976. positions[lp + p] = positions[p];
  26977. }
  26978. // indices
  26979. for (i = 0; i < li; i += 3) {
  26980. indices[i + li] = indices[i + 2] + l;
  26981. indices[i + 1 + li] = indices[i + 1] + l;
  26982. indices[i + 2 + li] = indices[i] + l;
  26983. }
  26984. // normals
  26985. for (n = 0; n < ln; n++) {
  26986. normals[ln + n] = -normals[n];
  26987. }
  26988. // uvs
  26989. var lu = uvs.length;
  26990. for (var u = 0; u < lu; u++) {
  26991. uvs[u + lu] = uvs[u];
  26992. }
  26993. break;
  26994. }
  26995. };
  26996. return VertexData;
  26997. })();
  26998. BABYLON.VertexData = VertexData;
  26999. })(BABYLON || (BABYLON = {}));
  27000. var BABYLON;
  27001. (function (BABYLON) {
  27002. var AnaglyphPostProcess = (function (_super) {
  27003. __extends(AnaglyphPostProcess, _super);
  27004. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27005. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  27006. }
  27007. return AnaglyphPostProcess;
  27008. })(BABYLON.PostProcess);
  27009. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  27010. })(BABYLON || (BABYLON = {}));
  27011. var BABYLON;
  27012. (function (BABYLON) {
  27013. var Tags = (function () {
  27014. function Tags() {
  27015. }
  27016. Tags.EnableFor = function (obj) {
  27017. obj._tags = obj._tags || {};
  27018. obj.hasTags = function () {
  27019. return Tags.HasTags(obj);
  27020. };
  27021. obj.addTags = function (tagsString) {
  27022. return Tags.AddTagsTo(obj, tagsString);
  27023. };
  27024. obj.removeTags = function (tagsString) {
  27025. return Tags.RemoveTagsFrom(obj, tagsString);
  27026. };
  27027. obj.matchesTagsQuery = function (tagsQuery) {
  27028. return Tags.MatchesQuery(obj, tagsQuery);
  27029. };
  27030. };
  27031. Tags.DisableFor = function (obj) {
  27032. delete obj._tags;
  27033. delete obj.hasTags;
  27034. delete obj.addTags;
  27035. delete obj.removeTags;
  27036. delete obj.matchesTagsQuery;
  27037. };
  27038. Tags.HasTags = function (obj) {
  27039. if (!obj._tags) {
  27040. return false;
  27041. }
  27042. return !BABYLON.Tools.IsEmpty(obj._tags);
  27043. };
  27044. Tags.GetTags = function (obj) {
  27045. if (!obj._tags) {
  27046. return null;
  27047. }
  27048. return obj._tags;
  27049. };
  27050. // the tags 'true' and 'false' are reserved and cannot be used as tags
  27051. // a tag cannot start with '||', '&&', and '!'
  27052. // it cannot contain whitespaces
  27053. Tags.AddTagsTo = function (obj, tagsString) {
  27054. if (!tagsString) {
  27055. return;
  27056. }
  27057. var tags = tagsString.split(" ");
  27058. for (var t in tags) {
  27059. Tags._AddTagTo(obj, tags[t]);
  27060. }
  27061. };
  27062. Tags._AddTagTo = function (obj, tag) {
  27063. tag = tag.trim();
  27064. if (tag === "" || tag === "true" || tag === "false") {
  27065. return;
  27066. }
  27067. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  27068. return;
  27069. }
  27070. Tags.EnableFor(obj);
  27071. obj._tags[tag] = true;
  27072. };
  27073. Tags.RemoveTagsFrom = function (obj, tagsString) {
  27074. if (!Tags.HasTags(obj)) {
  27075. return;
  27076. }
  27077. var tags = tagsString.split(" ");
  27078. for (var t in tags) {
  27079. Tags._RemoveTagFrom(obj, tags[t]);
  27080. }
  27081. };
  27082. Tags._RemoveTagFrom = function (obj, tag) {
  27083. delete obj._tags[tag];
  27084. };
  27085. Tags.MatchesQuery = function (obj, tagsQuery) {
  27086. if (tagsQuery === undefined) {
  27087. return true;
  27088. }
  27089. if (tagsQuery === "") {
  27090. return Tags.HasTags(obj);
  27091. }
  27092. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27093. };
  27094. return Tags;
  27095. })();
  27096. BABYLON.Tags = Tags;
  27097. })(BABYLON || (BABYLON = {}));
  27098. var BABYLON;
  27099. (function (BABYLON) {
  27100. var Internals;
  27101. (function (Internals) {
  27102. var AndOrNotEvaluator = (function () {
  27103. function AndOrNotEvaluator() {
  27104. }
  27105. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27106. if (!query.match(/\([^\(\)]*\)/g)) {
  27107. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27108. }
  27109. else {
  27110. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27111. // remove parenthesis
  27112. r = r.slice(1, r.length - 1);
  27113. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27114. });
  27115. }
  27116. if (query === "true") {
  27117. return true;
  27118. }
  27119. if (query === "false") {
  27120. return false;
  27121. }
  27122. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27123. };
  27124. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27125. evaluateCallback = evaluateCallback || (function (r) {
  27126. return r === "true" ? true : false;
  27127. });
  27128. var result;
  27129. var or = parenthesisContent.split("||");
  27130. for (var i in or) {
  27131. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27132. var and = ori.split("&&");
  27133. if (and.length > 1) {
  27134. for (var j = 0; j < and.length; ++j) {
  27135. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27136. if (andj !== "true" && andj !== "false") {
  27137. if (andj[0] === "!") {
  27138. result = !evaluateCallback(andj.substring(1));
  27139. }
  27140. else {
  27141. result = evaluateCallback(andj);
  27142. }
  27143. }
  27144. else {
  27145. result = andj === "true" ? true : false;
  27146. }
  27147. if (!result) {
  27148. ori = "false";
  27149. break;
  27150. }
  27151. }
  27152. }
  27153. if (result || ori === "true") {
  27154. result = true;
  27155. break;
  27156. }
  27157. // result equals false (or undefined)
  27158. if (ori !== "true" && ori !== "false") {
  27159. if (ori[0] === "!") {
  27160. result = !evaluateCallback(ori.substring(1));
  27161. }
  27162. else {
  27163. result = evaluateCallback(ori);
  27164. }
  27165. }
  27166. else {
  27167. result = ori === "true" ? true : false;
  27168. }
  27169. }
  27170. // the whole parenthesis scope is replaced by 'true' or 'false'
  27171. return result ? "true" : "false";
  27172. };
  27173. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27174. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27175. // remove whitespaces
  27176. r = r.replace(/[\s]/g, function () { return ""; });
  27177. return r.length % 2 ? "!" : "";
  27178. });
  27179. booleanString = booleanString.trim();
  27180. if (booleanString === "!true") {
  27181. booleanString = "false";
  27182. }
  27183. else if (booleanString === "!false") {
  27184. booleanString = "true";
  27185. }
  27186. return booleanString;
  27187. };
  27188. return AndOrNotEvaluator;
  27189. })();
  27190. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27191. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27192. })(BABYLON || (BABYLON = {}));
  27193. var BABYLON;
  27194. (function (BABYLON) {
  27195. var PostProcessRenderPass = (function () {
  27196. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27197. this._enabled = true;
  27198. this._refCount = 0;
  27199. this._name = name;
  27200. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27201. this.setRenderList(renderList);
  27202. this._renderTexture.onBeforeRender = beforeRender;
  27203. this._renderTexture.onAfterRender = afterRender;
  27204. this._scene = scene;
  27205. this._renderList = renderList;
  27206. }
  27207. // private
  27208. PostProcessRenderPass.prototype._incRefCount = function () {
  27209. if (this._refCount === 0) {
  27210. this._scene.customRenderTargets.push(this._renderTexture);
  27211. }
  27212. return ++this._refCount;
  27213. };
  27214. PostProcessRenderPass.prototype._decRefCount = function () {
  27215. this._refCount--;
  27216. if (this._refCount <= 0) {
  27217. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27218. }
  27219. return this._refCount;
  27220. };
  27221. PostProcessRenderPass.prototype._update = function () {
  27222. this.setRenderList(this._renderList);
  27223. };
  27224. // public
  27225. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27226. this._renderTexture.renderList = renderList;
  27227. };
  27228. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27229. return this._renderTexture;
  27230. };
  27231. return PostProcessRenderPass;
  27232. })();
  27233. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27234. })(BABYLON || (BABYLON = {}));
  27235. var BABYLON;
  27236. (function (BABYLON) {
  27237. var PostProcessRenderEffect = (function () {
  27238. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27239. this._engine = engine;
  27240. this._name = name;
  27241. this._singleInstance = singleInstance || true;
  27242. this._getPostProcess = getPostProcess;
  27243. this._cameras = [];
  27244. this._indicesForCamera = [];
  27245. this._postProcesses = {};
  27246. this._renderPasses = {};
  27247. this._renderEffectAsPasses = {};
  27248. }
  27249. PostProcessRenderEffect.prototype._update = function () {
  27250. for (var renderPassName in this._renderPasses) {
  27251. this._renderPasses[renderPassName]._update();
  27252. }
  27253. };
  27254. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27255. this._renderPasses[renderPass._name] = renderPass;
  27256. this._linkParameters();
  27257. };
  27258. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27259. delete this._renderPasses[renderPass._name];
  27260. this._linkParameters();
  27261. };
  27262. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27263. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27264. this._linkParameters();
  27265. };
  27266. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27267. for (var renderPassName in this._renderPasses) {
  27268. if (renderPassName === passName) {
  27269. return this._renderPasses[passName];
  27270. }
  27271. }
  27272. };
  27273. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27274. this._renderPasses = {};
  27275. this._linkParameters();
  27276. };
  27277. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27278. var cameraKey;
  27279. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27280. for (var i = 0; i < _cam.length; i++) {
  27281. var camera = _cam[i];
  27282. var cameraName = camera.name;
  27283. if (this._singleInstance) {
  27284. cameraKey = 0;
  27285. }
  27286. else {
  27287. cameraKey = cameraName;
  27288. }
  27289. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27290. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27291. if (!this._indicesForCamera[cameraName]) {
  27292. this._indicesForCamera[cameraName] = [];
  27293. }
  27294. this._indicesForCamera[cameraName].push(index);
  27295. if (this._cameras.indexOf(camera) === -1) {
  27296. this._cameras[cameraName] = camera;
  27297. }
  27298. for (var passName in this._renderPasses) {
  27299. this._renderPasses[passName]._incRefCount();
  27300. }
  27301. }
  27302. this._linkParameters();
  27303. };
  27304. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27305. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27306. for (var i = 0; i < _cam.length; i++) {
  27307. var camera = _cam[i];
  27308. var cameraName = camera.name;
  27309. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27310. var index = this._cameras.indexOf(cameraName);
  27311. this._indicesForCamera.splice(index, 1);
  27312. this._cameras.splice(index, 1);
  27313. for (var passName in this._renderPasses) {
  27314. this._renderPasses[passName]._decRefCount();
  27315. }
  27316. }
  27317. };
  27318. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27319. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27320. for (var i = 0; i < _cam.length; i++) {
  27321. var camera = _cam[i];
  27322. var cameraName = camera.name;
  27323. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27324. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27325. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27326. }
  27327. }
  27328. for (var passName in this._renderPasses) {
  27329. this._renderPasses[passName]._incRefCount();
  27330. }
  27331. }
  27332. };
  27333. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27334. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27335. for (var i = 0; i < _cam.length; i++) {
  27336. var camera = _cam[i];
  27337. var cameraName = camera.Name;
  27338. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27339. for (var passName in this._renderPasses) {
  27340. this._renderPasses[passName]._decRefCount();
  27341. }
  27342. }
  27343. };
  27344. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27345. if (this._singleInstance) {
  27346. return this._postProcesses[0];
  27347. }
  27348. else {
  27349. return this._postProcesses[camera.name];
  27350. }
  27351. };
  27352. PostProcessRenderEffect.prototype._linkParameters = function () {
  27353. var _this = this;
  27354. for (var index in this._postProcesses) {
  27355. if (this.applyParameters) {
  27356. this.applyParameters(this._postProcesses[index]);
  27357. }
  27358. this._postProcesses[index].onBeforeRender = function (effect) {
  27359. _this._linkTextures(effect);
  27360. };
  27361. }
  27362. };
  27363. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27364. for (var renderPassName in this._renderPasses) {
  27365. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27366. }
  27367. for (var renderEffectName in this._renderEffectAsPasses) {
  27368. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27369. }
  27370. };
  27371. return PostProcessRenderEffect;
  27372. })();
  27373. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27374. })(BABYLON || (BABYLON = {}));
  27375. var BABYLON;
  27376. (function (BABYLON) {
  27377. var PostProcessRenderPipeline = (function () {
  27378. function PostProcessRenderPipeline(engine, name) {
  27379. this._engine = engine;
  27380. this._name = name;
  27381. this._renderEffects = {};
  27382. this._renderEffectsForIsolatedPass = {};
  27383. this._cameras = [];
  27384. }
  27385. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  27386. this._renderEffects[renderEffect._name] = renderEffect;
  27387. };
  27388. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  27389. var renderEffects = this._renderEffects[renderEffectName];
  27390. if (!renderEffects) {
  27391. return;
  27392. }
  27393. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27394. };
  27395. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  27396. var renderEffects = this._renderEffects[renderEffectName];
  27397. if (!renderEffects) {
  27398. return;
  27399. }
  27400. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27401. };
  27402. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  27403. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27404. var indicesToDelete = [];
  27405. for (var i = 0; i < _cam.length; i++) {
  27406. var camera = _cam[i];
  27407. var cameraName = camera.name;
  27408. if (this._cameras.indexOf(camera) === -1) {
  27409. this._cameras[cameraName] = camera;
  27410. }
  27411. else if (unique) {
  27412. indicesToDelete.push(i);
  27413. }
  27414. }
  27415. for (var i = 0; i < indicesToDelete.length; i++) {
  27416. cameras.splice(indicesToDelete[i], 1);
  27417. }
  27418. for (var renderEffectName in this._renderEffects) {
  27419. this._renderEffects[renderEffectName]._attachCameras(_cam);
  27420. }
  27421. };
  27422. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  27423. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27424. for (var renderEffectName in this._renderEffects) {
  27425. this._renderEffects[renderEffectName]._detachCameras(_cam);
  27426. }
  27427. for (var i = 0; i < _cam.length; i++) {
  27428. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  27429. }
  27430. };
  27431. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  27432. var _this = this;
  27433. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27434. var pass = null;
  27435. for (var renderEffectName in this._renderEffects) {
  27436. pass = this._renderEffects[renderEffectName].getPass(passName);
  27437. if (pass != null) {
  27438. break;
  27439. }
  27440. }
  27441. if (pass === null) {
  27442. return;
  27443. }
  27444. for (var renderEffectName in this._renderEffects) {
  27445. this._renderEffects[renderEffectName]._disable(_cam);
  27446. }
  27447. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  27448. for (var i = 0; i < _cam.length; i++) {
  27449. var camera = _cam[i];
  27450. var cameraName = camera.name;
  27451. 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); });
  27452. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  27453. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  27454. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  27455. }
  27456. };
  27457. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  27458. var _this = this;
  27459. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27460. for (var i = 0; i < _cam.length; i++) {
  27461. var camera = _cam[i];
  27462. var cameraName = camera.name;
  27463. 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); });
  27464. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  27465. }
  27466. for (var renderEffectName in this._renderEffects) {
  27467. this._renderEffects[renderEffectName]._enable(_cam);
  27468. }
  27469. };
  27470. PostProcessRenderPipeline.prototype._update = function () {
  27471. for (var renderEffectName in this._renderEffects) {
  27472. this._renderEffects[renderEffectName]._update();
  27473. }
  27474. for (var i = 0; i < this._cameras.length; i++) {
  27475. var cameraName = this._cameras[i].name;
  27476. if (this._renderEffectsForIsolatedPass[cameraName]) {
  27477. this._renderEffectsForIsolatedPass[cameraName]._update();
  27478. }
  27479. }
  27480. };
  27481. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  27482. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  27483. return PostProcessRenderPipeline;
  27484. })();
  27485. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  27486. })(BABYLON || (BABYLON = {}));
  27487. var BABYLON;
  27488. (function (BABYLON) {
  27489. var PostProcessRenderPipelineManager = (function () {
  27490. function PostProcessRenderPipelineManager() {
  27491. this._renderPipelines = {};
  27492. }
  27493. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  27494. this._renderPipelines[renderPipeline._name] = renderPipeline;
  27495. };
  27496. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  27497. var renderPipeline = this._renderPipelines[renderPipelineName];
  27498. if (!renderPipeline) {
  27499. return;
  27500. }
  27501. renderPipeline._attachCameras(cameras, unique);
  27502. };
  27503. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  27504. var renderPipeline = this._renderPipelines[renderPipelineName];
  27505. if (!renderPipeline) {
  27506. return;
  27507. }
  27508. renderPipeline._detachCameras(cameras);
  27509. };
  27510. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27511. var renderPipeline = this._renderPipelines[renderPipelineName];
  27512. if (!renderPipeline) {
  27513. return;
  27514. }
  27515. renderPipeline._enableEffect(renderEffectName, cameras);
  27516. };
  27517. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27518. var renderPipeline = this._renderPipelines[renderPipelineName];
  27519. if (!renderPipeline) {
  27520. return;
  27521. }
  27522. renderPipeline._disableEffect(renderEffectName, cameras);
  27523. };
  27524. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  27525. var renderPipeline = this._renderPipelines[renderPipelineName];
  27526. if (!renderPipeline) {
  27527. return;
  27528. }
  27529. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  27530. };
  27531. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  27532. var renderPipeline = this._renderPipelines[renderPipelineName];
  27533. if (!renderPipeline) {
  27534. return;
  27535. }
  27536. renderPipeline._disableDisplayOnlyPass(cameras);
  27537. };
  27538. PostProcessRenderPipelineManager.prototype.update = function () {
  27539. for (var renderPipelineName in this._renderPipelines) {
  27540. this._renderPipelines[renderPipelineName]._update();
  27541. }
  27542. };
  27543. return PostProcessRenderPipelineManager;
  27544. })();
  27545. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  27546. })(BABYLON || (BABYLON = {}));
  27547. var BABYLON;
  27548. (function (BABYLON) {
  27549. var DisplayPassPostProcess = (function (_super) {
  27550. __extends(DisplayPassPostProcess, _super);
  27551. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27552. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  27553. }
  27554. return DisplayPassPostProcess;
  27555. })(BABYLON.PostProcess);
  27556. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  27557. })(BABYLON || (BABYLON = {}));
  27558. var BABYLON;
  27559. (function (BABYLON) {
  27560. var BoundingBoxRenderer = (function () {
  27561. function BoundingBoxRenderer(scene) {
  27562. this.frontColor = new BABYLON.Color3(1, 1, 1);
  27563. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  27564. this.showBackLines = true;
  27565. this.renderList = new BABYLON.SmartArray(32);
  27566. this._scene = scene;
  27567. }
  27568. BoundingBoxRenderer.prototype._prepareRessources = function () {
  27569. if (this._colorShader) {
  27570. return;
  27571. }
  27572. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  27573. attributes: ["position"],
  27574. uniforms: ["worldViewProjection", "color"]
  27575. });
  27576. var engine = this._scene.getEngine();
  27577. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  27578. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  27579. 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]);
  27580. };
  27581. BoundingBoxRenderer.prototype.reset = function () {
  27582. this.renderList.reset();
  27583. };
  27584. BoundingBoxRenderer.prototype.render = function () {
  27585. if (this.renderList.length === 0) {
  27586. return;
  27587. }
  27588. this._prepareRessources();
  27589. if (!this._colorShader.isReady()) {
  27590. return;
  27591. }
  27592. var engine = this._scene.getEngine();
  27593. engine.setDepthWrite(false);
  27594. this._colorShader._preBind();
  27595. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27596. var boundingBox = this.renderList.data[boundingBoxIndex];
  27597. var min = boundingBox.minimum;
  27598. var max = boundingBox.maximum;
  27599. var diff = max.subtract(min);
  27600. var median = min.add(diff.scale(0.5));
  27601. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27602. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27603. .multiply(boundingBox.getWorldMatrix());
  27604. // VBOs
  27605. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27606. if (this.showBackLines) {
  27607. // Back
  27608. engine.setDepthFunctionToGreaterOrEqual();
  27609. this._scene.resetCachedMaterial();
  27610. this._colorShader.setColor4("color", this.backColor.toColor4());
  27611. this._colorShader.bind(worldMatrix);
  27612. // Draw order
  27613. engine.draw(false, 0, 24);
  27614. }
  27615. // Front
  27616. engine.setDepthFunctionToLess();
  27617. this._scene.resetCachedMaterial();
  27618. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27619. this._colorShader.bind(worldMatrix);
  27620. // Draw order
  27621. engine.draw(false, 0, 24);
  27622. }
  27623. this._colorShader.unbind();
  27624. engine.setDepthFunctionToLessOrEqual();
  27625. engine.setDepthWrite(true);
  27626. };
  27627. BoundingBoxRenderer.prototype.dispose = function () {
  27628. if (!this._colorShader) {
  27629. return;
  27630. }
  27631. this._colorShader.dispose();
  27632. this._vb.dispose();
  27633. this._scene.getEngine()._releaseBuffer(this._ib);
  27634. };
  27635. return BoundingBoxRenderer;
  27636. })();
  27637. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27638. })(BABYLON || (BABYLON = {}));
  27639. var BABYLON;
  27640. (function (BABYLON) {
  27641. var Condition = (function () {
  27642. function Condition(actionManager) {
  27643. this._actionManager = actionManager;
  27644. }
  27645. Condition.prototype.isValid = function () {
  27646. return true;
  27647. };
  27648. Condition.prototype._getProperty = function (propertyPath) {
  27649. return this._actionManager._getProperty(propertyPath);
  27650. };
  27651. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27652. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27653. };
  27654. return Condition;
  27655. })();
  27656. BABYLON.Condition = Condition;
  27657. var ValueCondition = (function (_super) {
  27658. __extends(ValueCondition, _super);
  27659. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27660. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27661. _super.call(this, actionManager);
  27662. this.propertyPath = propertyPath;
  27663. this.value = value;
  27664. this.operator = operator;
  27665. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27666. this._property = this._getProperty(this.propertyPath);
  27667. }
  27668. Object.defineProperty(ValueCondition, "IsEqual", {
  27669. get: function () {
  27670. return ValueCondition._IsEqual;
  27671. },
  27672. enumerable: true,
  27673. configurable: true
  27674. });
  27675. Object.defineProperty(ValueCondition, "IsDifferent", {
  27676. get: function () {
  27677. return ValueCondition._IsDifferent;
  27678. },
  27679. enumerable: true,
  27680. configurable: true
  27681. });
  27682. Object.defineProperty(ValueCondition, "IsGreater", {
  27683. get: function () {
  27684. return ValueCondition._IsGreater;
  27685. },
  27686. enumerable: true,
  27687. configurable: true
  27688. });
  27689. Object.defineProperty(ValueCondition, "IsLesser", {
  27690. get: function () {
  27691. return ValueCondition._IsLesser;
  27692. },
  27693. enumerable: true,
  27694. configurable: true
  27695. });
  27696. // Methods
  27697. ValueCondition.prototype.isValid = function () {
  27698. switch (this.operator) {
  27699. case ValueCondition.IsGreater:
  27700. return this._target[this._property] > this.value;
  27701. case ValueCondition.IsLesser:
  27702. return this._target[this._property] < this.value;
  27703. case ValueCondition.IsEqual:
  27704. case ValueCondition.IsDifferent:
  27705. var check;
  27706. if (this.value.equals) {
  27707. check = this.value.equals(this._target[this._property]);
  27708. }
  27709. else {
  27710. check = this.value === this._target[this._property];
  27711. }
  27712. return this.operator === ValueCondition.IsEqual ? check : !check;
  27713. }
  27714. return false;
  27715. };
  27716. // Statics
  27717. ValueCondition._IsEqual = 0;
  27718. ValueCondition._IsDifferent = 1;
  27719. ValueCondition._IsGreater = 2;
  27720. ValueCondition._IsLesser = 3;
  27721. return ValueCondition;
  27722. })(Condition);
  27723. BABYLON.ValueCondition = ValueCondition;
  27724. var PredicateCondition = (function (_super) {
  27725. __extends(PredicateCondition, _super);
  27726. function PredicateCondition(actionManager, predicate) {
  27727. _super.call(this, actionManager);
  27728. this.predicate = predicate;
  27729. }
  27730. PredicateCondition.prototype.isValid = function () {
  27731. return this.predicate();
  27732. };
  27733. return PredicateCondition;
  27734. })(Condition);
  27735. BABYLON.PredicateCondition = PredicateCondition;
  27736. var StateCondition = (function (_super) {
  27737. __extends(StateCondition, _super);
  27738. function StateCondition(actionManager, target, value) {
  27739. _super.call(this, actionManager);
  27740. this.value = value;
  27741. this._target = target;
  27742. }
  27743. // Methods
  27744. StateCondition.prototype.isValid = function () {
  27745. return this._target.state === this.value;
  27746. };
  27747. return StateCondition;
  27748. })(Condition);
  27749. BABYLON.StateCondition = StateCondition;
  27750. })(BABYLON || (BABYLON = {}));
  27751. var BABYLON;
  27752. (function (BABYLON) {
  27753. var Action = (function () {
  27754. function Action(triggerOptions, condition) {
  27755. this.triggerOptions = triggerOptions;
  27756. if (triggerOptions.parameter) {
  27757. this.trigger = triggerOptions.trigger;
  27758. this._triggerParameter = triggerOptions.parameter;
  27759. }
  27760. else {
  27761. this.trigger = triggerOptions;
  27762. }
  27763. this._nextActiveAction = this;
  27764. this._condition = condition;
  27765. }
  27766. // Methods
  27767. Action.prototype._prepare = function () {
  27768. };
  27769. Action.prototype.getTriggerParameter = function () {
  27770. return this._triggerParameter;
  27771. };
  27772. Action.prototype._executeCurrent = function (evt) {
  27773. if (this._nextActiveAction._condition) {
  27774. var condition = this._nextActiveAction._condition;
  27775. var currentRenderId = this._actionManager.getScene().getRenderId();
  27776. // We cache the current evaluation for the current frame
  27777. if (condition._evaluationId === currentRenderId) {
  27778. if (!condition._currentResult) {
  27779. return;
  27780. }
  27781. }
  27782. else {
  27783. condition._evaluationId = currentRenderId;
  27784. if (!condition.isValid()) {
  27785. condition._currentResult = false;
  27786. return;
  27787. }
  27788. condition._currentResult = true;
  27789. }
  27790. }
  27791. this._nextActiveAction.execute(evt);
  27792. if (this._nextActiveAction._child) {
  27793. if (!this._nextActiveAction._child._actionManager) {
  27794. this._nextActiveAction._child._actionManager = this._actionManager;
  27795. }
  27796. this._nextActiveAction = this._nextActiveAction._child;
  27797. }
  27798. else {
  27799. this._nextActiveAction = this;
  27800. }
  27801. };
  27802. Action.prototype.execute = function (evt) {
  27803. };
  27804. Action.prototype.then = function (action) {
  27805. this._child = action;
  27806. action._actionManager = this._actionManager;
  27807. action._prepare();
  27808. return action;
  27809. };
  27810. Action.prototype._getProperty = function (propertyPath) {
  27811. return this._actionManager._getProperty(propertyPath);
  27812. };
  27813. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27814. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27815. };
  27816. return Action;
  27817. })();
  27818. BABYLON.Action = Action;
  27819. })(BABYLON || (BABYLON = {}));
  27820. var BABYLON;
  27821. (function (BABYLON) {
  27822. /**
  27823. * ActionEvent is the event beint sent when an action is triggered.
  27824. */
  27825. var ActionEvent = (function () {
  27826. /**
  27827. * @constructor
  27828. * @param source The mesh that triggered the action.
  27829. * @param pointerX the X mouse cursor position at the time of the event
  27830. * @param pointerY the Y mouse cursor position at the time of the event
  27831. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27832. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27833. */
  27834. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27835. this.source = source;
  27836. this.pointerX = pointerX;
  27837. this.pointerY = pointerY;
  27838. this.meshUnderPointer = meshUnderPointer;
  27839. this.sourceEvent = sourceEvent;
  27840. this.additionalData = additionalData;
  27841. }
  27842. /**
  27843. * Helper function to auto-create an ActionEvent from a source mesh.
  27844. * @param source the source mesh that triggered the event
  27845. * @param evt {Event} The original (browser) event
  27846. */
  27847. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27848. var scene = source.getScene();
  27849. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27850. };
  27851. /**
  27852. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27853. * @param scene the scene where the event occurred
  27854. * @param evt {Event} The original (browser) event
  27855. */
  27856. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27857. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27858. };
  27859. return ActionEvent;
  27860. })();
  27861. BABYLON.ActionEvent = ActionEvent;
  27862. /**
  27863. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27864. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27865. */
  27866. var ActionManager = (function () {
  27867. function ActionManager(scene) {
  27868. // Members
  27869. this.actions = new Array();
  27870. this._scene = scene;
  27871. scene._actionManagers.push(this);
  27872. }
  27873. Object.defineProperty(ActionManager, "NothingTrigger", {
  27874. get: function () {
  27875. return ActionManager._NothingTrigger;
  27876. },
  27877. enumerable: true,
  27878. configurable: true
  27879. });
  27880. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27881. get: function () {
  27882. return ActionManager._OnPickTrigger;
  27883. },
  27884. enumerable: true,
  27885. configurable: true
  27886. });
  27887. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27888. get: function () {
  27889. return ActionManager._OnLeftPickTrigger;
  27890. },
  27891. enumerable: true,
  27892. configurable: true
  27893. });
  27894. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27895. get: function () {
  27896. return ActionManager._OnRightPickTrigger;
  27897. },
  27898. enumerable: true,
  27899. configurable: true
  27900. });
  27901. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27902. get: function () {
  27903. return ActionManager._OnCenterPickTrigger;
  27904. },
  27905. enumerable: true,
  27906. configurable: true
  27907. });
  27908. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27909. get: function () {
  27910. return ActionManager._OnPointerOverTrigger;
  27911. },
  27912. enumerable: true,
  27913. configurable: true
  27914. });
  27915. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27916. get: function () {
  27917. return ActionManager._OnPointerOutTrigger;
  27918. },
  27919. enumerable: true,
  27920. configurable: true
  27921. });
  27922. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27923. get: function () {
  27924. return ActionManager._OnEveryFrameTrigger;
  27925. },
  27926. enumerable: true,
  27927. configurable: true
  27928. });
  27929. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27930. get: function () {
  27931. return ActionManager._OnIntersectionEnterTrigger;
  27932. },
  27933. enumerable: true,
  27934. configurable: true
  27935. });
  27936. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27937. get: function () {
  27938. return ActionManager._OnIntersectionExitTrigger;
  27939. },
  27940. enumerable: true,
  27941. configurable: true
  27942. });
  27943. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27944. get: function () {
  27945. return ActionManager._OnKeyDownTrigger;
  27946. },
  27947. enumerable: true,
  27948. configurable: true
  27949. });
  27950. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27951. get: function () {
  27952. return ActionManager._OnKeyUpTrigger;
  27953. },
  27954. enumerable: true,
  27955. configurable: true
  27956. });
  27957. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27958. get: function () {
  27959. return ActionManager._OnPickUpTrigger;
  27960. },
  27961. enumerable: true,
  27962. configurable: true
  27963. });
  27964. // Methods
  27965. ActionManager.prototype.dispose = function () {
  27966. var index = this._scene._actionManagers.indexOf(this);
  27967. if (index > -1) {
  27968. this._scene._actionManagers.splice(index, 1);
  27969. }
  27970. };
  27971. ActionManager.prototype.getScene = function () {
  27972. return this._scene;
  27973. };
  27974. /**
  27975. * Does this action manager handles actions of any of the given triggers
  27976. * @param {number[]} triggers - the triggers to be tested
  27977. * @return {boolean} whether one (or more) of the triggers is handeled
  27978. */
  27979. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27980. for (var index = 0; index < this.actions.length; index++) {
  27981. var action = this.actions[index];
  27982. if (triggers.indexOf(action.trigger) > -1) {
  27983. return true;
  27984. }
  27985. }
  27986. return false;
  27987. };
  27988. /**
  27989. * Does this action manager handles actions of a given trigger
  27990. * @param {number} trigger - the trigger to be tested
  27991. * @return {boolean} whether the trigger is handeled
  27992. */
  27993. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27994. for (var index = 0; index < this.actions.length; index++) {
  27995. var action = this.actions[index];
  27996. if (action.trigger === trigger) {
  27997. return true;
  27998. }
  27999. }
  28000. return false;
  28001. };
  28002. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  28003. /**
  28004. * Does this action manager has pointer triggers
  28005. * @return {boolean} whether or not it has pointer triggers
  28006. */
  28007. get: function () {
  28008. for (var index = 0; index < this.actions.length; index++) {
  28009. var action = this.actions[index];
  28010. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  28011. return true;
  28012. }
  28013. if (action.trigger == ActionManager._OnPickUpTrigger) {
  28014. return true;
  28015. }
  28016. }
  28017. return false;
  28018. },
  28019. enumerable: true,
  28020. configurable: true
  28021. });
  28022. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  28023. /**
  28024. * Does this action manager has pick triggers
  28025. * @return {boolean} whether or not it has pick triggers
  28026. */
  28027. get: function () {
  28028. for (var index = 0; index < this.actions.length; index++) {
  28029. var action = this.actions[index];
  28030. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  28031. return true;
  28032. }
  28033. }
  28034. return false;
  28035. },
  28036. enumerable: true,
  28037. configurable: true
  28038. });
  28039. /**
  28040. * Registers an action to this action manager
  28041. * @param {BABYLON.Action} action - the action to be registered
  28042. * @return {BABYLON.Action} the action amended (prepared) after registration
  28043. */
  28044. ActionManager.prototype.registerAction = function (action) {
  28045. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  28046. if (this.getScene().actionManager !== this) {
  28047. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  28048. return null;
  28049. }
  28050. }
  28051. this.actions.push(action);
  28052. action._actionManager = this;
  28053. action._prepare();
  28054. return action;
  28055. };
  28056. /**
  28057. * Process a specific trigger
  28058. * @param {number} trigger - the trigger to process
  28059. * @param evt {BABYLON.ActionEvent} the event details to be processed
  28060. */
  28061. ActionManager.prototype.processTrigger = function (trigger, evt) {
  28062. for (var index = 0; index < this.actions.length; index++) {
  28063. var action = this.actions[index];
  28064. if (action.trigger === trigger) {
  28065. if (trigger === ActionManager.OnKeyUpTrigger
  28066. || trigger === ActionManager.OnKeyDownTrigger) {
  28067. var parameter = action.getTriggerParameter();
  28068. if (parameter) {
  28069. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  28070. var actualkey = String.fromCharCode(unicode).toLowerCase();
  28071. if (actualkey !== parameter.toLowerCase()) {
  28072. continue;
  28073. }
  28074. }
  28075. }
  28076. action._executeCurrent(evt);
  28077. }
  28078. }
  28079. };
  28080. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28081. var properties = propertyPath.split(".");
  28082. for (var index = 0; index < properties.length - 1; index++) {
  28083. target = target[properties[index]];
  28084. }
  28085. return target;
  28086. };
  28087. ActionManager.prototype._getProperty = function (propertyPath) {
  28088. var properties = propertyPath.split(".");
  28089. return properties[properties.length - 1];
  28090. };
  28091. // Statics
  28092. ActionManager._NothingTrigger = 0;
  28093. ActionManager._OnPickTrigger = 1;
  28094. ActionManager._OnLeftPickTrigger = 2;
  28095. ActionManager._OnRightPickTrigger = 3;
  28096. ActionManager._OnCenterPickTrigger = 4;
  28097. ActionManager._OnPointerOverTrigger = 5;
  28098. ActionManager._OnPointerOutTrigger = 6;
  28099. ActionManager._OnEveryFrameTrigger = 7;
  28100. ActionManager._OnIntersectionEnterTrigger = 8;
  28101. ActionManager._OnIntersectionExitTrigger = 9;
  28102. ActionManager._OnKeyDownTrigger = 10;
  28103. ActionManager._OnKeyUpTrigger = 11;
  28104. ActionManager._OnPickUpTrigger = 12;
  28105. return ActionManager;
  28106. })();
  28107. BABYLON.ActionManager = ActionManager;
  28108. })(BABYLON || (BABYLON = {}));
  28109. var BABYLON;
  28110. (function (BABYLON) {
  28111. var InterpolateValueAction = (function (_super) {
  28112. __extends(InterpolateValueAction, _super);
  28113. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  28114. if (duration === void 0) { duration = 1000; }
  28115. _super.call(this, triggerOptions, condition);
  28116. this.propertyPath = propertyPath;
  28117. this.value = value;
  28118. this.duration = duration;
  28119. this.stopOtherAnimations = stopOtherAnimations;
  28120. this._target = target;
  28121. }
  28122. InterpolateValueAction.prototype._prepare = function () {
  28123. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28124. this._property = this._getProperty(this.propertyPath);
  28125. };
  28126. InterpolateValueAction.prototype.execute = function () {
  28127. var scene = this._actionManager.getScene();
  28128. var keys = [
  28129. {
  28130. frame: 0,
  28131. value: this._target[this._property]
  28132. }, {
  28133. frame: 100,
  28134. value: this.value
  28135. }
  28136. ];
  28137. var dataType;
  28138. if (typeof this.value === "number") {
  28139. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28140. }
  28141. else if (this.value instanceof BABYLON.Color3) {
  28142. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28143. }
  28144. else if (this.value instanceof BABYLON.Vector3) {
  28145. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28146. }
  28147. else if (this.value instanceof BABYLON.Matrix) {
  28148. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28149. }
  28150. else if (this.value instanceof BABYLON.Quaternion) {
  28151. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28152. }
  28153. else {
  28154. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28155. return;
  28156. }
  28157. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28158. animation.setKeys(keys);
  28159. if (this.stopOtherAnimations) {
  28160. scene.stopAnimation(this._target);
  28161. }
  28162. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  28163. };
  28164. return InterpolateValueAction;
  28165. })(BABYLON.Action);
  28166. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28167. })(BABYLON || (BABYLON = {}));
  28168. var BABYLON;
  28169. (function (BABYLON) {
  28170. var SwitchBooleanAction = (function (_super) {
  28171. __extends(SwitchBooleanAction, _super);
  28172. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28173. _super.call(this, triggerOptions, condition);
  28174. this.propertyPath = propertyPath;
  28175. this._target = target;
  28176. }
  28177. SwitchBooleanAction.prototype._prepare = function () {
  28178. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28179. this._property = this._getProperty(this.propertyPath);
  28180. };
  28181. SwitchBooleanAction.prototype.execute = function () {
  28182. this._target[this._property] = !this._target[this._property];
  28183. };
  28184. return SwitchBooleanAction;
  28185. })(BABYLON.Action);
  28186. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28187. var SetStateAction = (function (_super) {
  28188. __extends(SetStateAction, _super);
  28189. function SetStateAction(triggerOptions, target, value, condition) {
  28190. _super.call(this, triggerOptions, condition);
  28191. this.value = value;
  28192. this._target = target;
  28193. }
  28194. SetStateAction.prototype.execute = function () {
  28195. this._target.state = this.value;
  28196. };
  28197. return SetStateAction;
  28198. })(BABYLON.Action);
  28199. BABYLON.SetStateAction = SetStateAction;
  28200. var SetValueAction = (function (_super) {
  28201. __extends(SetValueAction, _super);
  28202. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28203. _super.call(this, triggerOptions, condition);
  28204. this.propertyPath = propertyPath;
  28205. this.value = value;
  28206. this._target = target;
  28207. }
  28208. SetValueAction.prototype._prepare = function () {
  28209. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28210. this._property = this._getProperty(this.propertyPath);
  28211. };
  28212. SetValueAction.prototype.execute = function () {
  28213. this._target[this._property] = this.value;
  28214. };
  28215. return SetValueAction;
  28216. })(BABYLON.Action);
  28217. BABYLON.SetValueAction = SetValueAction;
  28218. var IncrementValueAction = (function (_super) {
  28219. __extends(IncrementValueAction, _super);
  28220. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28221. _super.call(this, triggerOptions, condition);
  28222. this.propertyPath = propertyPath;
  28223. this.value = value;
  28224. this._target = target;
  28225. }
  28226. IncrementValueAction.prototype._prepare = function () {
  28227. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28228. this._property = this._getProperty(this.propertyPath);
  28229. if (typeof this._target[this._property] !== "number") {
  28230. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28231. }
  28232. };
  28233. IncrementValueAction.prototype.execute = function () {
  28234. this._target[this._property] += this.value;
  28235. };
  28236. return IncrementValueAction;
  28237. })(BABYLON.Action);
  28238. BABYLON.IncrementValueAction = IncrementValueAction;
  28239. var PlayAnimationAction = (function (_super) {
  28240. __extends(PlayAnimationAction, _super);
  28241. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28242. _super.call(this, triggerOptions, condition);
  28243. this.from = from;
  28244. this.to = to;
  28245. this.loop = loop;
  28246. this._target = target;
  28247. }
  28248. PlayAnimationAction.prototype._prepare = function () {
  28249. };
  28250. PlayAnimationAction.prototype.execute = function () {
  28251. var scene = this._actionManager.getScene();
  28252. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28253. };
  28254. return PlayAnimationAction;
  28255. })(BABYLON.Action);
  28256. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28257. var StopAnimationAction = (function (_super) {
  28258. __extends(StopAnimationAction, _super);
  28259. function StopAnimationAction(triggerOptions, target, condition) {
  28260. _super.call(this, triggerOptions, condition);
  28261. this._target = target;
  28262. }
  28263. StopAnimationAction.prototype._prepare = function () {
  28264. };
  28265. StopAnimationAction.prototype.execute = function () {
  28266. var scene = this._actionManager.getScene();
  28267. scene.stopAnimation(this._target);
  28268. };
  28269. return StopAnimationAction;
  28270. })(BABYLON.Action);
  28271. BABYLON.StopAnimationAction = StopAnimationAction;
  28272. var DoNothingAction = (function (_super) {
  28273. __extends(DoNothingAction, _super);
  28274. function DoNothingAction(triggerOptions, condition) {
  28275. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28276. _super.call(this, triggerOptions, condition);
  28277. }
  28278. DoNothingAction.prototype.execute = function () {
  28279. };
  28280. return DoNothingAction;
  28281. })(BABYLON.Action);
  28282. BABYLON.DoNothingAction = DoNothingAction;
  28283. var CombineAction = (function (_super) {
  28284. __extends(CombineAction, _super);
  28285. function CombineAction(triggerOptions, children, condition) {
  28286. _super.call(this, triggerOptions, condition);
  28287. this.children = children;
  28288. }
  28289. CombineAction.prototype._prepare = function () {
  28290. for (var index = 0; index < this.children.length; index++) {
  28291. this.children[index]._actionManager = this._actionManager;
  28292. this.children[index]._prepare();
  28293. }
  28294. };
  28295. CombineAction.prototype.execute = function (evt) {
  28296. for (var index = 0; index < this.children.length; index++) {
  28297. this.children[index].execute(evt);
  28298. }
  28299. };
  28300. return CombineAction;
  28301. })(BABYLON.Action);
  28302. BABYLON.CombineAction = CombineAction;
  28303. var ExecuteCodeAction = (function (_super) {
  28304. __extends(ExecuteCodeAction, _super);
  28305. function ExecuteCodeAction(triggerOptions, func, condition) {
  28306. _super.call(this, triggerOptions, condition);
  28307. this.func = func;
  28308. }
  28309. ExecuteCodeAction.prototype.execute = function (evt) {
  28310. this.func(evt);
  28311. };
  28312. return ExecuteCodeAction;
  28313. })(BABYLON.Action);
  28314. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28315. var SetParentAction = (function (_super) {
  28316. __extends(SetParentAction, _super);
  28317. function SetParentAction(triggerOptions, target, parent, condition) {
  28318. _super.call(this, triggerOptions, condition);
  28319. this._target = target;
  28320. this._parent = parent;
  28321. }
  28322. SetParentAction.prototype._prepare = function () {
  28323. };
  28324. SetParentAction.prototype.execute = function () {
  28325. if (this._target.parent === this._parent) {
  28326. return;
  28327. }
  28328. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28329. invertParentWorldMatrix.invert();
  28330. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28331. this._target.parent = this._parent;
  28332. };
  28333. return SetParentAction;
  28334. })(BABYLON.Action);
  28335. BABYLON.SetParentAction = SetParentAction;
  28336. var PlaySoundAction = (function (_super) {
  28337. __extends(PlaySoundAction, _super);
  28338. function PlaySoundAction(triggerOptions, sound, condition) {
  28339. _super.call(this, triggerOptions, condition);
  28340. this._sound = sound;
  28341. }
  28342. PlaySoundAction.prototype._prepare = function () {
  28343. };
  28344. PlaySoundAction.prototype.execute = function () {
  28345. if (this._sound !== undefined)
  28346. this._sound.play();
  28347. };
  28348. return PlaySoundAction;
  28349. })(BABYLON.Action);
  28350. BABYLON.PlaySoundAction = PlaySoundAction;
  28351. var StopSoundAction = (function (_super) {
  28352. __extends(StopSoundAction, _super);
  28353. function StopSoundAction(triggerOptions, sound, condition) {
  28354. _super.call(this, triggerOptions, condition);
  28355. this._sound = sound;
  28356. }
  28357. StopSoundAction.prototype._prepare = function () {
  28358. };
  28359. StopSoundAction.prototype.execute = function () {
  28360. if (this._sound !== undefined)
  28361. this._sound.stop();
  28362. };
  28363. return StopSoundAction;
  28364. })(BABYLON.Action);
  28365. BABYLON.StopSoundAction = StopSoundAction;
  28366. })(BABYLON || (BABYLON = {}));
  28367. var BABYLON;
  28368. (function (BABYLON) {
  28369. var Geometry = (function () {
  28370. function Geometry(id, scene, vertexData, updatable, mesh) {
  28371. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28372. this._totalVertices = 0;
  28373. this._indices = [];
  28374. this._isDisposed = false;
  28375. this.id = id;
  28376. this._engine = scene.getEngine();
  28377. this._meshes = [];
  28378. this._scene = scene;
  28379. // vertexData
  28380. if (vertexData) {
  28381. this.setAllVerticesData(vertexData, updatable);
  28382. }
  28383. else {
  28384. this._totalVertices = 0;
  28385. this._indices = [];
  28386. }
  28387. // applyToMesh
  28388. if (mesh) {
  28389. this.applyToMesh(mesh);
  28390. mesh.computeWorldMatrix(true);
  28391. }
  28392. }
  28393. Geometry.prototype.getScene = function () {
  28394. return this._scene;
  28395. };
  28396. Geometry.prototype.getEngine = function () {
  28397. return this._engine;
  28398. };
  28399. Geometry.prototype.isReady = function () {
  28400. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28401. };
  28402. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28403. vertexData.applyToGeometry(this, updatable);
  28404. this.notifyUpdate();
  28405. };
  28406. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28407. this._vertexBuffers = this._vertexBuffers || {};
  28408. if (this._vertexBuffers[kind]) {
  28409. this._vertexBuffers[kind].dispose();
  28410. }
  28411. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28412. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28413. stride = this._vertexBuffers[kind].getStrideSize();
  28414. this._totalVertices = data.length / stride;
  28415. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28416. var meshes = this._meshes;
  28417. var numOfMeshes = meshes.length;
  28418. for (var index = 0; index < numOfMeshes; index++) {
  28419. var mesh = meshes[index];
  28420. mesh._resetPointsArrayCache();
  28421. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28422. mesh._createGlobalSubMesh();
  28423. mesh.computeWorldMatrix(true);
  28424. }
  28425. }
  28426. this.notifyUpdate(kind);
  28427. };
  28428. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28429. var vertexBuffer = this.getVertexBuffer(kind);
  28430. if (!vertexBuffer) {
  28431. return;
  28432. }
  28433. vertexBuffer.updateDirectly(data, offset);
  28434. this.notifyUpdate(kind);
  28435. };
  28436. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28437. var vertexBuffer = this.getVertexBuffer(kind);
  28438. if (!vertexBuffer) {
  28439. return;
  28440. }
  28441. vertexBuffer.update(data);
  28442. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28443. var extend;
  28444. var stride = vertexBuffer.getStrideSize();
  28445. this._totalVertices = data.length / stride;
  28446. if (updateExtends) {
  28447. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28448. }
  28449. var meshes = this._meshes;
  28450. var numOfMeshes = meshes.length;
  28451. for (var index = 0; index < numOfMeshes; index++) {
  28452. var mesh = meshes[index];
  28453. mesh._resetPointsArrayCache();
  28454. if (updateExtends) {
  28455. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28456. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28457. var subMesh = mesh.subMeshes[subIndex];
  28458. subMesh.refreshBoundingInfo();
  28459. }
  28460. }
  28461. }
  28462. }
  28463. this.notifyUpdate(kind);
  28464. };
  28465. Geometry.prototype.getTotalVertices = function () {
  28466. if (!this.isReady()) {
  28467. return 0;
  28468. }
  28469. return this._totalVertices;
  28470. };
  28471. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28472. var vertexBuffer = this.getVertexBuffer(kind);
  28473. if (!vertexBuffer) {
  28474. return null;
  28475. }
  28476. var orig = vertexBuffer.getData();
  28477. if (!copyWhenShared || this._meshes.length === 1) {
  28478. return orig;
  28479. }
  28480. else {
  28481. var len = orig.length;
  28482. var copy = [];
  28483. for (var i = 0; i < len; i++) {
  28484. copy.push(orig[i]);
  28485. }
  28486. return copy;
  28487. }
  28488. };
  28489. Geometry.prototype.getVertexBuffer = function (kind) {
  28490. if (!this.isReady()) {
  28491. return null;
  28492. }
  28493. return this._vertexBuffers[kind];
  28494. };
  28495. Geometry.prototype.getVertexBuffers = function () {
  28496. if (!this.isReady()) {
  28497. return null;
  28498. }
  28499. return this._vertexBuffers;
  28500. };
  28501. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28502. if (!this._vertexBuffers) {
  28503. if (this._delayInfo) {
  28504. return this._delayInfo.indexOf(kind) !== -1;
  28505. }
  28506. return false;
  28507. }
  28508. return this._vertexBuffers[kind] !== undefined;
  28509. };
  28510. Geometry.prototype.getVerticesDataKinds = function () {
  28511. var result = [];
  28512. if (!this._vertexBuffers && this._delayInfo) {
  28513. for (var kind in this._delayInfo) {
  28514. result.push(kind);
  28515. }
  28516. }
  28517. else {
  28518. for (kind in this._vertexBuffers) {
  28519. result.push(kind);
  28520. }
  28521. }
  28522. return result;
  28523. };
  28524. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28525. if (this._indexBuffer) {
  28526. this._engine._releaseBuffer(this._indexBuffer);
  28527. }
  28528. this._indices = indices;
  28529. if (this._meshes.length !== 0 && this._indices) {
  28530. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28531. }
  28532. if (totalVertices !== undefined) {
  28533. this._totalVertices = totalVertices;
  28534. }
  28535. var meshes = this._meshes;
  28536. var numOfMeshes = meshes.length;
  28537. for (var index = 0; index < numOfMeshes; index++) {
  28538. meshes[index]._createGlobalSubMesh();
  28539. }
  28540. this.notifyUpdate();
  28541. };
  28542. Geometry.prototype.getTotalIndices = function () {
  28543. if (!this.isReady()) {
  28544. return 0;
  28545. }
  28546. return this._indices.length;
  28547. };
  28548. Geometry.prototype.getIndices = function (copyWhenShared) {
  28549. if (!this.isReady()) {
  28550. return null;
  28551. }
  28552. var orig = this._indices;
  28553. if (!copyWhenShared || this._meshes.length === 1) {
  28554. return orig;
  28555. }
  28556. else {
  28557. var len = orig.length;
  28558. var copy = [];
  28559. for (var i = 0; i < len; i++) {
  28560. copy.push(orig[i]);
  28561. }
  28562. return copy;
  28563. }
  28564. };
  28565. Geometry.prototype.getIndexBuffer = function () {
  28566. if (!this.isReady()) {
  28567. return null;
  28568. }
  28569. return this._indexBuffer;
  28570. };
  28571. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28572. var meshes = this._meshes;
  28573. var index = meshes.indexOf(mesh);
  28574. if (index === -1) {
  28575. return;
  28576. }
  28577. for (var kind in this._vertexBuffers) {
  28578. this._vertexBuffers[kind].dispose();
  28579. }
  28580. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28581. this._indexBuffer = null;
  28582. }
  28583. meshes.splice(index, 1);
  28584. mesh._geometry = null;
  28585. if (meshes.length === 0 && shouldDispose) {
  28586. this.dispose();
  28587. }
  28588. };
  28589. Geometry.prototype.applyToMesh = function (mesh) {
  28590. if (mesh._geometry === this) {
  28591. return;
  28592. }
  28593. var previousGeometry = mesh._geometry;
  28594. if (previousGeometry) {
  28595. previousGeometry.releaseForMesh(mesh);
  28596. }
  28597. var meshes = this._meshes;
  28598. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28599. mesh._geometry = this;
  28600. this._scene.pushGeometry(this);
  28601. meshes.push(mesh);
  28602. if (this.isReady()) {
  28603. this._applyToMesh(mesh);
  28604. }
  28605. else {
  28606. mesh._boundingInfo = this._boundingInfo;
  28607. }
  28608. };
  28609. Geometry.prototype._applyToMesh = function (mesh) {
  28610. var numOfMeshes = this._meshes.length;
  28611. // vertexBuffers
  28612. for (var kind in this._vertexBuffers) {
  28613. if (numOfMeshes === 1) {
  28614. this._vertexBuffers[kind].create();
  28615. }
  28616. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28617. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28618. mesh._resetPointsArrayCache();
  28619. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28620. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28621. mesh._createGlobalSubMesh();
  28622. //bounding info was just created again, world matrix should be applied again.
  28623. mesh._updateBoundingInfo();
  28624. }
  28625. }
  28626. // indexBuffer
  28627. if (numOfMeshes === 1 && this._indices) {
  28628. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28629. }
  28630. if (this._indexBuffer) {
  28631. this._indexBuffer.references = numOfMeshes;
  28632. }
  28633. };
  28634. Geometry.prototype.notifyUpdate = function (kind) {
  28635. if (this.onGeometryUpdated) {
  28636. this.onGeometryUpdated(this, kind);
  28637. }
  28638. };
  28639. Geometry.prototype.load = function (scene, onLoaded) {
  28640. var _this = this;
  28641. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28642. return;
  28643. }
  28644. if (this.isReady()) {
  28645. if (onLoaded) {
  28646. onLoaded();
  28647. }
  28648. return;
  28649. }
  28650. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28651. scene._addPendingData(this);
  28652. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28653. _this._delayLoadingFunction(JSON.parse(data), _this);
  28654. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28655. _this._delayInfo = [];
  28656. scene._removePendingData(_this);
  28657. var meshes = _this._meshes;
  28658. var numOfMeshes = meshes.length;
  28659. for (var index = 0; index < numOfMeshes; index++) {
  28660. _this._applyToMesh(meshes[index]);
  28661. }
  28662. if (onLoaded) {
  28663. onLoaded();
  28664. }
  28665. }, function () { }, scene.database);
  28666. };
  28667. Geometry.prototype.isDisposed = function () {
  28668. return this._isDisposed;
  28669. };
  28670. Geometry.prototype.dispose = function () {
  28671. var meshes = this._meshes;
  28672. var numOfMeshes = meshes.length;
  28673. var index;
  28674. for (index = 0; index < numOfMeshes; index++) {
  28675. this.releaseForMesh(meshes[index]);
  28676. }
  28677. this._meshes = [];
  28678. for (var kind in this._vertexBuffers) {
  28679. this._vertexBuffers[kind].dispose();
  28680. }
  28681. this._vertexBuffers = [];
  28682. this._totalVertices = 0;
  28683. if (this._indexBuffer) {
  28684. this._engine._releaseBuffer(this._indexBuffer);
  28685. }
  28686. this._indexBuffer = null;
  28687. this._indices = [];
  28688. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28689. this.delayLoadingFile = null;
  28690. this._delayLoadingFunction = null;
  28691. this._delayInfo = [];
  28692. this._boundingInfo = null; // todo: .dispose()
  28693. this._scene.removeGeometry(this);
  28694. this._isDisposed = true;
  28695. };
  28696. Geometry.prototype.copy = function (id) {
  28697. var vertexData = new BABYLON.VertexData();
  28698. vertexData.indices = [];
  28699. var indices = this.getIndices();
  28700. for (var index = 0; index < indices.length; index++) {
  28701. vertexData.indices.push(indices[index]);
  28702. }
  28703. var updatable = false;
  28704. var stopChecking = false;
  28705. for (var kind in this._vertexBuffers) {
  28706. // using slice() to make a copy of the array and not just reference it
  28707. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  28708. if (!stopChecking) {
  28709. updatable = this.getVertexBuffer(kind).isUpdatable();
  28710. stopChecking = !updatable;
  28711. }
  28712. }
  28713. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28714. geometry.delayLoadState = this.delayLoadState;
  28715. geometry.delayLoadingFile = this.delayLoadingFile;
  28716. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28717. for (kind in this._delayInfo) {
  28718. geometry._delayInfo = geometry._delayInfo || [];
  28719. geometry._delayInfo.push(kind);
  28720. }
  28721. // Bounding info
  28722. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  28723. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28724. return geometry;
  28725. };
  28726. // Statics
  28727. Geometry.ExtractFromMesh = function (mesh, id) {
  28728. var geometry = mesh._geometry;
  28729. if (!geometry) {
  28730. return null;
  28731. }
  28732. return geometry.copy(id);
  28733. };
  28734. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28735. // be aware Math.random() could cause collisions
  28736. Geometry.RandomId = function () {
  28737. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28738. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28739. return v.toString(16);
  28740. });
  28741. };
  28742. return Geometry;
  28743. })();
  28744. BABYLON.Geometry = Geometry;
  28745. /////// Primitives //////////////////////////////////////////////
  28746. var Geometry;
  28747. (function (Geometry) {
  28748. var Primitives;
  28749. (function (Primitives) {
  28750. /// Abstract class
  28751. var _Primitive = (function (_super) {
  28752. __extends(_Primitive, _super);
  28753. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  28754. this._beingRegenerated = true;
  28755. this._canBeRegenerated = canBeRegenerated;
  28756. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  28757. this._beingRegenerated = false;
  28758. }
  28759. _Primitive.prototype.canBeRegenerated = function () {
  28760. return this._canBeRegenerated;
  28761. };
  28762. _Primitive.prototype.regenerate = function () {
  28763. if (!this._canBeRegenerated) {
  28764. return;
  28765. }
  28766. this._beingRegenerated = true;
  28767. this.setAllVerticesData(this._regenerateVertexData(), false);
  28768. this._beingRegenerated = false;
  28769. };
  28770. _Primitive.prototype.asNewGeometry = function (id) {
  28771. return _super.prototype.copy.call(this, id);
  28772. };
  28773. // overrides
  28774. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28775. if (!this._beingRegenerated) {
  28776. return;
  28777. }
  28778. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28779. };
  28780. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28781. if (!this._beingRegenerated) {
  28782. return;
  28783. }
  28784. _super.prototype.setVerticesData.call(this, kind, data, false);
  28785. };
  28786. // to override
  28787. // protected
  28788. _Primitive.prototype._regenerateVertexData = function () {
  28789. throw new Error("Abstract method");
  28790. };
  28791. _Primitive.prototype.copy = function (id) {
  28792. throw new Error("Must be overriden in sub-classes.");
  28793. };
  28794. return _Primitive;
  28795. })(Geometry);
  28796. Primitives._Primitive = _Primitive;
  28797. var Ribbon = (function (_super) {
  28798. __extends(Ribbon, _super);
  28799. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28800. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28801. this.pathArray = pathArray;
  28802. this.closeArray = closeArray;
  28803. this.closePath = closePath;
  28804. this.offset = offset;
  28805. this.side = side;
  28806. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28807. }
  28808. Ribbon.prototype._regenerateVertexData = function () {
  28809. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  28810. };
  28811. Ribbon.prototype.copy = function (id) {
  28812. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28813. };
  28814. return Ribbon;
  28815. })(_Primitive);
  28816. Primitives.Ribbon = Ribbon;
  28817. var Box = (function (_super) {
  28818. __extends(Box, _super);
  28819. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28820. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28821. this.size = size;
  28822. this.side = side;
  28823. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28824. }
  28825. Box.prototype._regenerateVertexData = function () {
  28826. return BABYLON.VertexData.CreateBox(this.size, this.side);
  28827. };
  28828. Box.prototype.copy = function (id) {
  28829. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28830. };
  28831. return Box;
  28832. })(_Primitive);
  28833. Primitives.Box = Box;
  28834. var Sphere = (function (_super) {
  28835. __extends(Sphere, _super);
  28836. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28837. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28838. this.segments = segments;
  28839. this.diameter = diameter;
  28840. this.side = side;
  28841. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28842. }
  28843. Sphere.prototype._regenerateVertexData = function () {
  28844. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  28845. };
  28846. Sphere.prototype.copy = function (id) {
  28847. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28848. };
  28849. return Sphere;
  28850. })(_Primitive);
  28851. Primitives.Sphere = Sphere;
  28852. var Cylinder = (function (_super) {
  28853. __extends(Cylinder, _super);
  28854. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28855. if (subdivisions === void 0) { subdivisions = 1; }
  28856. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28857. this.height = height;
  28858. this.diameterTop = diameterTop;
  28859. this.diameterBottom = diameterBottom;
  28860. this.tessellation = tessellation;
  28861. this.subdivisions = subdivisions;
  28862. this.side = side;
  28863. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28864. }
  28865. Cylinder.prototype._regenerateVertexData = function () {
  28866. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  28867. };
  28868. Cylinder.prototype.copy = function (id) {
  28869. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28870. };
  28871. return Cylinder;
  28872. })(_Primitive);
  28873. Primitives.Cylinder = Cylinder;
  28874. var Torus = (function (_super) {
  28875. __extends(Torus, _super);
  28876. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28877. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28878. this.diameter = diameter;
  28879. this.thickness = thickness;
  28880. this.tessellation = tessellation;
  28881. this.side = side;
  28882. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28883. }
  28884. Torus.prototype._regenerateVertexData = function () {
  28885. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  28886. };
  28887. Torus.prototype.copy = function (id) {
  28888. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28889. };
  28890. return Torus;
  28891. })(_Primitive);
  28892. Primitives.Torus = Torus;
  28893. var Ground = (function (_super) {
  28894. __extends(Ground, _super);
  28895. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28896. this.width = width;
  28897. this.height = height;
  28898. this.subdivisions = subdivisions;
  28899. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28900. }
  28901. Ground.prototype._regenerateVertexData = function () {
  28902. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  28903. };
  28904. Ground.prototype.copy = function (id) {
  28905. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28906. };
  28907. return Ground;
  28908. })(_Primitive);
  28909. Primitives.Ground = Ground;
  28910. var TiledGround = (function (_super) {
  28911. __extends(TiledGround, _super);
  28912. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28913. this.xmin = xmin;
  28914. this.zmin = zmin;
  28915. this.xmax = xmax;
  28916. this.zmax = zmax;
  28917. this.subdivisions = subdivisions;
  28918. this.precision = precision;
  28919. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28920. }
  28921. TiledGround.prototype._regenerateVertexData = function () {
  28922. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  28923. };
  28924. TiledGround.prototype.copy = function (id) {
  28925. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28926. };
  28927. return TiledGround;
  28928. })(_Primitive);
  28929. Primitives.TiledGround = TiledGround;
  28930. var Plane = (function (_super) {
  28931. __extends(Plane, _super);
  28932. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28934. this.size = size;
  28935. this.side = side;
  28936. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28937. }
  28938. Plane.prototype._regenerateVertexData = function () {
  28939. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  28940. };
  28941. Plane.prototype.copy = function (id) {
  28942. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28943. };
  28944. return Plane;
  28945. })(_Primitive);
  28946. Primitives.Plane = Plane;
  28947. var TorusKnot = (function (_super) {
  28948. __extends(TorusKnot, _super);
  28949. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28950. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28951. this.radius = radius;
  28952. this.tube = tube;
  28953. this.radialSegments = radialSegments;
  28954. this.tubularSegments = tubularSegments;
  28955. this.p = p;
  28956. this.q = q;
  28957. this.side = side;
  28958. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28959. }
  28960. TorusKnot.prototype._regenerateVertexData = function () {
  28961. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  28962. };
  28963. TorusKnot.prototype.copy = function (id) {
  28964. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28965. };
  28966. return TorusKnot;
  28967. })(_Primitive);
  28968. Primitives.TorusKnot = TorusKnot;
  28969. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28970. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28971. })(BABYLON || (BABYLON = {}));
  28972. var BABYLON;
  28973. (function (BABYLON) {
  28974. var GroundMesh = (function (_super) {
  28975. __extends(GroundMesh, _super);
  28976. function GroundMesh(name, scene) {
  28977. _super.call(this, name, scene);
  28978. this.generateOctree = false;
  28979. this._worldInverse = new BABYLON.Matrix();
  28980. }
  28981. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28982. get: function () {
  28983. return this._subdivisions;
  28984. },
  28985. enumerable: true,
  28986. configurable: true
  28987. });
  28988. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28989. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28990. this._subdivisions = chunksCount;
  28991. this.subdivide(this._subdivisions);
  28992. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28993. };
  28994. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28995. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  28996. this.getWorldMatrix().invertToRef(this._worldInverse);
  28997. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  28998. var pickInfo = this.intersects(ray);
  28999. if (pickInfo.hit) {
  29000. return pickInfo.pickedPoint.y;
  29001. }
  29002. return 0;
  29003. };
  29004. return GroundMesh;
  29005. })(BABYLON.Mesh);
  29006. BABYLON.GroundMesh = GroundMesh;
  29007. })(BABYLON || (BABYLON = {}));
  29008. var BABYLON;
  29009. (function (BABYLON) {
  29010. var LinesMesh = (function (_super) {
  29011. __extends(LinesMesh, _super);
  29012. function LinesMesh(name, scene, updatable) {
  29013. if (updatable === void 0) { updatable = false; }
  29014. _super.call(this, name, scene);
  29015. this.color = new BABYLON.Color3(1, 1, 1);
  29016. this.alpha = 1;
  29017. this._indices = new Array();
  29018. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  29019. attributes: ["position"],
  29020. uniforms: ["worldViewProjection", "color"],
  29021. needAlphaBlending: true
  29022. });
  29023. }
  29024. Object.defineProperty(LinesMesh.prototype, "material", {
  29025. get: function () {
  29026. return this._colorShader;
  29027. },
  29028. enumerable: true,
  29029. configurable: true
  29030. });
  29031. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  29032. get: function () {
  29033. return false;
  29034. },
  29035. enumerable: true,
  29036. configurable: true
  29037. });
  29038. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  29039. get: function () {
  29040. return false;
  29041. },
  29042. enumerable: true,
  29043. configurable: true
  29044. });
  29045. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  29046. var engine = this.getScene().getEngine();
  29047. var indexToBind = this._geometry.getIndexBuffer();
  29048. // VBOs
  29049. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  29050. // Color
  29051. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  29052. };
  29053. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  29054. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  29055. return;
  29056. }
  29057. var engine = this.getScene().getEngine();
  29058. // Draw order
  29059. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  29060. };
  29061. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  29062. return null;
  29063. };
  29064. LinesMesh.prototype.dispose = function (doNotRecurse) {
  29065. this._colorShader.dispose();
  29066. _super.prototype.dispose.call(this, doNotRecurse);
  29067. };
  29068. return LinesMesh;
  29069. })(BABYLON.Mesh);
  29070. BABYLON.LinesMesh = LinesMesh;
  29071. })(BABYLON || (BABYLON = {}));
  29072. var BABYLON;
  29073. (function (BABYLON) {
  29074. var OutlineRenderer = (function () {
  29075. function OutlineRenderer(scene) {
  29076. this._scene = scene;
  29077. }
  29078. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  29079. var _this = this;
  29080. if (useOverlay === void 0) { useOverlay = false; }
  29081. var scene = this._scene;
  29082. var engine = this._scene.getEngine();
  29083. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29084. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29085. return;
  29086. }
  29087. var mesh = subMesh.getRenderingMesh();
  29088. var material = subMesh.getMaterial();
  29089. engine.enableEffect(this._effect);
  29090. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29091. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29092. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29093. // Bones
  29094. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29095. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29096. }
  29097. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29098. // Alpha test
  29099. if (material && material.needAlphaTesting()) {
  29100. var alphaTexture = material.getAlphaTestTexture();
  29101. this._effect.setTexture("diffuseSampler", alphaTexture);
  29102. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29103. }
  29104. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29105. };
  29106. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29107. var defines = [];
  29108. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29109. var mesh = subMesh.getMesh();
  29110. var material = subMesh.getMaterial();
  29111. // Alpha test
  29112. if (material && material.needAlphaTesting()) {
  29113. defines.push("#define ALPHATEST");
  29114. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29115. attribs.push(BABYLON.VertexBuffer.UVKind);
  29116. defines.push("#define UV1");
  29117. }
  29118. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29119. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29120. defines.push("#define UV2");
  29121. }
  29122. }
  29123. // Bones
  29124. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29125. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29126. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29127. defines.push("#define BONES");
  29128. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29129. }
  29130. // Instances
  29131. if (useInstances) {
  29132. defines.push("#define INSTANCES");
  29133. attribs.push("world0");
  29134. attribs.push("world1");
  29135. attribs.push("world2");
  29136. attribs.push("world3");
  29137. }
  29138. // Get correct effect
  29139. var join = defines.join("\n");
  29140. if (this._cachedDefines !== join) {
  29141. this._cachedDefines = join;
  29142. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29143. }
  29144. return this._effect.isReady();
  29145. };
  29146. return OutlineRenderer;
  29147. })();
  29148. BABYLON.OutlineRenderer = OutlineRenderer;
  29149. })(BABYLON || (BABYLON = {}));
  29150. var BABYLON;
  29151. (function (BABYLON) {
  29152. var MeshAssetTask = (function () {
  29153. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29154. this.name = name;
  29155. this.meshesNames = meshesNames;
  29156. this.rootUrl = rootUrl;
  29157. this.sceneFilename = sceneFilename;
  29158. this.isCompleted = false;
  29159. }
  29160. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29161. var _this = this;
  29162. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29163. _this.loadedMeshes = meshes;
  29164. _this.loadedParticleSystems = particleSystems;
  29165. _this.loadedSkeletons = skeletons;
  29166. _this.isCompleted = true;
  29167. if (_this.onSuccess) {
  29168. _this.onSuccess(_this);
  29169. }
  29170. onSuccess();
  29171. }, null, function () {
  29172. if (_this.onError) {
  29173. _this.onError(_this);
  29174. }
  29175. onError();
  29176. });
  29177. };
  29178. return MeshAssetTask;
  29179. })();
  29180. BABYLON.MeshAssetTask = MeshAssetTask;
  29181. var TextFileAssetTask = (function () {
  29182. function TextFileAssetTask(name, url) {
  29183. this.name = name;
  29184. this.url = url;
  29185. this.isCompleted = false;
  29186. }
  29187. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29188. var _this = this;
  29189. BABYLON.Tools.LoadFile(this.url, function (data) {
  29190. _this.text = data;
  29191. _this.isCompleted = true;
  29192. if (_this.onSuccess) {
  29193. _this.onSuccess(_this);
  29194. }
  29195. onSuccess();
  29196. }, null, scene.database, false, function () {
  29197. if (_this.onError) {
  29198. _this.onError(_this);
  29199. }
  29200. onError();
  29201. });
  29202. };
  29203. return TextFileAssetTask;
  29204. })();
  29205. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29206. var BinaryFileAssetTask = (function () {
  29207. function BinaryFileAssetTask(name, url) {
  29208. this.name = name;
  29209. this.url = url;
  29210. this.isCompleted = false;
  29211. }
  29212. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29213. var _this = this;
  29214. BABYLON.Tools.LoadFile(this.url, function (data) {
  29215. _this.data = data;
  29216. _this.isCompleted = true;
  29217. if (_this.onSuccess) {
  29218. _this.onSuccess(_this);
  29219. }
  29220. onSuccess();
  29221. }, null, scene.database, true, function () {
  29222. if (_this.onError) {
  29223. _this.onError(_this);
  29224. }
  29225. onError();
  29226. });
  29227. };
  29228. return BinaryFileAssetTask;
  29229. })();
  29230. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29231. var ImageAssetTask = (function () {
  29232. function ImageAssetTask(name, url) {
  29233. this.name = name;
  29234. this.url = url;
  29235. this.isCompleted = false;
  29236. }
  29237. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29238. var _this = this;
  29239. var img = new Image();
  29240. img.onload = function () {
  29241. _this.image = img;
  29242. _this.isCompleted = true;
  29243. if (_this.onSuccess) {
  29244. _this.onSuccess(_this);
  29245. }
  29246. onSuccess();
  29247. };
  29248. img.onerror = function () {
  29249. if (_this.onError) {
  29250. _this.onError(_this);
  29251. }
  29252. onError();
  29253. };
  29254. img.src = this.url;
  29255. };
  29256. return ImageAssetTask;
  29257. })();
  29258. BABYLON.ImageAssetTask = ImageAssetTask;
  29259. var TextureAssetTask = (function () {
  29260. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29261. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29262. this.name = name;
  29263. this.url = url;
  29264. this.noMipmap = noMipmap;
  29265. this.invertY = invertY;
  29266. this.samplingMode = samplingMode;
  29267. this.isCompleted = false;
  29268. }
  29269. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29270. var _this = this;
  29271. var onload = function () {
  29272. _this.isCompleted = true;
  29273. if (_this.onSuccess) {
  29274. _this.onSuccess(_this);
  29275. }
  29276. onSuccess();
  29277. };
  29278. var onerror = function () {
  29279. if (_this.onError) {
  29280. _this.onError(_this);
  29281. }
  29282. onError();
  29283. };
  29284. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29285. };
  29286. return TextureAssetTask;
  29287. })();
  29288. BABYLON.TextureAssetTask = TextureAssetTask;
  29289. var AssetsManager = (function () {
  29290. function AssetsManager(scene) {
  29291. this._tasks = new Array();
  29292. this._waitingTasksCount = 0;
  29293. this.useDefaultLoadingScreen = true;
  29294. this._scene = scene;
  29295. }
  29296. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29297. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29298. this._tasks.push(task);
  29299. return task;
  29300. };
  29301. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29302. var task = new TextFileAssetTask(taskName, url);
  29303. this._tasks.push(task);
  29304. return task;
  29305. };
  29306. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29307. var task = new BinaryFileAssetTask(taskName, url);
  29308. this._tasks.push(task);
  29309. return task;
  29310. };
  29311. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29312. var task = new ImageAssetTask(taskName, url);
  29313. this._tasks.push(task);
  29314. return task;
  29315. };
  29316. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29317. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29318. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29319. this._tasks.push(task);
  29320. return task;
  29321. };
  29322. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29323. this._waitingTasksCount--;
  29324. if (this._waitingTasksCount === 0) {
  29325. if (this.onFinish) {
  29326. this.onFinish(this._tasks);
  29327. }
  29328. this._scene.getEngine().hideLoadingUI();
  29329. }
  29330. };
  29331. AssetsManager.prototype._runTask = function (task) {
  29332. var _this = this;
  29333. task.run(this._scene, function () {
  29334. if (_this.onTaskSuccess) {
  29335. _this.onTaskSuccess(task);
  29336. }
  29337. _this._decreaseWaitingTasksCount();
  29338. }, function () {
  29339. if (_this.onTaskError) {
  29340. _this.onTaskError(task);
  29341. }
  29342. _this._decreaseWaitingTasksCount();
  29343. });
  29344. };
  29345. AssetsManager.prototype.reset = function () {
  29346. this._tasks = new Array();
  29347. return this;
  29348. };
  29349. AssetsManager.prototype.load = function () {
  29350. this._waitingTasksCount = this._tasks.length;
  29351. if (this._waitingTasksCount === 0) {
  29352. if (this.onFinish) {
  29353. this.onFinish(this._tasks);
  29354. }
  29355. return this;
  29356. }
  29357. if (this.useDefaultLoadingScreen) {
  29358. this._scene.getEngine().displayLoadingUI();
  29359. }
  29360. for (var index = 0; index < this._tasks.length; index++) {
  29361. var task = this._tasks[index];
  29362. this._runTask(task);
  29363. }
  29364. return this;
  29365. };
  29366. return AssetsManager;
  29367. })();
  29368. BABYLON.AssetsManager = AssetsManager;
  29369. })(BABYLON || (BABYLON = {}));
  29370. var BABYLON;
  29371. (function (BABYLON) {
  29372. var VRDeviceOrientationFreeCamera = (function (_super) {
  29373. __extends(VRDeviceOrientationFreeCamera, _super);
  29374. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  29375. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29376. _super.call(this, name, position, scene);
  29377. this._alpha = 0;
  29378. this._beta = 0;
  29379. this._gamma = 0;
  29380. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29381. metrics.compensateDistorsion = compensateDistorsion;
  29382. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29383. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  29384. }
  29385. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  29386. this._alpha = +evt.alpha | 0;
  29387. this._beta = +evt.beta | 0;
  29388. this._gamma = +evt.gamma | 0;
  29389. if (this._gamma < 0) {
  29390. this._gamma = 90 + this._gamma;
  29391. }
  29392. else {
  29393. // Incline it in the correct angle.
  29394. this._gamma = 270 - this._gamma;
  29395. }
  29396. this.rotation.x = this._gamma / 180.0 * Math.PI;
  29397. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  29398. this.rotation.z = this._beta / 180.0 * Math.PI;
  29399. };
  29400. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29401. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29402. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  29403. };
  29404. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  29405. _super.prototype.detachControl.call(this, element);
  29406. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  29407. };
  29408. return VRDeviceOrientationFreeCamera;
  29409. })(BABYLON.FreeCamera);
  29410. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  29411. })(BABYLON || (BABYLON = {}));
  29412. var BABYLON;
  29413. (function (BABYLON) {
  29414. var WebVRFreeCamera = (function (_super) {
  29415. __extends(WebVRFreeCamera, _super);
  29416. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  29417. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29418. _super.call(this, name, position, scene);
  29419. this._hmdDevice = null;
  29420. this._sensorDevice = null;
  29421. this._cacheState = null;
  29422. this._cacheQuaternion = new BABYLON.Quaternion();
  29423. this._cacheRotation = BABYLON.Vector3.Zero();
  29424. this._vrEnabled = false;
  29425. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29426. metrics.compensateDistorsion = compensateDistorsion;
  29427. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29428. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  29429. }
  29430. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  29431. var size = devices.length;
  29432. var i = 0;
  29433. // Reset devices.
  29434. this._sensorDevice = null;
  29435. this._hmdDevice = null;
  29436. // Search for a HmdDevice.
  29437. while (i < size && this._hmdDevice === null) {
  29438. if (devices[i] instanceof HMDVRDevice) {
  29439. this._hmdDevice = devices[i];
  29440. }
  29441. i++;
  29442. }
  29443. i = 0;
  29444. while (i < size && this._sensorDevice === null) {
  29445. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  29446. this._sensorDevice = devices[i];
  29447. }
  29448. i++;
  29449. }
  29450. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  29451. };
  29452. WebVRFreeCamera.prototype._checkInputs = function () {
  29453. if (this._vrEnabled) {
  29454. this._cacheState = this._sensorDevice.getState();
  29455. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  29456. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  29457. this.rotation.x = -this._cacheRotation.z;
  29458. this.rotation.y = -this._cacheRotation.y;
  29459. this.rotation.z = this._cacheRotation.x;
  29460. }
  29461. _super.prototype._checkInputs.call(this);
  29462. };
  29463. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29464. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29465. if (navigator.getVRDevices) {
  29466. navigator.getVRDevices().then(this._getWebVRDevices);
  29467. }
  29468. else if (navigator.mozGetVRDevices) {
  29469. navigator.mozGetVRDevices(this._getWebVRDevices);
  29470. }
  29471. };
  29472. WebVRFreeCamera.prototype.detachControl = function (element) {
  29473. _super.prototype.detachControl.call(this, element);
  29474. this._vrEnabled = false;
  29475. };
  29476. return WebVRFreeCamera;
  29477. })(BABYLON.FreeCamera);
  29478. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  29479. })(BABYLON || (BABYLON = {}));
  29480. var BABYLON;
  29481. (function (BABYLON) {
  29482. // Standard optimizations
  29483. var SceneOptimization = (function () {
  29484. function SceneOptimization(priority) {
  29485. if (priority === void 0) { priority = 0; }
  29486. this.priority = priority;
  29487. this.apply = function (scene) {
  29488. return true; // Return true if everything that can be done was applied
  29489. };
  29490. }
  29491. return SceneOptimization;
  29492. })();
  29493. BABYLON.SceneOptimization = SceneOptimization;
  29494. var TextureOptimization = (function (_super) {
  29495. __extends(TextureOptimization, _super);
  29496. function TextureOptimization(priority, maximumSize) {
  29497. var _this = this;
  29498. if (priority === void 0) { priority = 0; }
  29499. if (maximumSize === void 0) { maximumSize = 1024; }
  29500. _super.call(this, priority);
  29501. this.priority = priority;
  29502. this.maximumSize = maximumSize;
  29503. this.apply = function (scene) {
  29504. var allDone = true;
  29505. for (var index = 0; index < scene.textures.length; index++) {
  29506. var texture = scene.textures[index];
  29507. if (!texture.canRescale) {
  29508. continue;
  29509. }
  29510. var currentSize = texture.getSize();
  29511. var maxDimension = Math.max(currentSize.width, currentSize.height);
  29512. if (maxDimension > _this.maximumSize) {
  29513. texture.scale(0.5);
  29514. allDone = false;
  29515. }
  29516. }
  29517. return allDone;
  29518. };
  29519. }
  29520. return TextureOptimization;
  29521. })(SceneOptimization);
  29522. BABYLON.TextureOptimization = TextureOptimization;
  29523. var HardwareScalingOptimization = (function (_super) {
  29524. __extends(HardwareScalingOptimization, _super);
  29525. function HardwareScalingOptimization(priority, maximumScale) {
  29526. var _this = this;
  29527. if (priority === void 0) { priority = 0; }
  29528. if (maximumScale === void 0) { maximumScale = 2; }
  29529. _super.call(this, priority);
  29530. this.priority = priority;
  29531. this.maximumScale = maximumScale;
  29532. this._currentScale = 1;
  29533. this.apply = function (scene) {
  29534. _this._currentScale++;
  29535. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  29536. return _this._currentScale >= _this.maximumScale;
  29537. };
  29538. }
  29539. return HardwareScalingOptimization;
  29540. })(SceneOptimization);
  29541. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  29542. var ShadowsOptimization = (function (_super) {
  29543. __extends(ShadowsOptimization, _super);
  29544. function ShadowsOptimization() {
  29545. _super.apply(this, arguments);
  29546. this.apply = function (scene) {
  29547. scene.shadowsEnabled = false;
  29548. return true;
  29549. };
  29550. }
  29551. return ShadowsOptimization;
  29552. })(SceneOptimization);
  29553. BABYLON.ShadowsOptimization = ShadowsOptimization;
  29554. var PostProcessesOptimization = (function (_super) {
  29555. __extends(PostProcessesOptimization, _super);
  29556. function PostProcessesOptimization() {
  29557. _super.apply(this, arguments);
  29558. this.apply = function (scene) {
  29559. scene.postProcessesEnabled = false;
  29560. return true;
  29561. };
  29562. }
  29563. return PostProcessesOptimization;
  29564. })(SceneOptimization);
  29565. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  29566. var LensFlaresOptimization = (function (_super) {
  29567. __extends(LensFlaresOptimization, _super);
  29568. function LensFlaresOptimization() {
  29569. _super.apply(this, arguments);
  29570. this.apply = function (scene) {
  29571. scene.lensFlaresEnabled = false;
  29572. return true;
  29573. };
  29574. }
  29575. return LensFlaresOptimization;
  29576. })(SceneOptimization);
  29577. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  29578. var ParticlesOptimization = (function (_super) {
  29579. __extends(ParticlesOptimization, _super);
  29580. function ParticlesOptimization() {
  29581. _super.apply(this, arguments);
  29582. this.apply = function (scene) {
  29583. scene.particlesEnabled = false;
  29584. return true;
  29585. };
  29586. }
  29587. return ParticlesOptimization;
  29588. })(SceneOptimization);
  29589. BABYLON.ParticlesOptimization = ParticlesOptimization;
  29590. var RenderTargetsOptimization = (function (_super) {
  29591. __extends(RenderTargetsOptimization, _super);
  29592. function RenderTargetsOptimization() {
  29593. _super.apply(this, arguments);
  29594. this.apply = function (scene) {
  29595. scene.renderTargetsEnabled = false;
  29596. return true;
  29597. };
  29598. }
  29599. return RenderTargetsOptimization;
  29600. })(SceneOptimization);
  29601. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  29602. var MergeMeshesOptimization = (function (_super) {
  29603. __extends(MergeMeshesOptimization, _super);
  29604. function MergeMeshesOptimization() {
  29605. var _this = this;
  29606. _super.apply(this, arguments);
  29607. this._canBeMerged = function (abstractMesh) {
  29608. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  29609. return false;
  29610. }
  29611. var mesh = abstractMesh;
  29612. if (!mesh.isVisible || !mesh.isEnabled()) {
  29613. return false;
  29614. }
  29615. if (mesh.instances.length > 0) {
  29616. return false;
  29617. }
  29618. if (mesh.skeleton || mesh.hasLODLevels) {
  29619. return false;
  29620. }
  29621. return true;
  29622. };
  29623. this.apply = function (scene, updateSelectionTree) {
  29624. var globalPool = scene.meshes.slice(0);
  29625. var globalLength = globalPool.length;
  29626. for (var index = 0; index < globalLength; index++) {
  29627. var currentPool = new Array();
  29628. var current = globalPool[index];
  29629. // Checks
  29630. if (!_this._canBeMerged(current)) {
  29631. continue;
  29632. }
  29633. currentPool.push(current);
  29634. // Find compatible meshes
  29635. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  29636. var otherMesh = globalPool[subIndex];
  29637. if (!_this._canBeMerged(otherMesh)) {
  29638. continue;
  29639. }
  29640. if (otherMesh.material !== current.material) {
  29641. continue;
  29642. }
  29643. if (otherMesh.checkCollisions !== current.checkCollisions) {
  29644. continue;
  29645. }
  29646. currentPool.push(otherMesh);
  29647. globalLength--;
  29648. globalPool.splice(subIndex, 1);
  29649. subIndex--;
  29650. }
  29651. if (currentPool.length < 2) {
  29652. continue;
  29653. }
  29654. // Merge meshes
  29655. BABYLON.Mesh.MergeMeshes(currentPool);
  29656. }
  29657. if (updateSelectionTree != undefined) {
  29658. if (updateSelectionTree) {
  29659. scene.createOrUpdateSelectionOctree();
  29660. }
  29661. }
  29662. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  29663. scene.createOrUpdateSelectionOctree();
  29664. }
  29665. return true;
  29666. };
  29667. }
  29668. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  29669. get: function () {
  29670. return MergeMeshesOptimization._UpdateSelectionTree;
  29671. },
  29672. set: function (value) {
  29673. MergeMeshesOptimization._UpdateSelectionTree = value;
  29674. },
  29675. enumerable: true,
  29676. configurable: true
  29677. });
  29678. MergeMeshesOptimization._UpdateSelectionTree = false;
  29679. return MergeMeshesOptimization;
  29680. })(SceneOptimization);
  29681. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  29682. // Options
  29683. var SceneOptimizerOptions = (function () {
  29684. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  29685. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  29686. if (trackerDuration === void 0) { trackerDuration = 2000; }
  29687. this.targetFrameRate = targetFrameRate;
  29688. this.trackerDuration = trackerDuration;
  29689. this.optimizations = new Array();
  29690. }
  29691. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  29692. var result = new SceneOptimizerOptions(targetFrameRate);
  29693. var priority = 0;
  29694. result.optimizations.push(new MergeMeshesOptimization(priority));
  29695. result.optimizations.push(new ShadowsOptimization(priority));
  29696. result.optimizations.push(new LensFlaresOptimization(priority));
  29697. // Next priority
  29698. priority++;
  29699. result.optimizations.push(new PostProcessesOptimization(priority));
  29700. result.optimizations.push(new ParticlesOptimization(priority));
  29701. // Next priority
  29702. priority++;
  29703. result.optimizations.push(new TextureOptimization(priority, 1024));
  29704. return result;
  29705. };
  29706. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  29707. var result = new SceneOptimizerOptions(targetFrameRate);
  29708. var priority = 0;
  29709. result.optimizations.push(new MergeMeshesOptimization(priority));
  29710. result.optimizations.push(new ShadowsOptimization(priority));
  29711. result.optimizations.push(new LensFlaresOptimization(priority));
  29712. // Next priority
  29713. priority++;
  29714. result.optimizations.push(new PostProcessesOptimization(priority));
  29715. result.optimizations.push(new ParticlesOptimization(priority));
  29716. // Next priority
  29717. priority++;
  29718. result.optimizations.push(new TextureOptimization(priority, 512));
  29719. // Next priority
  29720. priority++;
  29721. result.optimizations.push(new RenderTargetsOptimization(priority));
  29722. // Next priority
  29723. priority++;
  29724. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  29725. return result;
  29726. };
  29727. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  29728. var result = new SceneOptimizerOptions(targetFrameRate);
  29729. var priority = 0;
  29730. result.optimizations.push(new MergeMeshesOptimization(priority));
  29731. result.optimizations.push(new ShadowsOptimization(priority));
  29732. result.optimizations.push(new LensFlaresOptimization(priority));
  29733. // Next priority
  29734. priority++;
  29735. result.optimizations.push(new PostProcessesOptimization(priority));
  29736. result.optimizations.push(new ParticlesOptimization(priority));
  29737. // Next priority
  29738. priority++;
  29739. result.optimizations.push(new TextureOptimization(priority, 256));
  29740. // Next priority
  29741. priority++;
  29742. result.optimizations.push(new RenderTargetsOptimization(priority));
  29743. // Next priority
  29744. priority++;
  29745. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  29746. return result;
  29747. };
  29748. return SceneOptimizerOptions;
  29749. })();
  29750. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  29751. // Scene optimizer tool
  29752. var SceneOptimizer = (function () {
  29753. function SceneOptimizer() {
  29754. }
  29755. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  29756. // TODO: add an epsilon
  29757. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  29758. if (onSuccess) {
  29759. onSuccess();
  29760. }
  29761. return;
  29762. }
  29763. // Apply current level of optimizations
  29764. var allDone = true;
  29765. var noOptimizationApplied = true;
  29766. for (var index = 0; index < options.optimizations.length; index++) {
  29767. var optimization = options.optimizations[index];
  29768. if (optimization.priority === currentPriorityLevel) {
  29769. noOptimizationApplied = false;
  29770. allDone = allDone && optimization.apply(scene);
  29771. }
  29772. }
  29773. // If no optimization was applied, this is a failure :(
  29774. if (noOptimizationApplied) {
  29775. if (onFailure) {
  29776. onFailure();
  29777. }
  29778. return;
  29779. }
  29780. // If all optimizations were done, move to next level
  29781. if (allDone) {
  29782. currentPriorityLevel++;
  29783. }
  29784. // Let's the system running for a specific amount of time before checking FPS
  29785. scene.executeWhenReady(function () {
  29786. setTimeout(function () {
  29787. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  29788. }, options.trackerDuration);
  29789. });
  29790. };
  29791. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  29792. if (!options) {
  29793. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  29794. }
  29795. // Let's the system running for a specific amount of time before checking FPS
  29796. scene.executeWhenReady(function () {
  29797. setTimeout(function () {
  29798. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  29799. }, options.trackerDuration);
  29800. });
  29801. };
  29802. return SceneOptimizer;
  29803. })();
  29804. BABYLON.SceneOptimizer = SceneOptimizer;
  29805. })(BABYLON || (BABYLON = {}));
  29806. var BABYLON;
  29807. (function (BABYLON) {
  29808. var Internals;
  29809. (function (Internals) {
  29810. var MeshLODLevel = (function () {
  29811. function MeshLODLevel(distance, mesh) {
  29812. this.distance = distance;
  29813. this.mesh = mesh;
  29814. }
  29815. return MeshLODLevel;
  29816. })();
  29817. Internals.MeshLODLevel = MeshLODLevel;
  29818. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29819. })(BABYLON || (BABYLON = {}));
  29820. var BABYLON;
  29821. (function (BABYLON) {
  29822. var AudioEngine = (function () {
  29823. function AudioEngine() {
  29824. this._audioContext = null;
  29825. this._audioContextInitialized = false;
  29826. this.canUseWebAudio = false;
  29827. this.WarnedWebAudioUnsupported = false;
  29828. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  29829. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  29830. this.canUseWebAudio = true;
  29831. }
  29832. }
  29833. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  29834. get: function () {
  29835. if (!this._audioContextInitialized) {
  29836. this._initializeAudioContext();
  29837. }
  29838. return this._audioContext;
  29839. },
  29840. enumerable: true,
  29841. configurable: true
  29842. });
  29843. AudioEngine.prototype._initializeAudioContext = function () {
  29844. try {
  29845. if (this.canUseWebAudio) {
  29846. this._audioContext = new AudioContext();
  29847. // create a global volume gain node
  29848. this.masterGain = this._audioContext.createGain();
  29849. this.masterGain.gain.value = 1;
  29850. this.masterGain.connect(this._audioContext.destination);
  29851. this._audioContextInitialized = true;
  29852. }
  29853. }
  29854. catch (e) {
  29855. this.canUseWebAudio = false;
  29856. BABYLON.Tools.Error("Web Audio: " + e.message);
  29857. }
  29858. };
  29859. AudioEngine.prototype.dispose = function () {
  29860. if (this.canUseWebAudio && this._audioContextInitialized) {
  29861. if (this._connectedAnalyser) {
  29862. this._connectedAnalyser.stopDebugCanvas();
  29863. this._connectedAnalyser.dispose();
  29864. this.masterGain.disconnect();
  29865. this.masterGain.connect(this._audioContext.destination);
  29866. this._connectedAnalyser = null;
  29867. }
  29868. this.masterGain.gain.value = 1;
  29869. }
  29870. this.WarnedWebAudioUnsupported = false;
  29871. };
  29872. AudioEngine.prototype.getGlobalVolume = function () {
  29873. if (this.canUseWebAudio && this._audioContextInitialized) {
  29874. return this.masterGain.gain.value;
  29875. }
  29876. else {
  29877. return -1;
  29878. }
  29879. };
  29880. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  29881. if (this.canUseWebAudio && this._audioContextInitialized) {
  29882. this.masterGain.gain.value = newVolume;
  29883. }
  29884. };
  29885. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  29886. if (this._connectedAnalyser) {
  29887. this._connectedAnalyser.stopDebugCanvas();
  29888. }
  29889. if (this.canUseWebAudio && this._audioContextInitialized) {
  29890. this._connectedAnalyser = analyser;
  29891. this.masterGain.disconnect();
  29892. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  29893. }
  29894. };
  29895. return AudioEngine;
  29896. })();
  29897. BABYLON.AudioEngine = AudioEngine;
  29898. })(BABYLON || (BABYLON = {}));
  29899. var BABYLON;
  29900. (function (BABYLON) {
  29901. var Sound = (function () {
  29902. /**
  29903. * Create a sound and attach it to a scene
  29904. * @param name Name of your sound
  29905. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  29906. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  29907. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  29908. */
  29909. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  29910. var _this = this;
  29911. this.autoplay = false;
  29912. this.loop = false;
  29913. this.useCustomAttenuation = false;
  29914. this.spatialSound = false;
  29915. this.refDistance = 1;
  29916. this.rolloffFactor = 1;
  29917. this.maxDistance = 100;
  29918. this.distanceModel = "linear";
  29919. this._panningModel = "equalpower";
  29920. this._playbackRate = 1;
  29921. this._startTime = 0;
  29922. this._startOffset = 0;
  29923. this._position = BABYLON.Vector3.Zero();
  29924. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  29925. this._volume = 1;
  29926. this._isLoaded = false;
  29927. this._isReadyToPlay = false;
  29928. this.isPlaying = false;
  29929. this.isPaused = false;
  29930. this._isDirectional = false;
  29931. // Used if you'd like to create a directional sound.
  29932. // If not set, the sound will be omnidirectional
  29933. this._coneInnerAngle = 360;
  29934. this._coneOuterAngle = 360;
  29935. this._coneOuterGain = 0;
  29936. this.name = name;
  29937. this._scene = scene;
  29938. this._readyToPlayCallback = readyToPlayCallback;
  29939. // Default custom attenuation function is a linear attenuation
  29940. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  29941. if (currentDistance < maxDistance) {
  29942. return currentVolume * (1 - currentDistance / maxDistance);
  29943. }
  29944. else {
  29945. return 0;
  29946. }
  29947. };
  29948. if (options) {
  29949. this.autoplay = options.autoplay || false;
  29950. this.loop = options.loop || false;
  29951. // if volume === 0, we need another way to check this option
  29952. if (options.volume !== undefined) {
  29953. this._volume = options.volume;
  29954. }
  29955. this.spatialSound = options.spatialSound || false;
  29956. this.maxDistance = options.maxDistance || 100;
  29957. this.useCustomAttenuation = options.useCustomAttenuation || false;
  29958. this.rolloffFactor = options.rolloffFactor || 1;
  29959. this.refDistance = options.refDistance || 1;
  29960. this.distanceModel = options.distanceModel || "linear";
  29961. this._playbackRate = options.playbackRate || 1;
  29962. }
  29963. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29964. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  29965. this._soundGain.gain.value = this._volume;
  29966. this._inputAudioNode = this._soundGain;
  29967. this._ouputAudioNode = this._soundGain;
  29968. if (this.spatialSound) {
  29969. this._createSpatialParameters();
  29970. }
  29971. this._scene.mainSoundTrack.AddSound(this);
  29972. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29973. if (urlOrArrayBuffer) {
  29974. // If it's an URL
  29975. if (typeof (urlOrArrayBuffer) === "string") {
  29976. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  29977. }
  29978. else {
  29979. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29980. this._soundLoaded(urlOrArrayBuffer);
  29981. }
  29982. else {
  29983. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29984. }
  29985. }
  29986. }
  29987. }
  29988. else {
  29989. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29990. this._scene.mainSoundTrack.AddSound(this);
  29991. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29992. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29993. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  29994. }
  29995. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  29996. if (this._readyToPlayCallback) {
  29997. window.setTimeout(function () {
  29998. _this._readyToPlayCallback();
  29999. }, 1000);
  30000. }
  30001. }
  30002. }
  30003. Sound.prototype.dispose = function () {
  30004. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  30005. if (this.isPlaying) {
  30006. this.stop();
  30007. }
  30008. this._isReadyToPlay = false;
  30009. if (this.soundTrackId === -1) {
  30010. this._scene.mainSoundTrack.RemoveSound(this);
  30011. }
  30012. else {
  30013. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  30014. }
  30015. if (this._soundGain) {
  30016. this._soundGain.disconnect();
  30017. this._soundGain = null;
  30018. }
  30019. if (this._soundPanner) {
  30020. this._soundPanner.disconnect();
  30021. this._soundPanner = null;
  30022. }
  30023. if (this._soundSource) {
  30024. this._soundSource.disconnect();
  30025. this._soundSource = null;
  30026. }
  30027. this._audioBuffer = null;
  30028. if (this._connectedMesh) {
  30029. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  30030. this._connectedMesh = null;
  30031. }
  30032. }
  30033. };
  30034. Sound.prototype._soundLoaded = function (audioData) {
  30035. var _this = this;
  30036. this._isLoaded = true;
  30037. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  30038. _this._audioBuffer = buffer;
  30039. _this._isReadyToPlay = true;
  30040. if (_this.autoplay) {
  30041. _this.play();
  30042. }
  30043. if (_this._readyToPlayCallback) {
  30044. _this._readyToPlayCallback();
  30045. }
  30046. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  30047. };
  30048. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  30049. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30050. this._audioBuffer = audioBuffer;
  30051. this._isReadyToPlay = true;
  30052. }
  30053. };
  30054. Sound.prototype.updateOptions = function (options) {
  30055. if (options) {
  30056. this.loop = options.loop || this.loop;
  30057. this.maxDistance = options.maxDistance || this.maxDistance;
  30058. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  30059. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  30060. this.refDistance = options.refDistance || this.refDistance;
  30061. this.distanceModel = options.distanceModel || this.distanceModel;
  30062. this._playbackRate = options.playbackRate || this._playbackRate;
  30063. this._updateSpatialParameters();
  30064. if (this.isPlaying) {
  30065. this._soundSource.playbackRate.value = this._playbackRate;
  30066. }
  30067. }
  30068. };
  30069. Sound.prototype._createSpatialParameters = function () {
  30070. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30071. if (this._scene.headphone) {
  30072. this._panningModel = "HRTF";
  30073. }
  30074. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  30075. this._updateSpatialParameters();
  30076. this._soundPanner.connect(this._ouputAudioNode);
  30077. this._inputAudioNode = this._soundPanner;
  30078. }
  30079. };
  30080. Sound.prototype._updateSpatialParameters = function () {
  30081. if (this.spatialSound) {
  30082. if (this.useCustomAttenuation) {
  30083. // Tricks to disable in a way embedded Web Audio attenuation
  30084. this._soundPanner.distanceModel = "linear";
  30085. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30086. this._soundPanner.refDistance = 1;
  30087. this._soundPanner.rolloffFactor = 1;
  30088. this._soundPanner.panningModel = this._panningModel;
  30089. }
  30090. else {
  30091. this._soundPanner.distanceModel = this.distanceModel;
  30092. this._soundPanner.maxDistance = this.maxDistance;
  30093. this._soundPanner.refDistance = this.refDistance;
  30094. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30095. this._soundPanner.panningModel = this._panningModel;
  30096. }
  30097. }
  30098. };
  30099. Sound.prototype.switchPanningModelToHRTF = function () {
  30100. this._panningModel = "HRTF";
  30101. this._switchPanningModel();
  30102. };
  30103. Sound.prototype.switchPanningModelToEqualPower = function () {
  30104. this._panningModel = "equalpower";
  30105. this._switchPanningModel();
  30106. };
  30107. Sound.prototype._switchPanningModel = function () {
  30108. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30109. this._soundPanner.panningModel = this._panningModel;
  30110. }
  30111. };
  30112. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30113. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30114. this._ouputAudioNode.disconnect();
  30115. this._ouputAudioNode.connect(soundTrackAudioNode);
  30116. }
  30117. };
  30118. /**
  30119. * Transform this sound into a directional source
  30120. * @param coneInnerAngle Size of the inner cone in degree
  30121. * @param coneOuterAngle Size of the outer cone in degree
  30122. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30123. */
  30124. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30125. if (coneOuterAngle < coneInnerAngle) {
  30126. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30127. return;
  30128. }
  30129. this._coneInnerAngle = coneInnerAngle;
  30130. this._coneOuterAngle = coneOuterAngle;
  30131. this._coneOuterGain = coneOuterGain;
  30132. this._isDirectional = true;
  30133. if (this.isPlaying && this.loop) {
  30134. this.stop();
  30135. this.play();
  30136. }
  30137. };
  30138. Sound.prototype.setPosition = function (newPosition) {
  30139. this._position = newPosition;
  30140. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30141. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30142. }
  30143. };
  30144. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30145. this._localDirection = newLocalDirection;
  30146. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30147. this._updateDirection();
  30148. }
  30149. };
  30150. Sound.prototype._updateDirection = function () {
  30151. var mat = this._connectedMesh.getWorldMatrix();
  30152. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30153. direction.normalize();
  30154. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30155. };
  30156. Sound.prototype.updateDistanceFromListener = function () {
  30157. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30158. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30159. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30160. }
  30161. };
  30162. Sound.prototype.setAttenuationFunction = function (callback) {
  30163. this._customAttenuationFunction = callback;
  30164. };
  30165. /**
  30166. * Play the sound
  30167. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30168. */
  30169. Sound.prototype.play = function (time) {
  30170. var _this = this;
  30171. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30172. try {
  30173. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30174. if (!this._soundSource) {
  30175. if (this.spatialSound) {
  30176. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30177. if (this._isDirectional) {
  30178. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30179. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30180. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30181. if (this._connectedMesh) {
  30182. this._updateDirection();
  30183. }
  30184. else {
  30185. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30186. }
  30187. }
  30188. }
  30189. }
  30190. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30191. this._soundSource.buffer = this._audioBuffer;
  30192. this._soundSource.connect(this._inputAudioNode);
  30193. this._soundSource.loop = this.loop;
  30194. this._soundSource.playbackRate.value = this._playbackRate;
  30195. this._startTime = startTime;
  30196. this._soundSource.onended = function () { _this._onended(); };
  30197. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30198. this.isPlaying = true;
  30199. this.isPaused = false;
  30200. }
  30201. catch (ex) {
  30202. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30203. }
  30204. }
  30205. };
  30206. Sound.prototype._onended = function () {
  30207. this.isPlaying = false;
  30208. if (this.onended) {
  30209. this.onended();
  30210. }
  30211. };
  30212. /**
  30213. * Stop the sound
  30214. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30215. */
  30216. Sound.prototype.stop = function (time) {
  30217. if (this.isPlaying) {
  30218. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30219. this._soundSource.stop(stopTime);
  30220. this.isPlaying = false;
  30221. }
  30222. };
  30223. Sound.prototype.pause = function () {
  30224. if (this.isPlaying) {
  30225. this.stop(0);
  30226. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30227. this.isPaused = true;
  30228. }
  30229. };
  30230. Sound.prototype.setVolume = function (newVolume, time) {
  30231. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30232. if (time) {
  30233. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30234. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30235. }
  30236. else {
  30237. this._soundGain.gain.value = newVolume;
  30238. }
  30239. }
  30240. this._volume = newVolume;
  30241. };
  30242. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30243. this._playbackRate = newPlaybackRate;
  30244. if (this.isPlaying) {
  30245. this._soundSource.playbackRate.value = this._playbackRate;
  30246. }
  30247. };
  30248. Sound.prototype.getVolume = function () {
  30249. return this._volume;
  30250. };
  30251. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30252. var _this = this;
  30253. this._connectedMesh = meshToConnectTo;
  30254. if (!this.spatialSound) {
  30255. this.spatialSound = true;
  30256. this._createSpatialParameters();
  30257. if (this.isPlaying && this.loop) {
  30258. this.stop();
  30259. this.play();
  30260. }
  30261. }
  30262. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30263. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30264. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30265. };
  30266. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30267. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30268. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30269. this._updateDirection();
  30270. }
  30271. };
  30272. return Sound;
  30273. })();
  30274. BABYLON.Sound = Sound;
  30275. })(BABYLON || (BABYLON = {}));
  30276. var BABYLON;
  30277. (function (BABYLON) {
  30278. var SoundTrack = (function () {
  30279. function SoundTrack(scene, options) {
  30280. this.id = -1;
  30281. this._isMainTrack = false;
  30282. this._scene = scene;
  30283. this._audioEngine = BABYLON.Engine.audioEngine;
  30284. this.soundCollection = new Array();
  30285. if (this._audioEngine.canUseWebAudio) {
  30286. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30287. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30288. if (options) {
  30289. if (options.volume) {
  30290. this._outputAudioNode.gain.value = options.volume;
  30291. }
  30292. if (options.mainTrack) {
  30293. this._isMainTrack = options.mainTrack;
  30294. }
  30295. }
  30296. }
  30297. if (!this._isMainTrack) {
  30298. this._scene.soundTracks.push(this);
  30299. this.id = this._scene.soundTracks.length - 1;
  30300. }
  30301. }
  30302. SoundTrack.prototype.dispose = function () {
  30303. if (this._audioEngine.canUseWebAudio) {
  30304. if (this._connectedAnalyser) {
  30305. this._connectedAnalyser.stopDebugCanvas();
  30306. }
  30307. while (this.soundCollection.length) {
  30308. this.soundCollection[0].dispose();
  30309. }
  30310. if (this._outputAudioNode) {
  30311. this._outputAudioNode.disconnect();
  30312. }
  30313. this._outputAudioNode = null;
  30314. }
  30315. };
  30316. SoundTrack.prototype.AddSound = function (sound) {
  30317. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30318. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30319. }
  30320. if (sound.soundTrackId) {
  30321. if (sound.soundTrackId === -1) {
  30322. this._scene.mainSoundTrack.RemoveSound(sound);
  30323. }
  30324. else {
  30325. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30326. }
  30327. }
  30328. this.soundCollection.push(sound);
  30329. sound.soundTrackId = this.id;
  30330. };
  30331. SoundTrack.prototype.RemoveSound = function (sound) {
  30332. var index = this.soundCollection.indexOf(sound);
  30333. if (index !== -1) {
  30334. this.soundCollection.splice(index, 1);
  30335. }
  30336. };
  30337. SoundTrack.prototype.setVolume = function (newVolume) {
  30338. if (this._audioEngine.canUseWebAudio) {
  30339. this._outputAudioNode.gain.value = newVolume;
  30340. }
  30341. };
  30342. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30343. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30344. for (var i = 0; i < this.soundCollection.length; i++) {
  30345. this.soundCollection[i].switchPanningModelToHRTF();
  30346. }
  30347. }
  30348. };
  30349. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30350. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30351. for (var i = 0; i < this.soundCollection.length; i++) {
  30352. this.soundCollection[i].switchPanningModelToEqualPower();
  30353. }
  30354. }
  30355. };
  30356. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30357. if (this._connectedAnalyser) {
  30358. this._connectedAnalyser.stopDebugCanvas();
  30359. }
  30360. this._connectedAnalyser = analyser;
  30361. if (this._audioEngine.canUseWebAudio) {
  30362. this._outputAudioNode.disconnect();
  30363. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  30364. }
  30365. };
  30366. return SoundTrack;
  30367. })();
  30368. BABYLON.SoundTrack = SoundTrack;
  30369. })(BABYLON || (BABYLON = {}));
  30370. var BABYLON;
  30371. (function (BABYLON) {
  30372. var DebugLayer = (function () {
  30373. function DebugLayer(scene) {
  30374. var _this = this;
  30375. this._transformationMatrix = BABYLON.Matrix.Identity();
  30376. this._enabled = false;
  30377. this._labelsEnabled = false;
  30378. this._displayStatistics = true;
  30379. this._displayTree = false;
  30380. this._displayLogs = false;
  30381. this._identityMatrix = BABYLON.Matrix.Identity();
  30382. this.axisRatio = 0.02;
  30383. this.accentColor = "orange";
  30384. this._scene = scene;
  30385. this._syncPositions = function () {
  30386. var engine = _this._scene.getEngine();
  30387. var canvasRect = engine.getRenderingCanvasClientRect();
  30388. if (_this._showUI) {
  30389. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30390. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30391. _this._statsDiv.style.width = "400px";
  30392. _this._statsDiv.style.height = "auto";
  30393. _this._statsSubsetDiv.style.maxHeight = "240px";
  30394. _this._optionsDiv.style.left = "0px";
  30395. _this._optionsDiv.style.top = "10px";
  30396. _this._optionsDiv.style.width = "200px";
  30397. _this._optionsDiv.style.height = "auto";
  30398. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30399. _this._logDiv.style.left = "0px";
  30400. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30401. _this._logDiv.style.width = "600px";
  30402. _this._logDiv.style.height = "160px";
  30403. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30404. _this._treeDiv.style.top = "10px";
  30405. _this._treeDiv.style.width = "300px";
  30406. _this._treeDiv.style.height = "auto";
  30407. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30408. }
  30409. _this._globalDiv.style.left = canvasRect.left + "px";
  30410. _this._globalDiv.style.top = canvasRect.top + "px";
  30411. _this._drawingCanvas.style.left = "0px";
  30412. _this._drawingCanvas.style.top = "0px";
  30413. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30414. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30415. var devicePixelRatio = window.devicePixelRatio || 1;
  30416. var context = _this._drawingContext;
  30417. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30418. context.mozBackingStorePixelRatio ||
  30419. context.msBackingStorePixelRatio ||
  30420. context.oBackingStorePixelRatio ||
  30421. context.backingStorePixelRatio || 1;
  30422. _this._ratio = devicePixelRatio / backingStoreRatio;
  30423. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30424. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30425. };
  30426. this._onCanvasClick = function (evt) {
  30427. _this._clickPosition = {
  30428. x: evt.clientX * _this._ratio,
  30429. y: evt.clientY * _this._ratio
  30430. };
  30431. };
  30432. this._syncUI = function () {
  30433. if (_this._showUI) {
  30434. if (_this._displayStatistics) {
  30435. _this._displayStats();
  30436. _this._statsDiv.style.display = "";
  30437. }
  30438. else {
  30439. _this._statsDiv.style.display = "none";
  30440. }
  30441. if (_this._displayLogs) {
  30442. _this._logDiv.style.display = "";
  30443. }
  30444. else {
  30445. _this._logDiv.style.display = "none";
  30446. }
  30447. if (_this._displayTree) {
  30448. _this._treeDiv.style.display = "";
  30449. if (_this._needToRefreshMeshesTree) {
  30450. _this._needToRefreshMeshesTree = false;
  30451. _this._refreshMeshesTreeContent();
  30452. }
  30453. }
  30454. else {
  30455. _this._treeDiv.style.display = "none";
  30456. }
  30457. }
  30458. };
  30459. this._syncData = function () {
  30460. if (_this._labelsEnabled || !_this._showUI) {
  30461. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30462. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30463. var engine = _this._scene.getEngine();
  30464. var viewport = _this._camera.viewport;
  30465. var globalViewport = viewport.toGlobal(engine);
  30466. // Meshes
  30467. var meshes = _this._camera.getActiveMeshes();
  30468. for (var index = 0; index < meshes.length; index++) {
  30469. var mesh = meshes.data[index];
  30470. var position = mesh.getBoundingInfo().boundingSphere.center;
  30471. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30472. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30473. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30474. }
  30475. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30476. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30477. }
  30478. }
  30479. // Cameras
  30480. var cameras = _this._scene.cameras;
  30481. for (index = 0; index < cameras.length; index++) {
  30482. var camera = cameras[index];
  30483. if (camera === _this._camera) {
  30484. continue;
  30485. }
  30486. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30487. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30488. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30489. _this._camera.detachControl(engine.getRenderingCanvas());
  30490. _this._camera = camera;
  30491. _this._camera.attachControl(engine.getRenderingCanvas());
  30492. }, function () { return "purple"; });
  30493. }
  30494. }
  30495. // Lights
  30496. var lights = _this._scene.lights;
  30497. for (index = 0; index < lights.length; index++) {
  30498. var light = lights[index];
  30499. if (light.position) {
  30500. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30501. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30502. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30503. light.setEnabled(!light.isEnabled());
  30504. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30505. }
  30506. }
  30507. }
  30508. }
  30509. _this._clickPosition = undefined;
  30510. };
  30511. }
  30512. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30513. while (this._treeSubsetDiv.hasChildNodes()) {
  30514. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30515. }
  30516. // Add meshes
  30517. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30518. sortedArray.sort(function (a, b) {
  30519. if (a.name === b.name) {
  30520. return 0;
  30521. }
  30522. return (a.name > b.name) ? 1 : -1;
  30523. });
  30524. for (var index = 0; index < sortedArray.length; index++) {
  30525. var mesh = sortedArray[index];
  30526. if (!mesh.isEnabled()) {
  30527. continue;
  30528. }
  30529. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30530. m.isVisible = element.checked;
  30531. }, mesh);
  30532. }
  30533. };
  30534. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30535. this._drawingContext.beginPath();
  30536. this._drawingContext.moveTo(zero.x, zero.y);
  30537. this._drawingContext.lineTo(unit.x, unit.y);
  30538. this._drawingContext.strokeStyle = color;
  30539. this._drawingContext.lineWidth = 4;
  30540. this._drawingContext.stroke();
  30541. this._drawingContext.font = "normal 14px Segoe UI";
  30542. this._drawingContext.fillStyle = color;
  30543. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30544. };
  30545. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30546. var position = mesh.getBoundingInfo().boundingSphere.center;
  30547. var worldMatrix = mesh.getWorldMatrix();
  30548. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30549. var unit = (unprojectedVector.subtract(position)).length();
  30550. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30551. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30552. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30553. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30554. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30555. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30556. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30557. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30558. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30559. };
  30560. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30561. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30562. this._drawingContext.font = "normal 12px Segoe UI";
  30563. var textMetrics = this._drawingContext.measureText(text);
  30564. var centerX = projectedPosition.x - textMetrics.width / 2;
  30565. var centerY = projectedPosition.y;
  30566. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30567. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30568. onClick();
  30569. }
  30570. this._drawingContext.beginPath();
  30571. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30572. this._drawingContext.fillStyle = getFillStyle();
  30573. this._drawingContext.globalAlpha = 0.5;
  30574. this._drawingContext.fill();
  30575. this._drawingContext.globalAlpha = 1.0;
  30576. this._drawingContext.strokeStyle = '#FFFFFF';
  30577. this._drawingContext.lineWidth = 1;
  30578. this._drawingContext.stroke();
  30579. this._drawingContext.fillStyle = "#FFFFFF";
  30580. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30581. this._drawingContext.beginPath();
  30582. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30583. this._drawingContext.fill();
  30584. }
  30585. };
  30586. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30587. if (!this._clickPosition) {
  30588. return false;
  30589. }
  30590. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30591. return false;
  30592. }
  30593. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30594. return false;
  30595. }
  30596. return true;
  30597. };
  30598. DebugLayer.prototype.isVisible = function () {
  30599. return this._enabled;
  30600. };
  30601. DebugLayer.prototype.hide = function () {
  30602. if (!this._enabled) {
  30603. return;
  30604. }
  30605. this._enabled = false;
  30606. var engine = this._scene.getEngine();
  30607. this._scene.unregisterBeforeRender(this._syncData);
  30608. this._scene.unregisterAfterRender(this._syncUI);
  30609. document.body.removeChild(this._globalDiv);
  30610. window.removeEventListener("resize", this._syncPositions);
  30611. this._scene.forceShowBoundingBoxes = false;
  30612. this._scene.forceWireframe = false;
  30613. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30614. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30615. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30616. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30617. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30618. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30619. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30620. this._scene.shadowsEnabled = true;
  30621. this._scene.particlesEnabled = true;
  30622. this._scene.postProcessesEnabled = true;
  30623. this._scene.collisionsEnabled = true;
  30624. this._scene.lightsEnabled = true;
  30625. this._scene.texturesEnabled = true;
  30626. this._scene.lensFlaresEnabled = true;
  30627. this._scene.proceduralTexturesEnabled = true;
  30628. this._scene.renderTargetsEnabled = true;
  30629. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30630. };
  30631. DebugLayer.prototype.show = function (showUI, camera) {
  30632. if (showUI === void 0) { showUI = true; }
  30633. if (camera === void 0) { camera = null; }
  30634. if (this._enabled) {
  30635. return;
  30636. }
  30637. this._enabled = true;
  30638. if (camera) {
  30639. this._camera = camera;
  30640. }
  30641. else {
  30642. this._camera = this._scene.activeCamera;
  30643. }
  30644. this._showUI = showUI;
  30645. var engine = this._scene.getEngine();
  30646. this._globalDiv = document.createElement("div");
  30647. document.body.appendChild(this._globalDiv);
  30648. this._generateDOMelements();
  30649. window.addEventListener("resize", this._syncPositions);
  30650. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30651. this._syncPositions();
  30652. this._scene.registerBeforeRender(this._syncData);
  30653. this._scene.registerAfterRender(this._syncUI);
  30654. };
  30655. DebugLayer.prototype._clearLabels = function () {
  30656. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30657. for (var index = 0; index < this._scene.meshes.length; index++) {
  30658. var mesh = this._scene.meshes[index];
  30659. mesh.renderOverlay = false;
  30660. }
  30661. };
  30662. DebugLayer.prototype._generateheader = function (root, text) {
  30663. var header = document.createElement("div");
  30664. header.innerHTML = text + "&nbsp;";
  30665. header.style.textAlign = "right";
  30666. header.style.width = "100%";
  30667. header.style.color = "white";
  30668. header.style.backgroundColor = "Black";
  30669. header.style.padding = "5px 5px 4px 0px";
  30670. header.style.marginLeft = "-5px";
  30671. header.style.fontWeight = "bold";
  30672. root.appendChild(header);
  30673. };
  30674. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30675. var label = document.createElement("label");
  30676. label.innerHTML = title;
  30677. label.style.color = color;
  30678. root.appendChild(label);
  30679. root.appendChild(document.createElement("br"));
  30680. };
  30681. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30682. if (tag === void 0) { tag = null; }
  30683. var label = document.createElement("label");
  30684. var boundingBoxesCheckbox = document.createElement("input");
  30685. boundingBoxesCheckbox.type = "checkbox";
  30686. boundingBoxesCheckbox.checked = initialState;
  30687. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30688. task(evt.target, tag);
  30689. });
  30690. label.appendChild(boundingBoxesCheckbox);
  30691. var container = document.createElement("span");
  30692. var leftPart = document.createElement("span");
  30693. var rightPart = document.createElement("span");
  30694. rightPart.style.cssFloat = "right";
  30695. leftPart.innerHTML = leftTitle;
  30696. rightPart.innerHTML = rightTitle;
  30697. rightPart.style.fontSize = "12px";
  30698. rightPart.style.maxWidth = "200px";
  30699. container.appendChild(leftPart);
  30700. container.appendChild(rightPart);
  30701. label.appendChild(container);
  30702. root.appendChild(label);
  30703. root.appendChild(document.createElement("br"));
  30704. };
  30705. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30706. if (tag === void 0) { tag = null; }
  30707. var label = document.createElement("label");
  30708. var checkBox = document.createElement("input");
  30709. checkBox.type = "checkbox";
  30710. checkBox.checked = initialState;
  30711. checkBox.addEventListener("change", function (evt) {
  30712. task(evt.target, tag);
  30713. });
  30714. label.appendChild(checkBox);
  30715. label.appendChild(document.createTextNode(title));
  30716. root.appendChild(label);
  30717. root.appendChild(document.createElement("br"));
  30718. };
  30719. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30720. if (tag === void 0) { tag = null; }
  30721. var button = document.createElement("button");
  30722. button.innerHTML = title;
  30723. button.style.height = "24px";
  30724. button.style.color = "#444444";
  30725. button.style.border = "1px solid white";
  30726. button.className = "debugLayerButton";
  30727. button.addEventListener("click", function (evt) {
  30728. task(evt.target, tag);
  30729. });
  30730. root.appendChild(button);
  30731. root.appendChild(document.createElement("br"));
  30732. };
  30733. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30734. if (tag === void 0) { tag = null; }
  30735. var label = document.createElement("label");
  30736. var boundingBoxesRadio = document.createElement("input");
  30737. boundingBoxesRadio.type = "radio";
  30738. boundingBoxesRadio.name = name;
  30739. boundingBoxesRadio.checked = initialState;
  30740. boundingBoxesRadio.addEventListener("change", function (evt) {
  30741. task(evt.target, tag);
  30742. });
  30743. label.appendChild(boundingBoxesRadio);
  30744. label.appendChild(document.createTextNode(title));
  30745. root.appendChild(label);
  30746. root.appendChild(document.createElement("br"));
  30747. };
  30748. DebugLayer.prototype._generateDOMelements = function () {
  30749. var _this = this;
  30750. this._globalDiv.id = "DebugLayer";
  30751. this._globalDiv.style.position = "absolute";
  30752. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30753. this._globalDiv.style.fontSize = "14px";
  30754. this._globalDiv.style.color = "white";
  30755. // Drawing canvas
  30756. this._drawingCanvas = document.createElement("canvas");
  30757. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30758. this._drawingCanvas.style.position = "absolute";
  30759. this._drawingCanvas.style.pointerEvents = "none";
  30760. this._drawingContext = this._drawingCanvas.getContext("2d");
  30761. this._globalDiv.appendChild(this._drawingCanvas);
  30762. if (this._showUI) {
  30763. var background = "rgba(128, 128, 128, 0.4)";
  30764. var border = "rgb(180, 180, 180) solid 1px";
  30765. // Stats
  30766. this._statsDiv = document.createElement("div");
  30767. this._statsDiv.id = "DebugLayerStats";
  30768. this._statsDiv.style.border = border;
  30769. this._statsDiv.style.position = "absolute";
  30770. this._statsDiv.style.background = background;
  30771. this._statsDiv.style.padding = "0px 0px 0px 5px";
  30772. this._generateheader(this._statsDiv, "STATISTICS");
  30773. this._statsSubsetDiv = document.createElement("div");
  30774. this._statsSubsetDiv.style.paddingTop = "5px";
  30775. this._statsSubsetDiv.style.paddingBottom = "5px";
  30776. this._statsSubsetDiv.style.overflowY = "auto";
  30777. this._statsDiv.appendChild(this._statsSubsetDiv);
  30778. // Tree
  30779. this._treeDiv = document.createElement("div");
  30780. this._treeDiv.id = "DebugLayerTree";
  30781. this._treeDiv.style.border = border;
  30782. this._treeDiv.style.position = "absolute";
  30783. this._treeDiv.style.background = background;
  30784. this._treeDiv.style.padding = "0px 0px 0px 5px";
  30785. this._treeDiv.style.display = "none";
  30786. this._generateheader(this._treeDiv, "MESHES TREE");
  30787. this._treeSubsetDiv = document.createElement("div");
  30788. this._treeSubsetDiv.style.paddingTop = "5px";
  30789. this._treeSubsetDiv.style.paddingRight = "5px";
  30790. this._treeSubsetDiv.style.overflowY = "auto";
  30791. this._treeSubsetDiv.style.maxHeight = "300px";
  30792. this._treeDiv.appendChild(this._treeSubsetDiv);
  30793. this._needToRefreshMeshesTree = true;
  30794. // Logs
  30795. this._logDiv = document.createElement("div");
  30796. this._logDiv.style.border = border;
  30797. this._logDiv.id = "DebugLayerLogs";
  30798. this._logDiv.style.position = "absolute";
  30799. this._logDiv.style.background = background;
  30800. this._logDiv.style.padding = "0px 0px 0px 5px";
  30801. this._logDiv.style.display = "none";
  30802. this._generateheader(this._logDiv, "LOGS");
  30803. this._logSubsetDiv = document.createElement("div");
  30804. this._logSubsetDiv.style.height = "127px";
  30805. this._logSubsetDiv.style.paddingTop = "5px";
  30806. this._logSubsetDiv.style.overflowY = "auto";
  30807. this._logSubsetDiv.style.fontSize = "12px";
  30808. this._logSubsetDiv.style.fontFamily = "consolas";
  30809. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  30810. this._logDiv.appendChild(this._logSubsetDiv);
  30811. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  30812. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  30813. };
  30814. // Options
  30815. this._optionsDiv = document.createElement("div");
  30816. this._optionsDiv.id = "DebugLayerOptions";
  30817. this._optionsDiv.style.border = border;
  30818. this._optionsDiv.style.position = "absolute";
  30819. this._optionsDiv.style.background = background;
  30820. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  30821. this._optionsDiv.style.overflowY = "auto";
  30822. this._generateheader(this._optionsDiv, "OPTIONS");
  30823. this._optionsSubsetDiv = document.createElement("div");
  30824. this._optionsSubsetDiv.style.paddingTop = "5px";
  30825. this._optionsSubsetDiv.style.paddingBottom = "5px";
  30826. this._optionsSubsetDiv.style.overflowY = "auto";
  30827. this._optionsSubsetDiv.style.maxHeight = "200px";
  30828. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  30829. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  30830. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  30831. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  30832. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  30833. _this._displayTree = element.checked;
  30834. _this._needToRefreshMeshesTree = true;
  30835. });
  30836. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30837. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  30838. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  30839. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  30840. _this._labelsEnabled = element.checked;
  30841. if (!_this._labelsEnabled) {
  30842. _this._clearLabels();
  30843. }
  30844. });
  30845. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  30846. if (element.checked) {
  30847. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  30848. }
  30849. else {
  30850. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  30851. }
  30852. });
  30853. ;
  30854. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30855. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  30856. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  30857. if (element.checked) {
  30858. _this._scene.forceWireframe = false;
  30859. _this._scene.forcePointsCloud = false;
  30860. }
  30861. });
  30862. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  30863. if (element.checked) {
  30864. _this._scene.forceWireframe = true;
  30865. _this._scene.forcePointsCloud = false;
  30866. }
  30867. });
  30868. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  30869. if (element.checked) {
  30870. _this._scene.forceWireframe = false;
  30871. _this._scene.forcePointsCloud = true;
  30872. }
  30873. });
  30874. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30875. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  30876. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  30877. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  30878. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  30879. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  30880. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  30881. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  30882. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  30883. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  30884. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30885. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  30886. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  30887. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  30888. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  30889. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  30890. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  30891. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  30892. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  30893. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  30894. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  30895. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  30896. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  30897. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  30898. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  30899. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30900. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30901. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  30902. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  30903. if (element.checked) {
  30904. _this._scene.headphone = true;
  30905. }
  30906. });
  30907. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  30908. if (element.checked) {
  30909. _this._scene.headphone = false;
  30910. }
  30911. });
  30912. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  30913. _this._scene.audioEnabled = !element.checked;
  30914. });
  30915. }
  30916. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30917. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  30918. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  30919. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30920. this._globalDiv.appendChild(this._statsDiv);
  30921. this._globalDiv.appendChild(this._logDiv);
  30922. this._globalDiv.appendChild(this._optionsDiv);
  30923. this._globalDiv.appendChild(this._treeDiv);
  30924. }
  30925. };
  30926. DebugLayer.prototype._displayStats = function () {
  30927. var scene = this._scene;
  30928. var engine = scene.getEngine();
  30929. var glInfo = engine.getGlInfo();
  30930. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  30931. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30932. + "<b>Count</b><br>"
  30933. + "Total meshes: " + scene.meshes.length + "<br>"
  30934. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  30935. + "Total materials: " + scene.materials.length + "<br>"
  30936. + "Total textures: " + scene.textures.length + "<br>"
  30937. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  30938. + "Active indices: " + scene.getActiveIndices() + "<br>"
  30939. + "Active bones: " + scene.getActiveBones() + "<br>"
  30940. + "Active particles: " + scene.getActiveParticles() + "<br>"
  30941. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  30942. + "<b>Duration</b><br>"
  30943. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  30944. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  30945. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  30946. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  30947. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  30948. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  30949. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  30950. + "</div>"
  30951. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30952. + "<b>Extensions</b><br>"
  30953. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  30954. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  30955. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  30956. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  30957. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  30958. + "<b>Caps.</b><br>"
  30959. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  30960. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  30961. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  30962. + "</div><br>"
  30963. + "<b>Info</b><br>"
  30964. + glInfo.version + "<br>"
  30965. + glInfo.renderer + "<br>";
  30966. if (this.customStatsFunction) {
  30967. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  30968. }
  30969. };
  30970. return DebugLayer;
  30971. })();
  30972. BABYLON.DebugLayer = DebugLayer;
  30973. })(BABYLON || (BABYLON = {}));
  30974. var BABYLON;
  30975. (function (BABYLON) {
  30976. var RawTexture = (function (_super) {
  30977. __extends(RawTexture, _super);
  30978. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  30979. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30980. if (invertY === void 0) { invertY = false; }
  30981. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30982. _super.call(this, null, scene, !generateMipMaps, invertY);
  30983. this.format = format;
  30984. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  30985. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30986. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30987. }
  30988. RawTexture.prototype.update = function (data) {
  30989. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  30990. };
  30991. // Statics
  30992. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30993. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30994. if (invertY === void 0) { invertY = false; }
  30995. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30996. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  30997. };
  30998. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30999. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31000. if (invertY === void 0) { invertY = false; }
  31001. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31002. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31003. };
  31004. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31005. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31006. if (invertY === void 0) { invertY = false; }
  31007. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31008. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  31009. };
  31010. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31011. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31012. if (invertY === void 0) { invertY = false; }
  31013. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31014. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  31015. };
  31016. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  31017. if (generateMipMaps === void 0) { generateMipMaps = true; }
  31018. if (invertY === void 0) { invertY = false; }
  31019. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  31020. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  31021. };
  31022. return RawTexture;
  31023. })(BABYLON.Texture);
  31024. BABYLON.RawTexture = RawTexture;
  31025. })(BABYLON || (BABYLON = {}));
  31026. var BABYLON;
  31027. (function (BABYLON) {
  31028. var IndexedVector2 = (function (_super) {
  31029. __extends(IndexedVector2, _super);
  31030. function IndexedVector2(original, index) {
  31031. _super.call(this, original.x, original.y);
  31032. this.index = index;
  31033. }
  31034. return IndexedVector2;
  31035. })(BABYLON.Vector2);
  31036. var PolygonPoints = (function () {
  31037. function PolygonPoints() {
  31038. this.elements = new Array();
  31039. }
  31040. PolygonPoints.prototype.add = function (originalPoints) {
  31041. var _this = this;
  31042. var result = new Array();
  31043. originalPoints.forEach(function (point) {
  31044. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  31045. var newPoint = new IndexedVector2(point, _this.elements.length);
  31046. result.push(newPoint);
  31047. _this.elements.push(newPoint);
  31048. }
  31049. });
  31050. return result;
  31051. };
  31052. PolygonPoints.prototype.computeBounds = function () {
  31053. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31054. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  31055. this.elements.forEach(function (point) {
  31056. // x
  31057. if (point.x < lmin.x) {
  31058. lmin.x = point.x;
  31059. }
  31060. else if (point.x > lmax.x) {
  31061. lmax.x = point.x;
  31062. }
  31063. // y
  31064. if (point.y < lmin.y) {
  31065. lmin.y = point.y;
  31066. }
  31067. else if (point.y > lmax.y) {
  31068. lmax.y = point.y;
  31069. }
  31070. });
  31071. return {
  31072. min: lmin,
  31073. max: lmax,
  31074. width: lmax.x - lmin.x,
  31075. height: lmax.y - lmin.y
  31076. };
  31077. };
  31078. return PolygonPoints;
  31079. })();
  31080. var Polygon = (function () {
  31081. function Polygon() {
  31082. }
  31083. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31084. return [
  31085. new BABYLON.Vector2(xmin, ymin),
  31086. new BABYLON.Vector2(xmax, ymin),
  31087. new BABYLON.Vector2(xmax, ymax),
  31088. new BABYLON.Vector2(xmin, ymax)
  31089. ];
  31090. };
  31091. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31092. if (cx === void 0) { cx = 0; }
  31093. if (cy === void 0) { cy = 0; }
  31094. if (numberOfSides === void 0) { numberOfSides = 32; }
  31095. var result = new Array();
  31096. var angle = 0;
  31097. var increment = (Math.PI * 2) / numberOfSides;
  31098. for (var i = 0; i < numberOfSides; i++) {
  31099. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31100. angle -= increment;
  31101. }
  31102. return result;
  31103. };
  31104. Polygon.Parse = function (input) {
  31105. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31106. var i, result = [];
  31107. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31108. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31109. }
  31110. return result;
  31111. };
  31112. Polygon.StartingAt = function (x, y) {
  31113. return BABYLON.Path2.StartingAt(x, y);
  31114. };
  31115. return Polygon;
  31116. })();
  31117. BABYLON.Polygon = Polygon;
  31118. var PolygonMeshBuilder = (function () {
  31119. function PolygonMeshBuilder(name, contours, scene) {
  31120. this._points = new PolygonPoints();
  31121. this._outlinepoints = new PolygonPoints();
  31122. this._holes = [];
  31123. if (!("poly2tri" in window)) {
  31124. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31125. }
  31126. this._name = name;
  31127. this._scene = scene;
  31128. var points;
  31129. if (contours instanceof BABYLON.Path2) {
  31130. points = contours.getPoints();
  31131. }
  31132. else {
  31133. points = contours;
  31134. }
  31135. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31136. this._outlinepoints.add(points);
  31137. }
  31138. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31139. this._swctx.addHole(this._points.add(hole));
  31140. var holepoints = new PolygonPoints();
  31141. holepoints.add(hole);
  31142. this._holes.push(holepoints);
  31143. return this;
  31144. };
  31145. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31146. var _this = this;
  31147. if (updatable === void 0) { updatable = false; }
  31148. var result = new BABYLON.Mesh(this._name, this._scene);
  31149. var normals = [];
  31150. var positions = [];
  31151. var uvs = [];
  31152. var bounds = this._points.computeBounds();
  31153. this._points.elements.forEach(function (p) {
  31154. normals.push(0, 1.0, 0);
  31155. positions.push(p.x, 0, p.y);
  31156. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31157. });
  31158. var indices = [];
  31159. this._swctx.triangulate();
  31160. this._swctx.getTriangles().forEach(function (triangle) {
  31161. triangle.getPoints().forEach(function (point) {
  31162. indices.push(point.index);
  31163. });
  31164. });
  31165. if (depth > 0) {
  31166. var positionscount = (positions.length / 3); //get the current pointcount
  31167. this._points.elements.forEach(function (p) {
  31168. normals.push(0, -1.0, 0);
  31169. positions.push(p.x, -depth, p.y);
  31170. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31171. });
  31172. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31173. var p2;
  31174. var poscounter = 0;
  31175. this._swctx.getTriangles().forEach(function (triangle) {
  31176. triangle.getPoints().forEach(function (point) {
  31177. switch (poscounter) {
  31178. case 0:
  31179. p1 = point;
  31180. break;
  31181. case 1:
  31182. p2 = point;
  31183. break;
  31184. case 2:
  31185. indices.push(point.index + positionscount);
  31186. indices.push(p2.index + positionscount);
  31187. indices.push(p1.index + positionscount);
  31188. poscounter = -1;
  31189. break;
  31190. }
  31191. poscounter++;
  31192. //indices.push((<IndexedVector2>point).index + positionscount);
  31193. });
  31194. });
  31195. //Add the sides
  31196. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31197. this._holes.forEach(function (hole) {
  31198. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31199. });
  31200. }
  31201. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31202. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31203. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31204. result.setIndices(indices);
  31205. return result;
  31206. };
  31207. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31208. var StartIndex = positions.length / 3;
  31209. var ulength = 0;
  31210. for (var i = 0; i < points.elements.length; i++) {
  31211. var p = points.elements[i];
  31212. var p1;
  31213. if ((i + 1) > points.elements.length - 1) {
  31214. p1 = points.elements[0];
  31215. }
  31216. else {
  31217. p1 = points.elements[i + 1];
  31218. }
  31219. positions.push(p.x, 0, p.y);
  31220. positions.push(p.x, -depth, p.y);
  31221. positions.push(p1.x, 0, p1.y);
  31222. positions.push(p1.x, -depth, p1.y);
  31223. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31224. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31225. var v3 = v2.subtract(v1);
  31226. var v4 = new BABYLON.Vector3(0, 1, 0);
  31227. var vn = BABYLON.Vector3.Cross(v3, v4);
  31228. vn = vn.normalize();
  31229. uvs.push(ulength / bounds.width, 0);
  31230. uvs.push(ulength / bounds.width, 1);
  31231. ulength += v3.length();
  31232. uvs.push((ulength / bounds.width), 0);
  31233. uvs.push((ulength / bounds.width), 1);
  31234. if (!flip) {
  31235. normals.push(-vn.x, -vn.y, -vn.z);
  31236. normals.push(-vn.x, -vn.y, -vn.z);
  31237. normals.push(-vn.x, -vn.y, -vn.z);
  31238. normals.push(-vn.x, -vn.y, -vn.z);
  31239. indices.push(StartIndex);
  31240. indices.push(StartIndex + 1);
  31241. indices.push(StartIndex + 2);
  31242. indices.push(StartIndex + 1);
  31243. indices.push(StartIndex + 3);
  31244. indices.push(StartIndex + 2);
  31245. }
  31246. else {
  31247. normals.push(vn.x, vn.y, vn.z);
  31248. normals.push(vn.x, vn.y, vn.z);
  31249. normals.push(vn.x, vn.y, vn.z);
  31250. normals.push(vn.x, vn.y, vn.z);
  31251. indices.push(StartIndex);
  31252. indices.push(StartIndex + 2);
  31253. indices.push(StartIndex + 1);
  31254. indices.push(StartIndex + 1);
  31255. indices.push(StartIndex + 2);
  31256. indices.push(StartIndex + 3);
  31257. }
  31258. StartIndex += 4;
  31259. }
  31260. ;
  31261. };
  31262. return PolygonMeshBuilder;
  31263. })();
  31264. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31265. })(BABYLON || (BABYLON = {}));
  31266. var BABYLON;
  31267. (function (BABYLON) {
  31268. var SimplificationSettings = (function () {
  31269. function SimplificationSettings(quality, distance, optimizeMesh) {
  31270. this.quality = quality;
  31271. this.distance = distance;
  31272. this.optimizeMesh = optimizeMesh;
  31273. }
  31274. return SimplificationSettings;
  31275. })();
  31276. BABYLON.SimplificationSettings = SimplificationSettings;
  31277. var SimplificationQueue = (function () {
  31278. function SimplificationQueue() {
  31279. this.running = false;
  31280. this._simplificationArray = [];
  31281. }
  31282. SimplificationQueue.prototype.addTask = function (task) {
  31283. this._simplificationArray.push(task);
  31284. };
  31285. SimplificationQueue.prototype.executeNext = function () {
  31286. var task = this._simplificationArray.pop();
  31287. if (task) {
  31288. this.running = true;
  31289. this.runSimplification(task);
  31290. }
  31291. else {
  31292. this.running = false;
  31293. }
  31294. };
  31295. SimplificationQueue.prototype.runSimplification = function (task) {
  31296. var _this = this;
  31297. if (task.parallelProcessing) {
  31298. //parallel simplifier
  31299. task.settings.forEach(function (setting) {
  31300. var simplifier = _this.getSimplifier(task);
  31301. simplifier.simplify(setting, function (newMesh) {
  31302. task.mesh.addLODLevel(setting.distance, newMesh);
  31303. newMesh.isVisible = true;
  31304. //check if it is the last
  31305. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31306. //all done, run the success callback.
  31307. task.successCallback();
  31308. }
  31309. _this.executeNext();
  31310. });
  31311. });
  31312. }
  31313. else {
  31314. //single simplifier.
  31315. var simplifier = this.getSimplifier(task);
  31316. var runDecimation = function (setting, callback) {
  31317. simplifier.simplify(setting, function (newMesh) {
  31318. task.mesh.addLODLevel(setting.distance, newMesh);
  31319. newMesh.isVisible = true;
  31320. //run the next quality level
  31321. callback();
  31322. });
  31323. };
  31324. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31325. runDecimation(task.settings[loop.index], function () {
  31326. loop.executeNext();
  31327. });
  31328. }, function () {
  31329. //execution ended, run the success callback.
  31330. if (task.successCallback) {
  31331. task.successCallback();
  31332. }
  31333. _this.executeNext();
  31334. });
  31335. }
  31336. };
  31337. SimplificationQueue.prototype.getSimplifier = function (task) {
  31338. switch (task.simplificationType) {
  31339. case SimplificationType.QUADRATIC:
  31340. default:
  31341. return new QuadraticErrorSimplification(task.mesh);
  31342. }
  31343. };
  31344. return SimplificationQueue;
  31345. })();
  31346. BABYLON.SimplificationQueue = SimplificationQueue;
  31347. /**
  31348. * The implemented types of simplification.
  31349. * At the moment only Quadratic Error Decimation is implemented.
  31350. */
  31351. (function (SimplificationType) {
  31352. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31353. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31354. var SimplificationType = BABYLON.SimplificationType;
  31355. var DecimationTriangle = (function () {
  31356. function DecimationTriangle(vertices) {
  31357. this.vertices = vertices;
  31358. this.error = new Array(4);
  31359. this.deleted = false;
  31360. this.isDirty = false;
  31361. this.deletePending = false;
  31362. this.borderFactor = 0;
  31363. }
  31364. return DecimationTriangle;
  31365. })();
  31366. BABYLON.DecimationTriangle = DecimationTriangle;
  31367. var DecimationVertex = (function () {
  31368. function DecimationVertex(position, id) {
  31369. this.position = position;
  31370. this.id = id;
  31371. this.isBorder = true;
  31372. this.q = new QuadraticMatrix();
  31373. this.triangleCount = 0;
  31374. this.triangleStart = 0;
  31375. this.originalOffsets = [];
  31376. }
  31377. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31378. this.position.copyFrom(newPosition);
  31379. };
  31380. return DecimationVertex;
  31381. })();
  31382. BABYLON.DecimationVertex = DecimationVertex;
  31383. var QuadraticMatrix = (function () {
  31384. function QuadraticMatrix(data) {
  31385. this.data = new Array(10);
  31386. for (var i = 0; i < 10; ++i) {
  31387. if (data && data[i]) {
  31388. this.data[i] = data[i];
  31389. }
  31390. else {
  31391. this.data[i] = 0;
  31392. }
  31393. }
  31394. }
  31395. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31396. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31397. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31398. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31399. return det;
  31400. };
  31401. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31402. for (var i = 0; i < 10; ++i) {
  31403. this.data[i] += matrix.data[i];
  31404. }
  31405. };
  31406. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31407. for (var i = 0; i < 10; ++i) {
  31408. this.data[i] += data[i];
  31409. }
  31410. };
  31411. QuadraticMatrix.prototype.add = function (matrix) {
  31412. var m = new QuadraticMatrix();
  31413. for (var i = 0; i < 10; ++i) {
  31414. m.data[i] = this.data[i] + matrix.data[i];
  31415. }
  31416. return m;
  31417. };
  31418. QuadraticMatrix.FromData = function (a, b, c, d) {
  31419. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31420. };
  31421. //returning an array to avoid garbage collection
  31422. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31423. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31424. };
  31425. return QuadraticMatrix;
  31426. })();
  31427. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31428. var Reference = (function () {
  31429. function Reference(vertexId, triangleId) {
  31430. this.vertexId = vertexId;
  31431. this.triangleId = triangleId;
  31432. }
  31433. return Reference;
  31434. })();
  31435. BABYLON.Reference = Reference;
  31436. /**
  31437. * An implementation of the Quadratic Error simplification algorithm.
  31438. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31439. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31440. * @author RaananW
  31441. */
  31442. var QuadraticErrorSimplification = (function () {
  31443. function QuadraticErrorSimplification(_mesh) {
  31444. this._mesh = _mesh;
  31445. this.initialized = false;
  31446. this.syncIterations = 5000;
  31447. this.aggressiveness = 7;
  31448. this.decimationIterations = 100;
  31449. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31450. }
  31451. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31452. var _this = this;
  31453. this.initDecimatedMesh();
  31454. //iterating through the submeshes array, one after the other.
  31455. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31456. _this.initWithMesh(loop.index, function () {
  31457. _this.runDecimation(settings, loop.index, function () {
  31458. loop.executeNext();
  31459. });
  31460. }, settings.optimizeMesh);
  31461. }, function () {
  31462. setTimeout(function () {
  31463. successCallback(_this._reconstructedMesh);
  31464. }, 0);
  31465. });
  31466. };
  31467. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31468. var _this = this;
  31469. var gCount = 0;
  31470. triangle.vertices.forEach(function (vertex) {
  31471. var count = 0;
  31472. var vPos = vertex.position;
  31473. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31474. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31475. ++count;
  31476. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  31477. ++count;
  31478. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  31479. ++count;
  31480. if (count > 1) {
  31481. ++gCount;
  31482. }
  31483. ;
  31484. });
  31485. if (gCount > 1) {
  31486. console.log(triangle, gCount);
  31487. }
  31488. return gCount > 1;
  31489. };
  31490. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31491. var _this = this;
  31492. var targetCount = ~~(this.triangles.length * settings.quality);
  31493. var deletedTriangles = 0;
  31494. var triangleCount = this.triangles.length;
  31495. var iterationFunction = function (iteration, callback) {
  31496. setTimeout(function () {
  31497. if (iteration % 5 === 0) {
  31498. _this.updateMesh(iteration === 0);
  31499. }
  31500. for (var i = 0; i < _this.triangles.length; ++i) {
  31501. _this.triangles[i].isDirty = false;
  31502. }
  31503. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31504. var trianglesIterator = function (i) {
  31505. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31506. var t = _this.triangles[tIdx];
  31507. if (!t)
  31508. return;
  31509. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31510. return;
  31511. }
  31512. for (var j = 0; j < 3; ++j) {
  31513. if (t.error[j] < threshold) {
  31514. var deleted0 = [];
  31515. var deleted1 = [];
  31516. var v0 = t.vertices[j];
  31517. var v1 = t.vertices[(j + 1) % 3];
  31518. if (v0.isBorder !== v1.isBorder)
  31519. continue;
  31520. var p = BABYLON.Vector3.Zero();
  31521. var n = BABYLON.Vector3.Zero();
  31522. var uv = BABYLON.Vector2.Zero();
  31523. var color = new BABYLON.Color4(0, 0, 0, 1);
  31524. _this.calculateError(v0, v1, p, n, uv, color);
  31525. var delTr = [];
  31526. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31527. continue;
  31528. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31529. continue;
  31530. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31531. continue;
  31532. var uniqueArray = [];
  31533. delTr.forEach(function (deletedT) {
  31534. if (uniqueArray.indexOf(deletedT) === -1) {
  31535. deletedT.deletePending = true;
  31536. uniqueArray.push(deletedT);
  31537. }
  31538. });
  31539. if (uniqueArray.length % 2 != 0) {
  31540. continue;
  31541. }
  31542. v0.q = v1.q.add(v0.q);
  31543. v0.updatePosition(p);
  31544. var tStart = _this.references.length;
  31545. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31546. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31547. var tCount = _this.references.length - tStart;
  31548. if (tCount <= v0.triangleCount) {
  31549. if (tCount) {
  31550. for (var c = 0; c < tCount; c++) {
  31551. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31552. }
  31553. }
  31554. }
  31555. else {
  31556. v0.triangleStart = tStart;
  31557. }
  31558. v0.triangleCount = tCount;
  31559. break;
  31560. }
  31561. }
  31562. };
  31563. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31564. }, 0);
  31565. };
  31566. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31567. if (triangleCount - deletedTriangles <= targetCount)
  31568. loop.breakLoop();
  31569. else {
  31570. iterationFunction(loop.index, function () {
  31571. loop.executeNext();
  31572. });
  31573. }
  31574. }, function () {
  31575. setTimeout(function () {
  31576. //reconstruct this part of the mesh
  31577. _this.reconstructMesh(submeshIndex);
  31578. successCallback();
  31579. }, 0);
  31580. });
  31581. };
  31582. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31583. var _this = this;
  31584. this.vertices = [];
  31585. this.triangles = [];
  31586. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31587. var indices = this._mesh.getIndices();
  31588. var submesh = this._mesh.subMeshes[submeshIndex];
  31589. var findInVertices = function (positionToSearch) {
  31590. if (optimizeMesh) {
  31591. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31592. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31593. return _this.vertices[ii];
  31594. }
  31595. }
  31596. }
  31597. return null;
  31598. };
  31599. var vertexReferences = [];
  31600. var vertexInit = function (i) {
  31601. var offset = i + submesh.verticesStart;
  31602. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31603. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31604. vertex.originalOffsets.push(offset);
  31605. if (vertex.id == _this.vertices.length) {
  31606. _this.vertices.push(vertex);
  31607. }
  31608. vertexReferences.push(vertex.id);
  31609. };
  31610. //var totalVertices = mesh.getTotalVertices();
  31611. var totalVertices = submesh.verticesCount;
  31612. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31613. var indicesInit = function (i) {
  31614. var offset = (submesh.indexStart / 3) + i;
  31615. var pos = (offset * 3);
  31616. var i0 = indices[pos + 0];
  31617. var i1 = indices[pos + 1];
  31618. var i2 = indices[pos + 2];
  31619. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31620. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31621. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31622. var triangle = new DecimationTriangle([v0, v1, v2]);
  31623. triangle.originalOffset = pos;
  31624. _this.triangles.push(triangle);
  31625. };
  31626. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31627. _this.init(callback);
  31628. });
  31629. });
  31630. };
  31631. QuadraticErrorSimplification.prototype.init = function (callback) {
  31632. var _this = this;
  31633. var triangleInit1 = function (i) {
  31634. var t = _this.triangles[i];
  31635. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31636. for (var j = 0; j < 3; j++) {
  31637. 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))));
  31638. }
  31639. };
  31640. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31641. var triangleInit2 = function (i) {
  31642. var t = _this.triangles[i];
  31643. for (var j = 0; j < 3; ++j) {
  31644. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31645. }
  31646. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31647. };
  31648. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31649. _this.initialized = true;
  31650. callback();
  31651. });
  31652. });
  31653. };
  31654. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31655. var newTriangles = [];
  31656. var i;
  31657. for (i = 0; i < this.vertices.length; ++i) {
  31658. this.vertices[i].triangleCount = 0;
  31659. }
  31660. var t;
  31661. var j;
  31662. for (i = 0; i < this.triangles.length; ++i) {
  31663. if (!this.triangles[i].deleted) {
  31664. t = this.triangles[i];
  31665. for (j = 0; j < 3; ++j) {
  31666. t.vertices[j].triangleCount = 1;
  31667. }
  31668. newTriangles.push(t);
  31669. }
  31670. }
  31671. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  31672. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  31673. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  31674. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  31675. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31676. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31677. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31678. var vertexCount = 0;
  31679. for (i = 0; i < this.vertices.length; ++i) {
  31680. var vertex = this.vertices[i];
  31681. vertex.id = vertexCount;
  31682. if (vertex.triangleCount) {
  31683. vertex.originalOffsets.forEach(function (originalOffset) {
  31684. newPositionData.push(vertex.position.x);
  31685. newPositionData.push(vertex.position.y);
  31686. newPositionData.push(vertex.position.z);
  31687. newNormalData.push(normalData[originalOffset * 3]);
  31688. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31689. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31690. if (uvs && uvs.length) {
  31691. newUVsData.push(uvs[(originalOffset * 2)]);
  31692. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31693. }
  31694. else if (colorsData && colorsData.length) {
  31695. newColorsData.push(colorsData[(originalOffset * 4)]);
  31696. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31697. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31698. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31699. }
  31700. ++vertexCount;
  31701. });
  31702. }
  31703. }
  31704. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31705. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31706. var submeshesArray = this._reconstructedMesh.subMeshes;
  31707. this._reconstructedMesh.subMeshes = [];
  31708. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31709. var originalIndices = this._mesh.getIndices();
  31710. for (i = 0; i < newTriangles.length; ++i) {
  31711. var t = newTriangles[i];
  31712. //now get the new referencing point for each vertex
  31713. [0, 1, 2].forEach(function (idx) {
  31714. var id = originalIndices[t.originalOffset + idx];
  31715. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31716. if (offset < 0)
  31717. offset = 0;
  31718. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31719. });
  31720. }
  31721. //overwriting the old vertex buffers and indices.
  31722. this._reconstructedMesh.setIndices(newIndicesArray);
  31723. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31724. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31725. if (newUVsData.length > 0)
  31726. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31727. if (newColorsData.length > 0)
  31728. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31729. //create submesh
  31730. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31731. if (submeshIndex > 0) {
  31732. this._reconstructedMesh.subMeshes = [];
  31733. submeshesArray.forEach(function (submesh) {
  31734. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31735. });
  31736. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31737. }
  31738. };
  31739. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31740. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31741. this._reconstructedMesh.material = this._mesh.material;
  31742. this._reconstructedMesh.parent = this._mesh.parent;
  31743. this._reconstructedMesh.isVisible = false;
  31744. };
  31745. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31746. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31747. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31748. if (t.deleted)
  31749. continue;
  31750. var s = this.references[vertex1.triangleStart + i].vertexId;
  31751. var v1 = t.vertices[(s + 1) % 3];
  31752. var v2 = t.vertices[(s + 2) % 3];
  31753. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31754. deletedArray[i] = true;
  31755. delTr.push(t);
  31756. continue;
  31757. }
  31758. var d1 = v1.position.subtract(point);
  31759. d1 = d1.normalize();
  31760. var d2 = v2.position.subtract(point);
  31761. d2 = d2.normalize();
  31762. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31763. return true;
  31764. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31765. deletedArray[i] = false;
  31766. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31767. return true;
  31768. }
  31769. return false;
  31770. };
  31771. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31772. var newDeleted = deletedTriangles;
  31773. for (var i = 0; i < vertex.triangleCount; ++i) {
  31774. var ref = this.references[vertex.triangleStart + i];
  31775. var t = this.triangles[ref.triangleId];
  31776. if (t.deleted)
  31777. continue;
  31778. if (deletedArray[i] && t.deletePending) {
  31779. t.deleted = true;
  31780. newDeleted++;
  31781. continue;
  31782. }
  31783. t.vertices[ref.vertexId] = origVertex;
  31784. t.isDirty = true;
  31785. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31786. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31787. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31788. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31789. this.references.push(ref);
  31790. }
  31791. return newDeleted;
  31792. };
  31793. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31794. for (var i = 0; i < this.vertices.length; ++i) {
  31795. var vCount = [];
  31796. var vId = [];
  31797. var v = this.vertices[i];
  31798. var j;
  31799. for (j = 0; j < v.triangleCount; ++j) {
  31800. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31801. for (var ii = 0; ii < 3; ii++) {
  31802. var ofs = 0;
  31803. var vv = triangle.vertices[ii];
  31804. while (ofs < vCount.length) {
  31805. if (vId[ofs] === vv.id)
  31806. break;
  31807. ++ofs;
  31808. }
  31809. if (ofs === vCount.length) {
  31810. vCount.push(1);
  31811. vId.push(vv.id);
  31812. }
  31813. else {
  31814. vCount[ofs]++;
  31815. }
  31816. }
  31817. }
  31818. for (j = 0; j < vCount.length; ++j) {
  31819. if (vCount[j] === 1) {
  31820. this.vertices[vId[j]].isBorder = true;
  31821. }
  31822. else {
  31823. this.vertices[vId[j]].isBorder = false;
  31824. }
  31825. }
  31826. }
  31827. };
  31828. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31829. if (identifyBorders === void 0) { identifyBorders = false; }
  31830. var i;
  31831. if (!identifyBorders) {
  31832. var newTrianglesVector = [];
  31833. for (i = 0; i < this.triangles.length; ++i) {
  31834. if (!this.triangles[i].deleted) {
  31835. newTrianglesVector.push(this.triangles[i]);
  31836. }
  31837. }
  31838. this.triangles = newTrianglesVector;
  31839. }
  31840. for (i = 0; i < this.vertices.length; ++i) {
  31841. this.vertices[i].triangleCount = 0;
  31842. this.vertices[i].triangleStart = 0;
  31843. }
  31844. var t;
  31845. var j;
  31846. var v;
  31847. for (i = 0; i < this.triangles.length; ++i) {
  31848. t = this.triangles[i];
  31849. for (j = 0; j < 3; ++j) {
  31850. v = t.vertices[j];
  31851. v.triangleCount++;
  31852. }
  31853. }
  31854. var tStart = 0;
  31855. for (i = 0; i < this.vertices.length; ++i) {
  31856. this.vertices[i].triangleStart = tStart;
  31857. tStart += this.vertices[i].triangleCount;
  31858. this.vertices[i].triangleCount = 0;
  31859. }
  31860. var newReferences = new Array(this.triangles.length * 3);
  31861. for (i = 0; i < this.triangles.length; ++i) {
  31862. t = this.triangles[i];
  31863. for (j = 0; j < 3; ++j) {
  31864. v = t.vertices[j];
  31865. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31866. v.triangleCount++;
  31867. }
  31868. }
  31869. this.references = newReferences;
  31870. if (identifyBorders) {
  31871. this.identifyBorder();
  31872. }
  31873. };
  31874. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31875. var x = point.x;
  31876. var y = point.y;
  31877. var z = point.z;
  31878. 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
  31879. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31880. };
  31881. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31882. var q = vertex1.q.add(vertex2.q);
  31883. var border = vertex1.isBorder && vertex2.isBorder;
  31884. var error = 0;
  31885. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31886. if (qDet !== 0 && !border) {
  31887. if (!pointResult) {
  31888. pointResult = BABYLON.Vector3.Zero();
  31889. }
  31890. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31891. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31892. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31893. error = this.vertexError(q, pointResult);
  31894. }
  31895. else {
  31896. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31897. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31898. var error1 = this.vertexError(q, vertex1.position);
  31899. var error2 = this.vertexError(q, vertex2.position);
  31900. var error3 = this.vertexError(q, p3);
  31901. error = Math.min(error1, error2, error3);
  31902. if (error === error1) {
  31903. if (pointResult) {
  31904. pointResult.copyFrom(vertex1.position);
  31905. }
  31906. }
  31907. else if (error === error2) {
  31908. if (pointResult) {
  31909. pointResult.copyFrom(vertex2.position);
  31910. }
  31911. }
  31912. else {
  31913. if (pointResult) {
  31914. pointResult.copyFrom(p3);
  31915. }
  31916. }
  31917. }
  31918. return error;
  31919. };
  31920. return QuadraticErrorSimplification;
  31921. })();
  31922. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31923. })(BABYLON || (BABYLON = {}));
  31924. var BABYLON;
  31925. (function (BABYLON) {
  31926. var Analyser = (function () {
  31927. function Analyser(scene) {
  31928. this.SMOOTHING = 0.75;
  31929. this.FFT_SIZE = 512;
  31930. this.BARGRAPHAMPLITUDE = 256;
  31931. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  31932. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  31933. this._scene = scene;
  31934. this._audioEngine = BABYLON.Engine.audioEngine;
  31935. if (this._audioEngine.canUseWebAudio) {
  31936. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  31937. this._webAudioAnalyser.minDecibels = -140;
  31938. this._webAudioAnalyser.maxDecibels = 0;
  31939. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31940. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31941. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  31942. }
  31943. }
  31944. Analyser.prototype.getFrequencyBinCount = function () {
  31945. if (this._audioEngine.canUseWebAudio) {
  31946. return this._webAudioAnalyser.frequencyBinCount;
  31947. }
  31948. else {
  31949. return 0;
  31950. }
  31951. };
  31952. Analyser.prototype.getByteFrequencyData = function () {
  31953. if (this._audioEngine.canUseWebAudio) {
  31954. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31955. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31956. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  31957. }
  31958. return this._byteFreqs;
  31959. };
  31960. Analyser.prototype.getByteTimeDomainData = function () {
  31961. if (this._audioEngine.canUseWebAudio) {
  31962. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31963. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31964. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  31965. }
  31966. return this._byteTime;
  31967. };
  31968. Analyser.prototype.getFloatFrequencyData = function () {
  31969. if (this._audioEngine.canUseWebAudio) {
  31970. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31971. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31972. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  31973. }
  31974. return this._floatFreqs;
  31975. };
  31976. Analyser.prototype.drawDebugCanvas = function () {
  31977. var _this = this;
  31978. if (this._audioEngine.canUseWebAudio) {
  31979. if (!this._debugCanvas) {
  31980. this._debugCanvas = document.createElement("canvas");
  31981. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  31982. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  31983. this._debugCanvas.style.position = "absolute";
  31984. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  31985. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  31986. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  31987. document.body.appendChild(this._debugCanvas);
  31988. this._registerFunc = function () {
  31989. _this.drawDebugCanvas();
  31990. };
  31991. this._scene.registerBeforeRender(this._registerFunc);
  31992. }
  31993. if (this._registerFunc) {
  31994. var workingArray = this.getByteFrequencyData();
  31995. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  31996. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  31997. // Draw the frequency domain chart.
  31998. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  31999. var value = workingArray[i];
  32000. var percent = value / this.BARGRAPHAMPLITUDE;
  32001. var height = this.DEBUGCANVASSIZE.height * percent;
  32002. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  32003. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  32004. var hue = i / this.getFrequencyBinCount() * 360;
  32005. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  32006. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  32007. }
  32008. }
  32009. }
  32010. };
  32011. Analyser.prototype.stopDebugCanvas = function () {
  32012. if (this._debugCanvas) {
  32013. this._scene.unregisterBeforeRender(this._registerFunc);
  32014. this._registerFunc = null;
  32015. document.body.removeChild(this._debugCanvas);
  32016. this._debugCanvas = null;
  32017. this._debugCanvasContext = null;
  32018. }
  32019. };
  32020. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  32021. if (this._audioEngine.canUseWebAudio) {
  32022. inputAudioNode.connect(this._webAudioAnalyser);
  32023. this._webAudioAnalyser.connect(outputAudioNode);
  32024. }
  32025. };
  32026. Analyser.prototype.dispose = function () {
  32027. if (this._audioEngine.canUseWebAudio) {
  32028. this._webAudioAnalyser.disconnect();
  32029. }
  32030. };
  32031. return Analyser;
  32032. })();
  32033. BABYLON.Analyser = Analyser;
  32034. })(BABYLON || (BABYLON = {}));
  32035. var BABYLON;
  32036. (function (BABYLON) {
  32037. var DepthRenderer = (function () {
  32038. function DepthRenderer(scene, type) {
  32039. var _this = this;
  32040. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  32041. this._viewMatrix = BABYLON.Matrix.Zero();
  32042. this._projectionMatrix = BABYLON.Matrix.Zero();
  32043. this._transformMatrix = BABYLON.Matrix.Zero();
  32044. this._worldViewProjection = BABYLON.Matrix.Zero();
  32045. this._scene = scene;
  32046. var engine = scene.getEngine();
  32047. // Render target
  32048. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  32049. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32050. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32051. this._depthMap.refreshRate = 1;
  32052. this._depthMap.renderParticles = false;
  32053. this._depthMap.renderList = null;
  32054. // set default depth value to 1.0 (far away)
  32055. this._depthMap.onClear = function (engine) {
  32056. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  32057. };
  32058. // Custom render function
  32059. var renderSubMesh = function (subMesh) {
  32060. var mesh = subMesh.getRenderingMesh();
  32061. var scene = _this._scene;
  32062. var engine = scene.getEngine();
  32063. // Culling
  32064. engine.setState(subMesh.getMaterial().backFaceCulling);
  32065. // Managing instances
  32066. var batch = mesh._getInstancesRenderList(subMesh._id);
  32067. if (batch.mustReturn) {
  32068. return;
  32069. }
  32070. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32071. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32072. engine.enableEffect(_this._effect);
  32073. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  32074. var material = subMesh.getMaterial();
  32075. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  32076. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  32077. // Alpha test
  32078. if (material && material.needAlphaTesting()) {
  32079. var alphaTexture = material.getAlphaTestTexture();
  32080. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32081. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32082. }
  32083. // Bones
  32084. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32085. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32086. }
  32087. // Draw
  32088. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32089. }
  32090. };
  32091. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32092. var index;
  32093. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32094. renderSubMesh(opaqueSubMeshes.data[index]);
  32095. }
  32096. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32097. renderSubMesh(alphaTestSubMeshes.data[index]);
  32098. }
  32099. };
  32100. }
  32101. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32102. var defines = [];
  32103. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32104. var mesh = subMesh.getMesh();
  32105. var scene = mesh.getScene();
  32106. var material = subMesh.getMaterial();
  32107. // Alpha test
  32108. if (material && material.needAlphaTesting()) {
  32109. defines.push("#define ALPHATEST");
  32110. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32111. attribs.push(BABYLON.VertexBuffer.UVKind);
  32112. defines.push("#define UV1");
  32113. }
  32114. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32115. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32116. defines.push("#define UV2");
  32117. }
  32118. }
  32119. // Bones
  32120. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32121. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32122. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32123. defines.push("#define BONES");
  32124. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32125. }
  32126. // Instances
  32127. if (useInstances) {
  32128. defines.push("#define INSTANCES");
  32129. attribs.push("world0");
  32130. attribs.push("world1");
  32131. attribs.push("world2");
  32132. attribs.push("world3");
  32133. }
  32134. // Get correct effect
  32135. var join = defines.join("\n");
  32136. if (this._cachedDefines !== join) {
  32137. this._cachedDefines = join;
  32138. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32139. }
  32140. return this._effect.isReady();
  32141. };
  32142. DepthRenderer.prototype.getDepthMap = function () {
  32143. return this._depthMap;
  32144. };
  32145. // Methods
  32146. DepthRenderer.prototype.dispose = function () {
  32147. this._depthMap.dispose();
  32148. };
  32149. return DepthRenderer;
  32150. })();
  32151. BABYLON.DepthRenderer = DepthRenderer;
  32152. })(BABYLON || (BABYLON = {}));
  32153. var BABYLON;
  32154. (function (BABYLON) {
  32155. var SSAORenderingPipeline = (function (_super) {
  32156. __extends(SSAORenderingPipeline, _super);
  32157. /**
  32158. * @constructor
  32159. * @param {string} name - The rendering pipeline name
  32160. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32161. * @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 }
  32162. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32163. */
  32164. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32165. var _this = this;
  32166. _super.call(this, scene.getEngine(), name);
  32167. // Members
  32168. /**
  32169. * The PassPostProcess id in the pipeline that contains the original scene color
  32170. * @type {string}
  32171. */
  32172. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32173. /**
  32174. * The SSAO PostProcess id in the pipeline
  32175. * @type {string}
  32176. */
  32177. this.SSAORenderEffect = "SSAORenderEffect";
  32178. /**
  32179. * The horizontal blur PostProcess id in the pipeline
  32180. * @type {string}
  32181. */
  32182. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32183. /**
  32184. * The vertical blur PostProcess id in the pipeline
  32185. * @type {string}
  32186. */
  32187. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32188. /**
  32189. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32190. * @type {string}
  32191. */
  32192. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32193. /**
  32194. * The output strength of the SSAO post-process. Default value is 1.0.
  32195. * @type {number}
  32196. */
  32197. this.totalStrength = 1.0;
  32198. /**
  32199. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32200. * @type {number}
  32201. */
  32202. this.radius = 0.0002;
  32203. /**
  32204. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32205. * Must not be equal to fallOff and superior to fallOff.
  32206. * Default value is 0.0075
  32207. * @type {number}
  32208. */
  32209. this.area = 0.0075;
  32210. /**
  32211. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32212. * Must not be equal to area and inferior to area.
  32213. * Default value is 0.0002
  32214. * @type {number}
  32215. */
  32216. this.fallOff = 0.0002;
  32217. this._firstUpdate = true;
  32218. this._scene = scene;
  32219. // Set up assets
  32220. this._createRandomTexture();
  32221. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32222. var ssaoRatio = ratio.ssaoRatio || ratio;
  32223. var combineRatio = ratio.combineRatio || ratio;
  32224. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32225. this._createSSAOPostProcess(ssaoRatio);
  32226. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32227. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32228. this._createSSAOCombinePostProcess(combineRatio);
  32229. // Set up pipeline
  32230. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32232. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32233. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32234. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32235. // Finish
  32236. scene.postProcessRenderPipelineManager.addPipeline(this);
  32237. if (cameras)
  32238. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32239. }
  32240. // Public Methods
  32241. /**
  32242. * Returns the horizontal blur PostProcess
  32243. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32244. */
  32245. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32246. return this._blurHPostProcess;
  32247. };
  32248. /**
  32249. * Returns the vertical blur PostProcess
  32250. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32251. */
  32252. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32253. return this._blurVPostProcess;
  32254. };
  32255. /**
  32256. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32257. */
  32258. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32259. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32260. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32261. this._originalColorPostProcess = undefined;
  32262. this._ssaoPostProcess = undefined;
  32263. this._blurHPostProcess = undefined;
  32264. this._blurVPostProcess = undefined;
  32265. this._ssaoCombinePostProcess = undefined;
  32266. this._randomTexture.dispose();
  32267. if (disableDepthRender)
  32268. this._scene.disableDepthRenderer();
  32269. };
  32270. // Private Methods
  32271. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32272. var _this = this;
  32273. var sampleSphere = [
  32274. 0.5381, 0.1856, -0.4319,
  32275. 0.1379, 0.2486, 0.4430,
  32276. 0.3371, 0.5679, -0.0057,
  32277. -0.6999, -0.0451, -0.0019,
  32278. 0.0689, -0.1598, -0.8547,
  32279. 0.0560, 0.0069, -0.1843,
  32280. -0.0146, 0.1402, 0.0762,
  32281. 0.0100, -0.1924, -0.0344,
  32282. -0.3577, -0.5301, -0.4358,
  32283. -0.3169, 0.1063, 0.0158,
  32284. 0.0103, -0.5869, 0.0046,
  32285. -0.0897, -0.4940, 0.3287,
  32286. 0.7119, -0.0154, -0.0918,
  32287. -0.0533, 0.0596, -0.5411,
  32288. 0.0352, -0.0631, 0.5460,
  32289. -0.4776, 0.2847, -0.0271
  32290. ];
  32291. var samplesFactor = 1.0 / 16.0;
  32292. 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);
  32293. this._ssaoPostProcess.onApply = function (effect) {
  32294. if (_this._firstUpdate) {
  32295. effect.setArray3("sampleSphere", sampleSphere);
  32296. effect.setFloat("samplesFactor", samplesFactor);
  32297. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32298. _this._firstUpdate = false;
  32299. }
  32300. effect.setFloat("totalStrength", _this.totalStrength);
  32301. effect.setFloat("radius", _this.radius);
  32302. effect.setFloat("area", _this.area);
  32303. effect.setFloat("fallOff", _this.fallOff);
  32304. effect.setTexture("textureSampler", _this._depthTexture);
  32305. effect.setTexture("randomSampler", _this._randomTexture);
  32306. };
  32307. };
  32308. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32309. var _this = this;
  32310. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32311. this._ssaoCombinePostProcess.onApply = function (effect) {
  32312. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32313. };
  32314. };
  32315. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32316. var size = 512;
  32317. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32318. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32319. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32320. var context = this._randomTexture.getContext();
  32321. var rand = function (min, max) {
  32322. return Math.random() * (max - min) + min;
  32323. };
  32324. for (var x = 0; x < size; x++) {
  32325. for (var y = 0; y < size; y++) {
  32326. var randVector = BABYLON.Vector3.Zero();
  32327. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32328. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32329. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32330. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32331. context.fillRect(x, y, 1, 1);
  32332. }
  32333. }
  32334. this._randomTexture.update(false);
  32335. };
  32336. return SSAORenderingPipeline;
  32337. })(BABYLON.PostProcessRenderPipeline);
  32338. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32339. })(BABYLON || (BABYLON = {}));
  32340. var BABYLON;
  32341. (function (BABYLON) {
  32342. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32343. var VolumetricLightScatteringPostProcess = (function (_super) {
  32344. __extends(VolumetricLightScatteringPostProcess, _super);
  32345. /**
  32346. * @constructor
  32347. * @param {string} name - The post-process name
  32348. * @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)
  32349. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32350. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32351. * @param {number} samples - The post-process quality, default 100
  32352. * @param {number} samplingMode - The post-process filtering mode
  32353. * @param {BABYLON.Engine} engine - The babylon engine
  32354. * @param {boolean} reusable - If the post-process is reusable
  32355. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  32356. */
  32357. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  32358. var _this = this;
  32359. if (samples === void 0) { samples = 100; }
  32360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32361. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  32362. this._screenCoordinates = BABYLON.Vector2.Zero();
  32363. /**
  32364. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  32365. * @type {boolean}
  32366. */
  32367. this.useCustomMeshPosition = false;
  32368. /**
  32369. * If the post-process should inverse the light scattering direction
  32370. * @type {boolean}
  32371. */
  32372. this.invert = true;
  32373. /**
  32374. * Set to true to use the diffuseColor instead of the diffuseTexture
  32375. * @type {boolean}
  32376. */
  32377. this.useDiffuseColor = false;
  32378. /**
  32379. * Array containing the excluded meshes not rendered in the internal pass
  32380. */
  32381. this.excludedMeshes = new Array();
  32382. /**
  32383. * Controls the overall intensity of the post-process
  32384. * @type {number}
  32385. */
  32386. this.exposure = 0.3;
  32387. /**
  32388. * Dissipates each sample's contribution in range [0, 1]
  32389. * @type {number}
  32390. */
  32391. this.decay = 0.96815;
  32392. /**
  32393. * Controls the overall intensity of each sample
  32394. * @type {number}
  32395. */
  32396. this.weight = 0.58767;
  32397. /**
  32398. * Controls the density of each sample
  32399. * @type {number}
  32400. */
  32401. this.density = 0.926;
  32402. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  32403. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  32404. // Configure mesh
  32405. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  32406. // Configure
  32407. this._createPass(scene, ratio.passRatio || ratio);
  32408. this.onApply = function (effect) {
  32409. _this._updateMeshScreenCoordinates(scene);
  32410. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  32411. effect.setFloat("exposure", _this.exposure);
  32412. effect.setFloat("decay", _this.decay);
  32413. effect.setFloat("weight", _this.weight);
  32414. effect.setFloat("density", _this.density);
  32415. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  32416. };
  32417. }
  32418. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  32419. var mesh = subMesh.getMesh();
  32420. var defines = [];
  32421. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32422. var material = subMesh.getMaterial();
  32423. var needUV = false;
  32424. // Render this.mesh as default
  32425. if (mesh === this.mesh) {
  32426. if (this.useDiffuseColor) {
  32427. defines.push("#define DIFFUSE_COLOR_RENDER");
  32428. }
  32429. else if (material) {
  32430. if (material.diffuseTexture !== undefined) {
  32431. defines.push("#define BASIC_RENDER");
  32432. }
  32433. else {
  32434. defines.push("#define DIFFUSE_COLOR_RENDER");
  32435. }
  32436. }
  32437. defines.push("#define NEED_UV");
  32438. needUV = true;
  32439. }
  32440. // Alpha test
  32441. if (material) {
  32442. if (material.needAlphaTesting()) {
  32443. defines.push("#define ALPHATEST");
  32444. }
  32445. if (material.opacityTexture !== undefined) {
  32446. defines.push("#define OPACITY");
  32447. if (material.opacityTexture.getAlphaFromRGB) {
  32448. defines.push("#define OPACITYRGB");
  32449. }
  32450. if (!needUV) {
  32451. defines.push("#define NEED_UV");
  32452. }
  32453. }
  32454. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32455. attribs.push(BABYLON.VertexBuffer.UVKind);
  32456. defines.push("#define UV1");
  32457. }
  32458. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32459. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32460. defines.push("#define UV2");
  32461. }
  32462. }
  32463. // Bones
  32464. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32465. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32466. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32467. defines.push("#define BONES");
  32468. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32469. }
  32470. // Instances
  32471. if (useInstances) {
  32472. defines.push("#define INSTANCES");
  32473. attribs.push("world0");
  32474. attribs.push("world1");
  32475. attribs.push("world2");
  32476. attribs.push("world3");
  32477. }
  32478. // Get correct effect
  32479. var join = defines.join("\n");
  32480. if (this._cachedDefines !== join) {
  32481. this._cachedDefines = join;
  32482. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  32483. }
  32484. return this._volumetricLightScatteringPass.isReady();
  32485. };
  32486. /**
  32487. * Sets the new light position for light scattering effect
  32488. * @param {BABYLON.Vector3} The new custom light position
  32489. */
  32490. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  32491. this._customMeshPosition = position;
  32492. };
  32493. /**
  32494. * Returns the light position for light scattering effect
  32495. * @return {BABYLON.Vector3} The custom light position
  32496. */
  32497. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  32498. return this._customMeshPosition;
  32499. };
  32500. /**
  32501. * Disposes the internal assets and detaches the post-process from the camera
  32502. */
  32503. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  32504. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  32505. if (rttIndex !== -1) {
  32506. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  32507. }
  32508. this._volumetricLightScatteringRTT.dispose();
  32509. _super.prototype.dispose.call(this, camera);
  32510. };
  32511. /**
  32512. * Returns the render target texture used by the post-process
  32513. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  32514. */
  32515. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  32516. return this._volumetricLightScatteringRTT;
  32517. };
  32518. // Private methods
  32519. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  32520. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  32521. return true;
  32522. }
  32523. return false;
  32524. };
  32525. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  32526. var _this = this;
  32527. var engine = scene.getEngine();
  32528. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  32529. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32530. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32531. this._volumetricLightScatteringRTT.renderList = null;
  32532. this._volumetricLightScatteringRTT.renderParticles = false;
  32533. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  32534. // Custom render function for submeshes
  32535. var renderSubMesh = function (subMesh) {
  32536. var mesh = subMesh.getRenderingMesh();
  32537. if (_this._meshExcluded(mesh)) {
  32538. return;
  32539. }
  32540. var scene = mesh.getScene();
  32541. var engine = scene.getEngine();
  32542. // Culling
  32543. engine.setState(subMesh.getMaterial().backFaceCulling);
  32544. // Managing instances
  32545. var batch = mesh._getInstancesRenderList(subMesh._id);
  32546. if (batch.mustReturn) {
  32547. return;
  32548. }
  32549. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32550. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32551. engine.enableEffect(_this._volumetricLightScatteringPass);
  32552. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  32553. var material = subMesh.getMaterial();
  32554. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  32555. // Alpha test
  32556. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  32557. var alphaTexture = material.getAlphaTestTexture();
  32558. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  32559. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  32560. }
  32561. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  32562. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  32563. if (alphaTexture) {
  32564. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32565. }
  32566. }
  32567. if (material.opacityTexture !== undefined) {
  32568. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  32569. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  32570. }
  32571. }
  32572. // Bones
  32573. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32574. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32575. }
  32576. // Draw
  32577. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  32578. }
  32579. };
  32580. // Render target texture callbacks
  32581. var savedSceneClearColor;
  32582. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  32583. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  32584. savedSceneClearColor = scene.clearColor;
  32585. scene.clearColor = sceneClearColor;
  32586. };
  32587. this._volumetricLightScatteringRTT.onAfterRender = function () {
  32588. scene.clearColor = savedSceneClearColor;
  32589. };
  32590. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  32591. var engine = scene.getEngine();
  32592. var index;
  32593. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32594. renderSubMesh(opaqueSubMeshes.data[index]);
  32595. }
  32596. engine.setAlphaTesting(true);
  32597. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32598. renderSubMesh(alphaTestSubMeshes.data[index]);
  32599. }
  32600. engine.setAlphaTesting(false);
  32601. if (transparentSubMeshes.length) {
  32602. // Sort sub meshes
  32603. for (index = 0; index < transparentSubMeshes.length; index++) {
  32604. var submesh = transparentSubMeshes.data[index];
  32605. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  32606. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  32607. }
  32608. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  32609. sortedArray.sort(function (a, b) {
  32610. // Alpha index first
  32611. if (a._alphaIndex > b._alphaIndex) {
  32612. return 1;
  32613. }
  32614. if (a._alphaIndex < b._alphaIndex) {
  32615. return -1;
  32616. }
  32617. // Then distance to camera
  32618. if (a._distanceToCamera < b._distanceToCamera) {
  32619. return 1;
  32620. }
  32621. if (a._distanceToCamera > b._distanceToCamera) {
  32622. return -1;
  32623. }
  32624. return 0;
  32625. });
  32626. // Render sub meshes
  32627. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32628. for (index = 0; index < sortedArray.length; index++) {
  32629. renderSubMesh(sortedArray[index]);
  32630. }
  32631. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32632. }
  32633. };
  32634. };
  32635. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  32636. var transform = scene.getTransformMatrix();
  32637. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  32638. this._screenCoordinates.x = pos.x / this._viewPort.width;
  32639. this._screenCoordinates.y = pos.y / this._viewPort.height;
  32640. if (this.invert)
  32641. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  32642. };
  32643. // Static methods
  32644. /**
  32645. * Creates a default mesh for the Volumeric Light Scattering post-process
  32646. * @param {string} The mesh name
  32647. * @param {BABYLON.Scene} The scene where to create the mesh
  32648. * @return {BABYLON.Mesh} the default mesh
  32649. */
  32650. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  32651. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  32652. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  32653. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  32654. return mesh;
  32655. };
  32656. return VolumetricLightScatteringPostProcess;
  32657. })(BABYLON.PostProcess);
  32658. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  32659. })(BABYLON || (BABYLON = {}));
  32660. var BABYLON;
  32661. (function (BABYLON) {
  32662. var LensRenderingPipeline = (function (_super) {
  32663. __extends(LensRenderingPipeline, _super);
  32664. /**
  32665. * @constructor
  32666. *
  32667. * Effect parameters are as follow:
  32668. * {
  32669. * chromatic_aberration: number; // from 0 to x (1 for realism)
  32670. * edge_blur: number; // from 0 to x (1 for realism)
  32671. * distortion: number; // from 0 to x (1 for realism)
  32672. * grain_amount: number; // from 0 to 1
  32673. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  32674. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  32675. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  32676. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  32677. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  32678. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  32679. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  32680. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  32681. * }
  32682. * Note: if an effect parameter is unset, effect is disabled
  32683. *
  32684. * @param {string} name - The rendering pipeline name
  32685. * @param {object} parameters - An object containing all parameters (see above)
  32686. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32687. * @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)
  32688. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32689. */
  32690. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  32691. var _this = this;
  32692. if (ratio === void 0) { ratio = 1.0; }
  32693. _super.call(this, scene.getEngine(), name);
  32694. // Lens effects can be of the following:
  32695. // - chromatic aberration (slight shift of RGB colors)
  32696. // - blur on the edge of the lens
  32697. // - lens distortion
  32698. // - depth-of-field blur & highlights enhancing
  32699. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  32700. // - grain effect (noise or custom texture)
  32701. // Two additional texture samplers are needed:
  32702. // - depth map (for depth-of-field)
  32703. // - grain texture
  32704. /**
  32705. * The chromatic aberration PostProcess id in the pipeline
  32706. * @type {string}
  32707. */
  32708. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  32709. /**
  32710. * The highlights enhancing PostProcess id in the pipeline
  32711. * @type {string}
  32712. */
  32713. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  32714. /**
  32715. * The depth-of-field PostProcess id in the pipeline
  32716. * @type {string}
  32717. */
  32718. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  32719. this._scene = scene;
  32720. // Fetch texture samplers
  32721. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32722. if (parameters.grain_texture) {
  32723. this._grainTexture = parameters.grain_texture;
  32724. }
  32725. else {
  32726. this._createGrainTexture();
  32727. }
  32728. // save parameters
  32729. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  32730. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  32731. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  32732. this._distortion = parameters.distortion ? parameters.distortion : 0;
  32733. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  32734. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  32735. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  32736. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  32737. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  32738. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  32739. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  32740. // Create effects
  32741. this._createChromaticAberrationPostProcess(ratio);
  32742. this._createHighlightsPostProcess(ratio);
  32743. this._createDepthOfFieldPostProcess(ratio / 4);
  32744. // Set up pipeline
  32745. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  32746. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  32747. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  32748. if (this._highlightsGain == -1) {
  32749. this._disableEffect(this.HighlightsEnhancingEffect, null);
  32750. }
  32751. // Finish
  32752. scene.postProcessRenderPipelineManager.addPipeline(this);
  32753. if (cameras) {
  32754. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32755. }
  32756. }
  32757. // public methods (self explanatory)
  32758. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  32759. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  32760. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  32761. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  32762. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  32763. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  32764. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  32765. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  32766. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  32767. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  32768. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  32769. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  32770. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  32771. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  32772. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  32773. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  32774. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  32775. this._highlightsGain = amount;
  32776. };
  32777. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  32778. if (this._highlightsGain == -1) {
  32779. this._highlightsGain = 1.0;
  32780. }
  32781. this._highlightsThreshold = amount;
  32782. };
  32783. LensRenderingPipeline.prototype.disableHighlights = function () {
  32784. this._highlightsGain = -1;
  32785. };
  32786. /**
  32787. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  32788. */
  32789. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32790. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32791. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32792. this._chromaticAberrationPostProcess = undefined;
  32793. this._highlightsPostProcess = undefined;
  32794. this._depthOfFieldPostProcess = undefined;
  32795. this._grainTexture.dispose();
  32796. if (disableDepthRender)
  32797. this._scene.disableDepthRenderer();
  32798. };
  32799. // colors shifting and distortion
  32800. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  32801. var _this = this;
  32802. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32803. this._chromaticAberrationPostProcess.onApply = function (effect) {
  32804. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  32805. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32806. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32807. };
  32808. };
  32809. // highlights enhancing
  32810. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  32811. var _this = this;
  32812. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32813. this._highlightsPostProcess.onApply = function (effect) {
  32814. effect.setFloat('gain', _this._highlightsGain);
  32815. effect.setFloat('threshold', _this._highlightsThreshold);
  32816. effect.setBool('pentagon', _this._dofPentagon);
  32817. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  32818. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32819. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32820. };
  32821. };
  32822. // colors shifting and distortion
  32823. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  32824. var _this = this;
  32825. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  32826. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  32827. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  32828. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32829. this._depthOfFieldPostProcess.onApply = function (effect) {
  32830. effect.setTexture("depthSampler", _this._depthTexture);
  32831. effect.setTexture("grainSampler", _this._grainTexture);
  32832. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  32833. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  32834. effect.setFloat('grain_amount', _this._grainAmount);
  32835. effect.setBool('blur_noise', _this._blurNoise);
  32836. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32837. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32838. effect.setFloat('distortion', _this._distortion);
  32839. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  32840. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  32841. effect.setFloat('aperture', _this._dofAperture);
  32842. effect.setFloat('darken', _this._dofDarken);
  32843. effect.setFloat('edge_blur', _this._edgeBlur);
  32844. effect.setBool('highlights', (_this._highlightsGain != -1));
  32845. effect.setFloat('near', _this._scene.activeCamera.minZ);
  32846. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  32847. };
  32848. };
  32849. // creates a black and white random noise texture, 512x512
  32850. LensRenderingPipeline.prototype._createGrainTexture = function () {
  32851. var size = 512;
  32852. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32853. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32854. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32855. var context = this._grainTexture.getContext();
  32856. var rand = function (min, max) {
  32857. return Math.random() * (max - min) + min;
  32858. };
  32859. var value;
  32860. for (var x = 0; x < size; x++) {
  32861. for (var y = 0; y < size; y++) {
  32862. value = Math.floor(rand(0.42, 0.58) * 255);
  32863. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  32864. context.fillRect(x, y, 1, 1);
  32865. }
  32866. }
  32867. this._grainTexture.update(false);
  32868. };
  32869. return LensRenderingPipeline;
  32870. })(BABYLON.PostProcessRenderPipeline);
  32871. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  32872. })(BABYLON || (BABYLON = {}));
  32873. //
  32874. // This post-process allows the modification of rendered colors by using
  32875. // a 'look-up table' (LUT). This effect is also called Color Grading.
  32876. //
  32877. // The object needs to be provided an url to a texture containing the color
  32878. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  32879. // Use an image editing software to tweak the LUT to match your needs.
  32880. //
  32881. // For an example of a color LUT, see here:
  32882. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  32883. // For explanations on color grading, see here:
  32884. // http://udn.epicgames.com/Three/ColorGrading.html
  32885. //
  32886. var BABYLON;
  32887. (function (BABYLON) {
  32888. var ColorCorrectionPostProcess = (function (_super) {
  32889. __extends(ColorCorrectionPostProcess, _super);
  32890. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  32891. var _this = this;
  32892. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  32893. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  32894. this._colorTableTexture.anisotropicFilteringLevel = 1;
  32895. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32896. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32897. this.onApply = function (effect) {
  32898. effect.setTexture("colorTable", _this._colorTableTexture);
  32899. };
  32900. }
  32901. return ColorCorrectionPostProcess;
  32902. })(BABYLON.PostProcess);
  32903. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  32904. })(BABYLON || (BABYLON = {}));
  32905. var BABYLON;
  32906. (function (BABYLON) {
  32907. var AnaglyphFreeCamera = (function (_super) {
  32908. __extends(AnaglyphFreeCamera, _super);
  32909. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  32910. _super.call(this, name, position, scene);
  32911. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32912. }
  32913. return AnaglyphFreeCamera;
  32914. })(BABYLON.FreeCamera);
  32915. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  32916. var AnaglyphArcRotateCamera = (function (_super) {
  32917. __extends(AnaglyphArcRotateCamera, _super);
  32918. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  32919. _super.call(this, name, alpha, beta, radius, target, scene);
  32920. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32921. }
  32922. return AnaglyphArcRotateCamera;
  32923. })(BABYLON.ArcRotateCamera);
  32924. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  32925. var AnaglyphGamepadCamera = (function (_super) {
  32926. __extends(AnaglyphGamepadCamera, _super);
  32927. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  32928. _super.call(this, name, position, scene);
  32929. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32930. }
  32931. return AnaglyphGamepadCamera;
  32932. })(BABYLON.GamepadCamera);
  32933. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  32934. var StereoscopicFreeCamera = (function (_super) {
  32935. __extends(StereoscopicFreeCamera, _super);
  32936. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  32937. _super.call(this, name, position, scene);
  32938. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32939. }
  32940. return StereoscopicFreeCamera;
  32941. })(BABYLON.FreeCamera);
  32942. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  32943. var StereoscopicArcRotateCamera = (function (_super) {
  32944. __extends(StereoscopicArcRotateCamera, _super);
  32945. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  32946. _super.call(this, name, alpha, beta, radius, target, scene);
  32947. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32948. }
  32949. return StereoscopicArcRotateCamera;
  32950. })(BABYLON.ArcRotateCamera);
  32951. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  32952. var StereoscopicGamepadCamera = (function (_super) {
  32953. __extends(StereoscopicGamepadCamera, _super);
  32954. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  32955. _super.call(this, name, position, scene);
  32956. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32957. }
  32958. return StereoscopicGamepadCamera;
  32959. })(BABYLON.GamepadCamera);
  32960. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  32961. })(BABYLON || (BABYLON = {}));
  32962. var BABYLON;
  32963. (function (BABYLON) {
  32964. var HDRRenderingPipeline = (function (_super) {
  32965. __extends(HDRRenderingPipeline, _super);
  32966. /**
  32967. * @constructor
  32968. * @param {string} name - The rendering pipeline name
  32969. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32970. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  32971. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  32972. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32973. */
  32974. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  32975. var _this = this;
  32976. if (originalPostProcess === void 0) { originalPostProcess = null; }
  32977. _super.call(this, scene.getEngine(), name);
  32978. /**
  32979. * Public members
  32980. */
  32981. // Gaussian Blur
  32982. /**
  32983. * Gaussian blur coefficient
  32984. * @type {number}
  32985. */
  32986. this.gaussCoeff = 0.3;
  32987. /**
  32988. * Gaussian blur mean
  32989. * @type {number}
  32990. */
  32991. this.gaussMean = 1.0;
  32992. /**
  32993. * Gaussian blur standard deviation
  32994. * @type {number}
  32995. */
  32996. this.gaussStandDev = 0.8;
  32997. // HDR
  32998. /**
  32999. * Exposure, controls the overall intensity of the pipeline
  33000. * @type {number}
  33001. */
  33002. this.exposure = 1.0;
  33003. /**
  33004. * Minimum luminance that the post-process can output. Luminance is >= 0
  33005. * @type {number}
  33006. */
  33007. this.minimumLuminance = 1.0;
  33008. /**
  33009. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  33010. * @type {number}
  33011. */
  33012. this.maximumLuminance = 1e20;
  33013. /**
  33014. * Increase rate for luminance: eye adaptation speed to dark
  33015. * @type {number}
  33016. */
  33017. this.luminanceIncreaserate = 0.5;
  33018. /**
  33019. * Decrease rate for luminance: eye adaptation speed to bright
  33020. * @type {number}
  33021. */
  33022. this.luminanceDecreaseRate = 0.5;
  33023. // Bright pass
  33024. /**
  33025. * Minimum luminance needed to compute HDR
  33026. * @type {number}
  33027. */
  33028. this.brightThreshold = 0.8;
  33029. this._needUpdate = true;
  33030. this._scene = scene;
  33031. // Bright pass
  33032. this._createBrightPassPostProcess(scene, ratio);
  33033. // Down sample X4
  33034. this._createDownSampleX4PostProcess(scene, ratio);
  33035. // Create gaussian blur post-processes
  33036. this._createGaussianBlurPostProcess(scene, ratio);
  33037. // Texture adder
  33038. this._createTextureAdderPostProcess(scene, ratio);
  33039. // Luminance generator
  33040. this._createLuminanceGeneratorPostProcess(scene);
  33041. // HDR
  33042. this._createHDRPostProcess(scene, ratio);
  33043. // Pass postprocess
  33044. if (originalPostProcess === null) {
  33045. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  33046. }
  33047. else {
  33048. this._originalPostProcess = originalPostProcess;
  33049. }
  33050. // Configure pipeline
  33051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  33052. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  33053. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  33054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  33055. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  33056. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  33057. var addDownSamplerPostProcess = function (id) {
  33058. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  33059. };
  33060. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33061. addDownSamplerPostProcess(i);
  33062. }
  33063. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  33064. // Finish
  33065. scene.postProcessRenderPipelineManager.addPipeline(this);
  33066. if (cameras !== null) {
  33067. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  33068. }
  33069. this.update();
  33070. }
  33071. /**
  33072. * Tells the pipeline to update its post-processes
  33073. */
  33074. HDRRenderingPipeline.prototype.update = function () {
  33075. this._needUpdate = true;
  33076. };
  33077. /**
  33078. * Returns the current calculated luminance
  33079. */
  33080. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33081. return this._hdrCurrentLuminance;
  33082. };
  33083. /**
  33084. * Returns the currently drawn luminance
  33085. */
  33086. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33087. return this._hdrOutputLuminance;
  33088. };
  33089. /**
  33090. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33091. */
  33092. HDRRenderingPipeline.prototype.dispose = function () {
  33093. this._originalPostProcess = undefined;
  33094. this._brightPassPostProcess = undefined;
  33095. this._downSampleX4PostProcess = undefined;
  33096. this._guassianBlurHPostProcess = undefined;
  33097. this._guassianBlurVPostProcess = undefined;
  33098. this._textureAdderPostProcess = undefined;
  33099. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33100. this._downSamplePostProcesses[i] = undefined;
  33101. }
  33102. this._hdrPostProcess = undefined;
  33103. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33104. };
  33105. /**
  33106. * Creates the HDR post-process and computes the luminance adaptation
  33107. */
  33108. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33109. var _this = this;
  33110. var hdrLastLuminance = 0.0;
  33111. this._hdrOutputLuminance = -1.0;
  33112. this._hdrCurrentLuminance = 1.0;
  33113. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33114. this._hdrPostProcess.onApply = function (effect) {
  33115. if (_this._hdrOutputLuminance < 0.0) {
  33116. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33117. }
  33118. else {
  33119. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33120. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33121. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33122. }
  33123. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33124. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33125. }
  33126. else {
  33127. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33128. }
  33129. }
  33130. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33131. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33132. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33133. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33134. effect.setFloat("exposure", _this.exposure);
  33135. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33136. _this._needUpdate = false;
  33137. };
  33138. };
  33139. /**
  33140. * Texture Adder post-process
  33141. */
  33142. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33143. var _this = this;
  33144. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33145. this._textureAdderPostProcess.onApply = function (effect) {
  33146. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33147. };
  33148. };
  33149. /**
  33150. * Down sample X4 post-process
  33151. */
  33152. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33153. var _this = this;
  33154. var downSampleX4Offsets = new Array(32);
  33155. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33156. this._downSampleX4PostProcess.onApply = function (effect) {
  33157. if (_this._needUpdate) {
  33158. var id = 0;
  33159. for (var i = -2; i < 2; i++) {
  33160. for (var j = -2; j < 2; j++) {
  33161. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33162. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33163. id += 2;
  33164. }
  33165. }
  33166. }
  33167. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33168. };
  33169. };
  33170. /**
  33171. * Bright pass post-process
  33172. */
  33173. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33174. var _this = this;
  33175. var brightOffsets = new Array(8);
  33176. var brightPassCallback = function (effect) {
  33177. if (_this._needUpdate) {
  33178. var sU = (1.0 / _this._brightPassPostProcess.width);
  33179. var sV = (1.0 / _this._brightPassPostProcess.height);
  33180. brightOffsets[0] = -0.5 * sU;
  33181. brightOffsets[1] = 0.5 * sV;
  33182. brightOffsets[2] = 0.5 * sU;
  33183. brightOffsets[3] = 0.5 * sV;
  33184. brightOffsets[4] = -0.5 * sU;
  33185. brightOffsets[5] = -0.5 * sV;
  33186. brightOffsets[6] = 0.5 * sU;
  33187. brightOffsets[7] = -0.5 * sV;
  33188. }
  33189. effect.setArray2("dsOffsets", brightOffsets);
  33190. effect.setFloat("brightThreshold", _this.brightThreshold);
  33191. };
  33192. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33193. this._brightPassPostProcess.onApply = brightPassCallback;
  33194. };
  33195. /**
  33196. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33197. */
  33198. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33199. var _this = this;
  33200. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33201. var luminanceOffsets = new Array(8);
  33202. var downSampleOffsets = new Array(18);
  33203. var halfDestPixelSize;
  33204. this._downSamplePostProcesses = new Array(lumSteps);
  33205. // Utils for luminance
  33206. var luminanceUpdateSourceOffsets = function (width, height) {
  33207. var sU = (1.0 / width);
  33208. var sV = (1.0 / height);
  33209. luminanceOffsets[0] = -0.5 * sU;
  33210. luminanceOffsets[1] = 0.5 * sV;
  33211. luminanceOffsets[2] = 0.5 * sU;
  33212. luminanceOffsets[3] = 0.5 * sV;
  33213. luminanceOffsets[4] = -0.5 * sU;
  33214. luminanceOffsets[5] = -0.5 * sV;
  33215. luminanceOffsets[6] = 0.5 * sU;
  33216. luminanceOffsets[7] = -0.5 * sV;
  33217. };
  33218. var luminanceUpdateDestOffsets = function (width, height) {
  33219. var id = 0;
  33220. for (var x = -1; x < 2; x++) {
  33221. for (var y = -1; y < 2; y++) {
  33222. downSampleOffsets[id] = (x) / width;
  33223. downSampleOffsets[id + 1] = (y) / height;
  33224. id += 2;
  33225. }
  33226. }
  33227. };
  33228. // Luminance callback
  33229. var luminanceCallback = function (effect) {
  33230. if (_this._needUpdate) {
  33231. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33232. }
  33233. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33234. effect.setArray2("lumOffsets", luminanceOffsets);
  33235. };
  33236. // Down sample callbacks
  33237. var downSampleCallback = function (indice) {
  33238. var i = indice;
  33239. return function (effect) {
  33240. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33241. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33242. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33243. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33244. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33245. effect.setArray2("dsOffsets", downSampleOffsets);
  33246. };
  33247. };
  33248. var downSampleAfterRenderCallback = function (effect) {
  33249. // Unpack result
  33250. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33251. var bit_shift = new BABYLON.Vector4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);
  33252. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33253. };
  33254. // Create luminance post-process
  33255. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33256. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  33257. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33258. // Create down sample post-processes
  33259. for (var i = lumSteps - 2; i >= 0; i--) {
  33260. var length = Math.pow(3, i);
  33261. ratio = { width: length, height: length };
  33262. var defines = "#define DOWN_SAMPLE\n";
  33263. if (i === 0) {
  33264. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33265. }
  33266. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33267. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33268. if (i === 0) {
  33269. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33270. }
  33271. }
  33272. };
  33273. /**
  33274. * Gaussian blur post-processes. Horizontal and Vertical
  33275. */
  33276. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33277. var _this = this;
  33278. var blurOffsetsW = new Array(9);
  33279. var blurOffsetsH = new Array(9);
  33280. var blurWeights = new Array(9);
  33281. var uniforms = ["blurOffsets", "blurWeights"];
  33282. // Utils for gaussian blur
  33283. var calculateBlurOffsets = function (height) {
  33284. var lastOutputDimensions = {
  33285. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33286. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33287. };
  33288. for (var i = 0; i < 9; i++) {
  33289. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33290. if (height) {
  33291. blurOffsetsH[i] = value;
  33292. }
  33293. else {
  33294. blurOffsetsW[i] = value;
  33295. }
  33296. }
  33297. };
  33298. var calculateWeights = function () {
  33299. var x = 0.0;
  33300. for (var i = 0; i < 9; i++) {
  33301. x = (i - 4.0) / 4.0;
  33302. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  33303. }
  33304. };
  33305. // Callback
  33306. var gaussianBlurCallback = function (height) {
  33307. return function (effect) {
  33308. if (_this._needUpdate) {
  33309. calculateWeights();
  33310. calculateBlurOffsets(height);
  33311. }
  33312. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33313. effect.setArray("blurWeights", blurWeights);
  33314. };
  33315. };
  33316. // Create horizontal gaussian blur post-processes
  33317. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33318. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33319. // Create vertical gaussian blur post-process
  33320. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33321. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33322. };
  33323. // Luminance generator
  33324. HDRRenderingPipeline.LUM_STEPS = 6;
  33325. return HDRRenderingPipeline;
  33326. })(BABYLON.PostProcessRenderPipeline);
  33327. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33328. })(BABYLON || (BABYLON = {}));
  33329. var BABYLON;
  33330. (function (BABYLON) {
  33331. var FaceAdjacencies = (function () {
  33332. function FaceAdjacencies() {
  33333. this.edges = new Array();
  33334. this.edgesConnectedCount = 0;
  33335. }
  33336. return FaceAdjacencies;
  33337. })();
  33338. var EdgesRenderer = (function () {
  33339. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  33340. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  33341. if (epsilon === void 0) { epsilon = 0.95; }
  33342. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  33343. this._linesPositions = new Array();
  33344. this._linesNormals = new Array();
  33345. this._linesIndices = new Array();
  33346. this._buffers = new Array();
  33347. this._checkVerticesInsteadOfIndices = false;
  33348. this._source = source;
  33349. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  33350. this._epsilon = epsilon;
  33351. this._prepareRessources();
  33352. this._generateEdgesLines();
  33353. }
  33354. EdgesRenderer.prototype._prepareRessources = function () {
  33355. if (this._lineShader) {
  33356. return;
  33357. }
  33358. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  33359. attributes: ["position", "normal"],
  33360. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  33361. });
  33362. this._lineShader.disableDepthWrite = true;
  33363. this._lineShader.backFaceCulling = false;
  33364. };
  33365. EdgesRenderer.prototype.dispose = function () {
  33366. this._vb0.dispose();
  33367. this._vb1.dispose();
  33368. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  33369. this._lineShader.dispose();
  33370. };
  33371. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  33372. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  33373. return 0;
  33374. }
  33375. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  33376. return 1;
  33377. }
  33378. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  33379. return 2;
  33380. }
  33381. return -1;
  33382. };
  33383. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  33384. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  33385. return 0;
  33386. }
  33387. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  33388. return 1;
  33389. }
  33390. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  33391. return 2;
  33392. }
  33393. return -1;
  33394. };
  33395. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  33396. var needToCreateLine;
  33397. if (edge === undefined) {
  33398. needToCreateLine = true;
  33399. }
  33400. else {
  33401. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  33402. needToCreateLine = dotProduct < this._epsilon;
  33403. }
  33404. if (needToCreateLine) {
  33405. var offset = this._linesPositions.length / 3;
  33406. var normal = p0.subtract(p1);
  33407. normal.normalize();
  33408. // Positions
  33409. this._linesPositions.push(p0.x);
  33410. this._linesPositions.push(p0.y);
  33411. this._linesPositions.push(p0.z);
  33412. this._linesPositions.push(p0.x);
  33413. this._linesPositions.push(p0.y);
  33414. this._linesPositions.push(p0.z);
  33415. this._linesPositions.push(p1.x);
  33416. this._linesPositions.push(p1.y);
  33417. this._linesPositions.push(p1.z);
  33418. this._linesPositions.push(p1.x);
  33419. this._linesPositions.push(p1.y);
  33420. this._linesPositions.push(p1.z);
  33421. // Normals
  33422. this._linesNormals.push(p1.x);
  33423. this._linesNormals.push(p1.y);
  33424. this._linesNormals.push(p1.z);
  33425. this._linesNormals.push(-1);
  33426. this._linesNormals.push(p1.x);
  33427. this._linesNormals.push(p1.y);
  33428. this._linesNormals.push(p1.z);
  33429. this._linesNormals.push(1);
  33430. this._linesNormals.push(p0.x);
  33431. this._linesNormals.push(p0.y);
  33432. this._linesNormals.push(p0.z);
  33433. this._linesNormals.push(-1);
  33434. this._linesNormals.push(p0.x);
  33435. this._linesNormals.push(p0.y);
  33436. this._linesNormals.push(p0.z);
  33437. this._linesNormals.push(1);
  33438. // Indices
  33439. this._linesIndices.push(offset);
  33440. this._linesIndices.push(offset + 1);
  33441. this._linesIndices.push(offset + 2);
  33442. this._linesIndices.push(offset);
  33443. this._linesIndices.push(offset + 2);
  33444. this._linesIndices.push(offset + 3);
  33445. }
  33446. };
  33447. EdgesRenderer.prototype._generateEdgesLines = function () {
  33448. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33449. var indices = this._source.getIndices();
  33450. // First let's find adjacencies
  33451. var adjacencies = new Array();
  33452. var faceNormals = new Array();
  33453. var index;
  33454. var faceAdjacencies;
  33455. // Prepare faces
  33456. for (index = 0; index < indices.length; index += 3) {
  33457. faceAdjacencies = new FaceAdjacencies();
  33458. var p0Index = indices[index];
  33459. var p1Index = indices[index + 1];
  33460. var p2Index = indices[index + 2];
  33461. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  33462. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  33463. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  33464. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  33465. faceNormal.normalize();
  33466. faceNormals.push(faceNormal);
  33467. adjacencies.push(faceAdjacencies);
  33468. }
  33469. // Scan
  33470. for (index = 0; index < adjacencies.length; index++) {
  33471. faceAdjacencies = adjacencies[index];
  33472. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  33473. var otherFaceAdjacencies = adjacencies[otherIndex];
  33474. if (faceAdjacencies.edgesConnectedCount === 3) {
  33475. break;
  33476. }
  33477. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  33478. continue;
  33479. }
  33480. var otherP0 = indices[otherIndex * 3];
  33481. var otherP1 = indices[otherIndex * 3 + 1];
  33482. var otherP2 = indices[otherIndex * 3 + 2];
  33483. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  33484. var otherEdgeIndex;
  33485. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  33486. continue;
  33487. }
  33488. switch (edgeIndex) {
  33489. case 0:
  33490. if (this._checkVerticesInsteadOfIndices) {
  33491. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33492. }
  33493. else {
  33494. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  33495. }
  33496. break;
  33497. case 1:
  33498. if (this._checkVerticesInsteadOfIndices) {
  33499. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33500. }
  33501. else {
  33502. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  33503. }
  33504. break;
  33505. case 2:
  33506. if (this._checkVerticesInsteadOfIndices) {
  33507. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33508. }
  33509. else {
  33510. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  33511. }
  33512. break;
  33513. }
  33514. if (otherEdgeIndex === -1) {
  33515. continue;
  33516. }
  33517. faceAdjacencies.edges[edgeIndex] = otherIndex;
  33518. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  33519. faceAdjacencies.edgesConnectedCount++;
  33520. otherFaceAdjacencies.edgesConnectedCount++;
  33521. if (faceAdjacencies.edgesConnectedCount === 3) {
  33522. break;
  33523. }
  33524. }
  33525. }
  33526. }
  33527. // Create lines
  33528. for (index = 0; index < adjacencies.length; index++) {
  33529. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  33530. var current = adjacencies[index];
  33531. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  33532. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  33533. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  33534. }
  33535. // Merge into a single mesh
  33536. var engine = this._source.getScene().getEngine();
  33537. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  33538. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  33539. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  33540. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  33541. this._ib = engine.createIndexBuffer(this._linesIndices);
  33542. this._indicesCount = this._linesIndices.length;
  33543. };
  33544. EdgesRenderer.prototype.render = function () {
  33545. if (!this._lineShader.isReady()) {
  33546. return;
  33547. }
  33548. var scene = this._source.getScene();
  33549. var engine = scene.getEngine();
  33550. this._lineShader._preBind();
  33551. // VBOs
  33552. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  33553. scene.resetCachedMaterial();
  33554. this._lineShader.setColor4("color", this._source.edgesColor);
  33555. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  33556. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  33557. this._lineShader.bind(this._source.getWorldMatrix());
  33558. // Draw order
  33559. engine.draw(true, 0, this._indicesCount);
  33560. this._lineShader.unbind();
  33561. engine.setDepthWrite(true);
  33562. };
  33563. return EdgesRenderer;
  33564. })();
  33565. BABYLON.EdgesRenderer = EdgesRenderer;
  33566. })(BABYLON || (BABYLON = {}));
  33567. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, glossiness);\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, glossiness);\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n\t#ifdef SPECULAR\r\n\t\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\t\tspecularColor = specularMapColor.rgb;\r\n\t\t#ifdef GLOSSINESS\r\n\t\t\tglossiness = specularMapColor.a;\r\n\t\t#endif\r\n\t#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\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// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#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#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","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}"};
  33568. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function i(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},i.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},i.prototype.multiply=function(t){return new i(this.r*t.r,this.g*t.g,this.b*t.b)},i.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},i.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},i.prototype.equalsFloats=function(t,i,o){return this.r===t&&this.g===i&&this.b===o},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b)},i.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},i.prototype.clone=function(){return new i(this.r,this.g,this.b)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},i.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||7!==o.length)return t.Tools.Warn(\"Color3.FromHexString must be called with a string like #FFFFFF\"),new i(0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16);return i.FromInts(n,r,s)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2])},i.FromInts=function(t,o,n){return new i(t/255,o/255,n/255)},i.Lerp=function(t,o,n){var r=t.r+(o.r-t.r)*n,s=t.g+(o.g-t.g)*n,e=t.b+(o.b-t.b)*n;return new i(r,s,e)},i.Red=function(){return new i(1,0,0)},i.Green=function(){return new i(0,1,0)},i.Blue=function(){return new i(0,0,1)},i.Black=function(){return new i(0,0,0)},i.White=function(){return new i(1,1,1)},i.Purple=function(){return new i(.5,0,.5)},i.Magenta=function(){return new i(1,0,1)},i.Yellow=function(){return new i(1,1,0)},i.Gray=function(){return new i(.5,.5,.5)},i}();t.Color3=i;var o=function(){function i(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return i.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},i.prototype.add=function(t){return new i(this.r+t.r,this.g+t.g,this.b+t.b,this.a+t.a)},i.prototype.subtract=function(t){return new i(this.r-t.r,this.g-t.g,this.b-t.b,this.a-t.a)},i.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},i.prototype.scale=function(t){return new i(this.r*t,this.g*t,this.b*t,this.a*t)},i.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},i.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},i.prototype.clone=function(){return new i(this.r,this.g,this.b,this.a)},i.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},i.prototype.toHexString=function(){var i=255*this.r|0,o=255*this.g|0,n=255*this.b|0,r=255*this.a|0;return\"#\"+t.Tools.ToHex(i)+t.Tools.ToHex(o)+t.Tools.ToHex(n)+t.Tools.ToHex(r)},i.FromHexString=function(o){if(\"#\"!==o.substring(0,1)||9!==o.length)return t.Tools.Warn(\"Color4.FromHexString must be called with a string like #FFFFFFFF\"),new i(0,0,0,0);var n=parseInt(o.substring(1,3),16),r=parseInt(o.substring(3,5),16),s=parseInt(o.substring(5,7),16),e=parseInt(o.substring(7,9),16);return i.FromInts(n,r,s,e)},i.Lerp=function(t,o,n){var r=new i(0,0,0,0);return i.LerpToRef(t,o,n,r),r},i.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromInts=function(t,o,n,r){return new i(t/255,o/255,n/255,r/255)},i}();t.Color4=o;var n=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromFloatArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),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(o,n,r){var s,e,a,h=i.Normalize(o),u=i.Normalize(r),l=f.X,m=f.Y,x=0,y=0,c=0,p=0,z=0,M=0,w=0,d=-1,I=0,D=0;t.Tools.WithinEpsilon(u.z,0,t.Engine.Epsilon)?M=1:t.Tools.WithinEpsilon(u.x,0,t.Engine.Epsilon)?p=1:(w=u.z/u.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),e=new i(p,z,M),e.normalize(),a=i.Cross(u,e),a.normalize(),s=i.Cross(h,e),s.normalize(),i.Dot(u,s)<0&&(d=1),D=i.Dot(h,e),D=Math.min(1,Math.max(-1,D)),c=Math.acos(D)*d,i.Dot(e,l)<0&&(c=Math.PI+c,e=e.scaleInPlace(-1),a=a.scaleInPlace(-1),I++);var S,v;return p=0,z=0,M=0,d=-1,t.Tools.WithinEpsilon(u.z,0,t.Engine.Epsilon)?p=1:(w=e.z/e.x,p=-w*Math.sqrt(1/(1+w*w)),M=Math.sqrt(1/(1+w*w))),S=new i(p,z,M),S.normalize(),v=i.Cross(S,e),v.normalize(),s=i.Cross(u,S),s.normalize(),i.Dot(e,s)<0&&(d=1),D=i.Dot(u,S),D=Math.min(1,Math.max(-1,D)),y=Math.acos(D)*d,i.Dot(v,m)<0&&(y=Math.PI+y,v=v.scaleInPlace(-1),S=S.scaleInPlace(-1),I++),d=-1,s=i.Cross(l,e),s.normalize(),i.Dot(s,m)<0&&(d=1),D=i.Dot(e,l),D=Math.min(1,Math.max(-1,D)),x=-Math.acos(D)*d,0>D&&2>I&&(x=Math.PI+x),new i(y,x,c)},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i,o){return void 0===o&&(o=t.Engine.Epsilon),i&&t.Tools.WithinEpsilon(this.x,i.x,o)&&t.Tools.WithinEpsilon(this.y,i.y,o)&&t.Tools.WithinEpsilon(this.z,i.z,o)&&t.Tools.WithinEpsilon(this.w,i.w,o)},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,r=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,n,r,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},i.prototype.add=function(t){var o=new i;return this.addToRef(t,o),o},i.prototype.addToRef=function(t,i){for(var o=0;16>o;o++)i.m[o]=this.m[o]+t.m[o];return this},i.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,d=u*p-f*x,I=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*d+h*I),g=s*M-e*d+h*D,T=-(s*w-e*I+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,F=e*c-a*y,A=s*p-h*x,P=s*c-a*x,C=s*y-e*x,E=a*f-h*m,L=e*f-h*l,q=e*m-a*l,Z=s*f-h*u,H=s*m-a*u,W=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*d+r*I)*R,t.m[9]=-(i*M-o*d+r*D)*R,t.m[13]=(i*w-o*I+n*D)*R,t.m[2]=(o*_-n*b+r*F)*R,t.m[6]=-(i*_-n*A+r*P)*R,t.m[10]=(i*b-o*A+r*C)*R,t.m[14]=-(i*F-o*P+n*C)*R,t.m[3]=-(o*E-n*L+r*q)*R,t.m[7]=(i*E-n*Z+r*H)*R,t.m[11]=-(i*L-o*Z+r*W)*R,t.m[15]=(i*q-o*H+n*W)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],d=t.m[1],I=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],F=t.m[11],A=t.m[12],P=t.m[13],C=t.m[14],E=t.m[15];return i[o]=n*w+r*S+s*R+e*A,i[o+1]=n*d+r*v+s*_+e*P,i[o+2]=n*I+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*F+e*E,i[o+4]=a*w+h*S+u*R+l*A,i[o+5]=a*d+h*v+u*_+l*P,i[o+6]=a*I+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*F+l*E,i[o+8]=m*w+f*S+x*R+y*A,i[o+9]=m*d+f*v+x*_+y*P,i[o+10]=m*I+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*F+y*E,i[o+12]=c*w+p*S+z*R+M*A,i[o+13]=c*d+p*v+z*_+M*P,i[o+14]=c*I+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*F+M*E,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));\n\nvar l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],r.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromFloat32ArrayToRefScaled=function(t,i,o,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]*o},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),d=SIMD.float32x4(0,1,0,0),I=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(n).multiply(r).multiply(m)},i.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},i.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=l;var m=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o,n,r,s,e=0,a=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else if(o=1/this.direction.x,n=(t.x-this.origin.x)*o,r=(i.x-this.origin.x)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(o=1/this.direction.y,n=(t.y-this.origin.y)*o,r=(i.y-this.origin.y)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(o=1/this.direction.z,n=(t.z-this.origin.z)*o,r=(i.z-this.origin.z)*o,r===-(1/0)&&(r=1/0),n>r&&(s=n,n=r,r=s),e=Math.max(n,e),a=Math.min(r,a),e>a)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=m,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function i(t,i){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var o=0;o<t.length;o++)this._curve[o]=t[o].clone();this._compute(i)}return i.prototype.getCurve=function(){return this._curve},i.prototype.getTangents=function(){return this._tangents},i.prototype.getNormals=function(){return this._normals},i.prototype.getBinormals=function(){return this._binormals},i.prototype.getDistances=function(){return this._distances},i.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},i.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u=1;i>u;u++)s=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=s.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+s.length(),a=this._tangents[u],h=this._binormals[u-1],this._normals[u]=r.Cross(h,a),this._normals[u].normalize(),this._binormals[u]=r.Cross(a,this._normals[u]),this._binormals[u].normalize()},i.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0===o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},i.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0===o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},i.prototype._normalVector=function(i,o,n){var s;if(void 0===n||null===n){var e;t.Tools.WithinEpsilon(o.y,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.x,1,t.Engine.Epsilon)?t.Tools.WithinEpsilon(o.z,1,t.Engine.Epsilon)||(e=new r(0,0,1)):e=new r(1,0,0):e=new r(0,-1,0),s=r.Cross(o,e)}else s=r.Cross(o,n),r.CrossToRef(s,o,s);return s.normalize(),s},i}();t.Path3D=w;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,i.x,o.x,n.x),a(h/s,i.y,o.y,n.y),a(h/s,i.z,o.z,n.z)));return new t(e)},t.CreateCubicBezier=function(i,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,i.x,o.x,n.x,s.x),h(u/e,i.y,o.y,n.y,s.y),h(u/e,i.z,o.z,n.z,s.z)));return new t(a)},t.CreateHermiteSpline=function(i,o,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(r.Hermite(i,o,n,s,u*h));return new t(a)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=i.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new t(n);return e},t.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},t}();t.Curve3=d;var I=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=I;var D=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function t(){}return Object.defineProperty(t,\"IsEnabled\",{get:function(){return t._isEnabled},enumerable:!0,configurable:!0}),t.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,t._isEnabled=!1},t.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(r.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(r.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(r.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),t._isEnabled=!0)},t._isEnabled=!1,t}();t.SIMDHelper=_}(BABYLON||(BABYLON={}));";
  33569. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  33570. module.exports = BABYLON;
  33571. };