babylon.2.2.max.js 1.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693
  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(0, 0, 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. // Cache
  7790. this._localScaling = BABYLON.Matrix.Zero();
  7791. this._localRotation = BABYLON.Matrix.Zero();
  7792. this._localTranslation = BABYLON.Matrix.Zero();
  7793. this._localBillboard = BABYLON.Matrix.Zero();
  7794. this._localPivotScaling = BABYLON.Matrix.Zero();
  7795. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7796. this._localWorld = BABYLON.Matrix.Zero();
  7797. this._worldMatrix = BABYLON.Matrix.Zero();
  7798. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7799. this._absolutePosition = BABYLON.Vector3.Zero();
  7800. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7801. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7802. this._isDirty = false;
  7803. this._pivotMatrix = BABYLON.Matrix.Identity();
  7804. this._isDisposed = false;
  7805. this._renderId = 0;
  7806. this._intersectionsInProgress = new Array();
  7807. this._onAfterWorldMatrixUpdate = new Array();
  7808. this._isWorldMatrixFrozen = false;
  7809. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7810. if (collidedMesh === void 0) { collidedMesh = null; }
  7811. //TODO move this to the collision coordinator!
  7812. if (_this.getScene().workerCollisions)
  7813. newPosition.multiplyInPlace(_this._collider.radius);
  7814. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7815. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7816. _this.position.addInPlace(_this._diffPositionForCollisions);
  7817. }
  7818. if (_this.onCollide && collidedMesh) {
  7819. _this.onCollide(collidedMesh);
  7820. }
  7821. };
  7822. scene.addMesh(this);
  7823. }
  7824. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7825. get: function () {
  7826. return AbstractMesh._BILLBOARDMODE_NONE;
  7827. },
  7828. enumerable: true,
  7829. configurable: true
  7830. });
  7831. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7832. get: function () {
  7833. return AbstractMesh._BILLBOARDMODE_X;
  7834. },
  7835. enumerable: true,
  7836. configurable: true
  7837. });
  7838. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7839. get: function () {
  7840. return AbstractMesh._BILLBOARDMODE_Y;
  7841. },
  7842. enumerable: true,
  7843. configurable: true
  7844. });
  7845. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7846. get: function () {
  7847. return AbstractMesh._BILLBOARDMODE_Z;
  7848. },
  7849. enumerable: true,
  7850. configurable: true
  7851. });
  7852. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7853. get: function () {
  7854. return AbstractMesh._BILLBOARDMODE_ALL;
  7855. },
  7856. enumerable: true,
  7857. configurable: true
  7858. });
  7859. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7860. // Methods
  7861. get: function () {
  7862. return false;
  7863. },
  7864. enumerable: true,
  7865. configurable: true
  7866. });
  7867. AbstractMesh.prototype.getLOD = function (camera) {
  7868. return this;
  7869. };
  7870. AbstractMesh.prototype.getTotalVertices = function () {
  7871. return 0;
  7872. };
  7873. AbstractMesh.prototype.getIndices = function () {
  7874. return null;
  7875. };
  7876. AbstractMesh.prototype.getVerticesData = function (kind) {
  7877. return null;
  7878. };
  7879. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7880. return false;
  7881. };
  7882. AbstractMesh.prototype.getBoundingInfo = function () {
  7883. if (this._masterMesh) {
  7884. return this._masterMesh.getBoundingInfo();
  7885. }
  7886. if (!this._boundingInfo) {
  7887. this._updateBoundingInfo();
  7888. }
  7889. return this._boundingInfo;
  7890. };
  7891. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7892. get: function () {
  7893. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7894. },
  7895. enumerable: true,
  7896. configurable: true
  7897. });
  7898. AbstractMesh.prototype._preActivate = function () {
  7899. };
  7900. AbstractMesh.prototype._activate = function (renderId) {
  7901. this._renderId = renderId;
  7902. };
  7903. AbstractMesh.prototype.getWorldMatrix = function () {
  7904. if (this._masterMesh) {
  7905. return this._masterMesh.getWorldMatrix();
  7906. }
  7907. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7908. this.computeWorldMatrix();
  7909. }
  7910. return this._worldMatrix;
  7911. };
  7912. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7913. get: function () {
  7914. return this._worldMatrix;
  7915. },
  7916. enumerable: true,
  7917. configurable: true
  7918. });
  7919. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7920. get: function () {
  7921. return this._absolutePosition;
  7922. },
  7923. enumerable: true,
  7924. configurable: true
  7925. });
  7926. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7927. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7928. this.computeWorldMatrix(true);
  7929. this._isWorldMatrixFrozen = true;
  7930. };
  7931. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7932. this._isWorldMatrixFrozen = false;
  7933. this.computeWorldMatrix(true);
  7934. };
  7935. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7936. get: function () {
  7937. return this._isWorldMatrixFrozen;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7943. axis.normalize();
  7944. if (!this.rotationQuaternion) {
  7945. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7946. this.rotation = BABYLON.Vector3.Zero();
  7947. }
  7948. if (!space || space === BABYLON.Space.LOCAL) {
  7949. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7950. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7951. }
  7952. else {
  7953. if (this.parent) {
  7954. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7955. invertParentWorldMatrix.invert();
  7956. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7957. }
  7958. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7959. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7960. }
  7961. };
  7962. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7963. var displacementVector = axis.scale(distance);
  7964. if (!space || space === BABYLON.Space.LOCAL) {
  7965. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7966. this.setPositionWithLocalVector(tempV3);
  7967. }
  7968. else {
  7969. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7970. }
  7971. };
  7972. AbstractMesh.prototype.getAbsolutePosition = function () {
  7973. this.computeWorldMatrix();
  7974. return this._absolutePosition;
  7975. };
  7976. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7977. if (!absolutePosition) {
  7978. return;
  7979. }
  7980. var absolutePositionX;
  7981. var absolutePositionY;
  7982. var absolutePositionZ;
  7983. if (absolutePosition.x === undefined) {
  7984. if (arguments.length < 3) {
  7985. return;
  7986. }
  7987. absolutePositionX = arguments[0];
  7988. absolutePositionY = arguments[1];
  7989. absolutePositionZ = arguments[2];
  7990. }
  7991. else {
  7992. absolutePositionX = absolutePosition.x;
  7993. absolutePositionY = absolutePosition.y;
  7994. absolutePositionZ = absolutePosition.z;
  7995. }
  7996. if (this.parent) {
  7997. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7998. invertParentWorldMatrix.invert();
  7999. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8000. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8001. }
  8002. else {
  8003. this.position.x = absolutePositionX;
  8004. this.position.y = absolutePositionY;
  8005. this.position.z = absolutePositionZ;
  8006. }
  8007. };
  8008. // ================================== Point of View Movement =================================
  8009. /**
  8010. * Perform relative position change from the point of view of behind the front of the mesh.
  8011. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8012. * Supports definition of mesh facing forward or backward.
  8013. * @param {number} amountRight
  8014. * @param {number} amountUp
  8015. * @param {number} amountForward
  8016. */
  8017. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8018. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8019. };
  8020. /**
  8021. * Calculate relative position change from the point of view of behind the front of the mesh.
  8022. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8023. * Supports definition of mesh facing forward or backward.
  8024. * @param {number} amountRight
  8025. * @param {number} amountUp
  8026. * @param {number} amountForward
  8027. */
  8028. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8029. var rotMatrix = new BABYLON.Matrix();
  8030. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8031. rotQuaternion.toRotationMatrix(rotMatrix);
  8032. var translationDelta = BABYLON.Vector3.Zero();
  8033. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8034. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8035. return translationDelta;
  8036. };
  8037. // ================================== Point of View Rotation =================================
  8038. /**
  8039. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8040. * Supports definition of mesh facing forward or backward.
  8041. * @param {number} flipBack
  8042. * @param {number} twirlClockwise
  8043. * @param {number} tiltRight
  8044. */
  8045. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8046. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8047. };
  8048. /**
  8049. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8050. * Supports definition of mesh facing forward or backward.
  8051. * @param {number} flipBack
  8052. * @param {number} twirlClockwise
  8053. * @param {number} tiltRight
  8054. */
  8055. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8056. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8057. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8058. };
  8059. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8060. this._pivotMatrix = matrix;
  8061. this._cache.pivotMatrixUpdated = true;
  8062. };
  8063. AbstractMesh.prototype.getPivotMatrix = function () {
  8064. return this._pivotMatrix;
  8065. };
  8066. AbstractMesh.prototype._isSynchronized = function () {
  8067. if (this._isDirty) {
  8068. return false;
  8069. }
  8070. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8071. return false;
  8072. if (this._cache.pivotMatrixUpdated) {
  8073. return false;
  8074. }
  8075. if (this.infiniteDistance) {
  8076. return false;
  8077. }
  8078. if (!this._cache.position.equals(this.position))
  8079. return false;
  8080. if (this.rotationQuaternion) {
  8081. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8082. return false;
  8083. }
  8084. else {
  8085. if (!this._cache.rotation.equals(this.rotation))
  8086. return false;
  8087. }
  8088. if (!this._cache.scaling.equals(this.scaling))
  8089. return false;
  8090. return true;
  8091. };
  8092. AbstractMesh.prototype._initCache = function () {
  8093. _super.prototype._initCache.call(this);
  8094. this._cache.localMatrixUpdated = false;
  8095. this._cache.position = BABYLON.Vector3.Zero();
  8096. this._cache.scaling = BABYLON.Vector3.Zero();
  8097. this._cache.rotation = BABYLON.Vector3.Zero();
  8098. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8099. };
  8100. AbstractMesh.prototype.markAsDirty = function (property) {
  8101. if (property === "rotation") {
  8102. this.rotationQuaternion = null;
  8103. }
  8104. this._currentRenderId = Number.MAX_VALUE;
  8105. this._isDirty = true;
  8106. };
  8107. AbstractMesh.prototype._updateBoundingInfo = function () {
  8108. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8109. this._boundingInfo._update(this.worldMatrixFromCache);
  8110. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8111. };
  8112. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8113. if (!this.subMeshes) {
  8114. return;
  8115. }
  8116. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8117. var subMesh = this.subMeshes[subIndex];
  8118. subMesh.updateBoundingInfo(matrix);
  8119. }
  8120. };
  8121. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8122. if (this._isWorldMatrixFrozen) {
  8123. return this._worldMatrix;
  8124. }
  8125. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8126. return this._worldMatrix;
  8127. }
  8128. this._cache.position.copyFrom(this.position);
  8129. this._cache.scaling.copyFrom(this.scaling);
  8130. this._cache.pivotMatrixUpdated = false;
  8131. this._currentRenderId = this.getScene().getRenderId();
  8132. this._isDirty = false;
  8133. // Scaling
  8134. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8135. // Rotation
  8136. if (this.rotationQuaternion) {
  8137. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8138. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8139. }
  8140. else {
  8141. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8142. this._cache.rotation.copyFrom(this.rotation);
  8143. }
  8144. // Translation
  8145. if (this.infiniteDistance && !this.parent) {
  8146. var camera = this.getScene().activeCamera;
  8147. if (camera) {
  8148. var cameraWorldMatrix = camera.getWorldMatrix();
  8149. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8150. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8151. }
  8152. }
  8153. else {
  8154. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8155. }
  8156. // Composing transformations
  8157. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8158. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8159. // Billboarding
  8160. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8161. var localPosition = this.position.clone();
  8162. var zero = this.getScene().activeCamera.globalPosition.clone();
  8163. if (this.parent && this.parent.position) {
  8164. localPosition.addInPlace(this.parent.position);
  8165. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8166. }
  8167. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  8168. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8169. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8170. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8171. zero.y = localPosition.y + 0.001;
  8172. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8173. zero.z = localPosition.z + 0.001;
  8174. }
  8175. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8176. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8177. this._localBillboard.invert();
  8178. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8179. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8180. }
  8181. // Local world
  8182. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8183. // Parent
  8184. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8185. this._markSyncedWithParent();
  8186. if (this._meshToBoneReferal) {
  8187. if (!this._localMeshReferalTransform) {
  8188. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8189. }
  8190. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8191. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8192. }
  8193. else {
  8194. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8195. }
  8196. }
  8197. else {
  8198. this._worldMatrix.copyFrom(this._localWorld);
  8199. }
  8200. // Bounding info
  8201. this._updateBoundingInfo();
  8202. // Absolute position
  8203. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8204. // Callbacks
  8205. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8206. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8207. }
  8208. return this._worldMatrix;
  8209. };
  8210. /**
  8211. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8212. * @param func: callback function to add
  8213. */
  8214. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8215. this._onAfterWorldMatrixUpdate.push(func);
  8216. };
  8217. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8218. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8219. if (index > -1) {
  8220. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8221. }
  8222. };
  8223. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8224. this.computeWorldMatrix();
  8225. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8226. };
  8227. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8228. this.computeWorldMatrix();
  8229. var invLocalWorldMatrix = this._localWorld.clone();
  8230. invLocalWorldMatrix.invert();
  8231. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8232. };
  8233. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8234. this.computeWorldMatrix(true);
  8235. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8236. };
  8237. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8238. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8239. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8240. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8241. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8242. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8243. /// <returns>Mesh oriented towards targetMesh</returns>
  8244. yawCor = yawCor || 0; // default to zero if undefined
  8245. pitchCor = pitchCor || 0;
  8246. rollCor = rollCor || 0;
  8247. var dv = targetPoint.subtract(this.position);
  8248. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8249. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8250. var pitch = Math.atan2(dv.y, len);
  8251. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8252. };
  8253. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8254. this._meshToBoneReferal = affectedMesh;
  8255. this.parent = bone;
  8256. };
  8257. AbstractMesh.prototype.detachFromBone = function () {
  8258. this._meshToBoneReferal = null;
  8259. this.parent = null;
  8260. };
  8261. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8262. return this._boundingInfo.isInFrustum(frustumPlanes);
  8263. };
  8264. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8265. if (!camera) {
  8266. camera = this.getScene().activeCamera;
  8267. }
  8268. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8269. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8270. return false;
  8271. }
  8272. return true;
  8273. };
  8274. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8275. if (!this._boundingInfo || !mesh._boundingInfo) {
  8276. return false;
  8277. }
  8278. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8279. };
  8280. AbstractMesh.prototype.intersectsPoint = function (point) {
  8281. if (!this._boundingInfo) {
  8282. return false;
  8283. }
  8284. return this._boundingInfo.intersectsPoint(point);
  8285. };
  8286. // Physics
  8287. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8288. var physicsEngine = this.getScene().getPhysicsEngine();
  8289. if (!physicsEngine) {
  8290. return;
  8291. }
  8292. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8293. if (impostor.impostor) {
  8294. // Old API
  8295. options = impostor;
  8296. impostor = impostor.impostor;
  8297. }
  8298. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8299. physicsEngine._unregisterMesh(this);
  8300. return;
  8301. }
  8302. if (!options) {
  8303. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8304. }
  8305. else {
  8306. if (!options.mass && options.mass !== 0)
  8307. options.mass = 0;
  8308. if (!options.friction && options.friction !== 0)
  8309. options.friction = 0.2;
  8310. if (!options.restitution && options.restitution !== 0)
  8311. options.restitution = 0.2;
  8312. }
  8313. this._physicImpostor = impostor;
  8314. this._physicsMass = options.mass;
  8315. this._physicsFriction = options.friction;
  8316. this._physicRestitution = options.restitution;
  8317. return physicsEngine._registerMesh(this, impostor, options);
  8318. };
  8319. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8320. if (!this._physicImpostor) {
  8321. return BABYLON.PhysicsEngine.NoImpostor;
  8322. }
  8323. return this._physicImpostor;
  8324. };
  8325. AbstractMesh.prototype.getPhysicsMass = function () {
  8326. if (!this._physicsMass) {
  8327. return 0;
  8328. }
  8329. return this._physicsMass;
  8330. };
  8331. AbstractMesh.prototype.getPhysicsFriction = function () {
  8332. if (!this._physicsFriction) {
  8333. return 0;
  8334. }
  8335. return this._physicsFriction;
  8336. };
  8337. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8338. if (!this._physicRestitution) {
  8339. return 0;
  8340. }
  8341. return this._physicRestitution;
  8342. };
  8343. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8344. if (!camera) {
  8345. camera = this.getScene().activeCamera;
  8346. }
  8347. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8348. };
  8349. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8350. if (!camera) {
  8351. camera = this.getScene().activeCamera;
  8352. }
  8353. return this.absolutePosition.subtract(camera.position).length();
  8354. };
  8355. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8356. if (!this._physicImpostor) {
  8357. return;
  8358. }
  8359. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8360. };
  8361. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8362. if (!this._physicImpostor) {
  8363. return;
  8364. }
  8365. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8366. };
  8367. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8368. if (!this._physicImpostor) {
  8369. return;
  8370. }
  8371. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8372. };
  8373. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8374. // Collisions
  8375. get: function () {
  8376. return this._checkCollisions;
  8377. },
  8378. set: function (collisionEnabled) {
  8379. this._checkCollisions = collisionEnabled;
  8380. if (this.getScene().workerCollisions) {
  8381. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8382. }
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8388. var globalPosition = this.getAbsolutePosition();
  8389. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8390. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8391. this._collider.radius = this.ellipsoid;
  8392. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8393. };
  8394. // Submeshes octree
  8395. /**
  8396. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8397. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8398. */
  8399. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8400. if (maxCapacity === void 0) { maxCapacity = 64; }
  8401. if (maxDepth === void 0) { maxDepth = 2; }
  8402. if (!this._submeshesOctree) {
  8403. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8404. }
  8405. this.computeWorldMatrix(true);
  8406. // Update octree
  8407. var bbox = this.getBoundingInfo().boundingBox;
  8408. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8409. return this._submeshesOctree;
  8410. };
  8411. // Collisions
  8412. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8413. this._generatePointsArray();
  8414. // Transformation
  8415. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8416. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8417. subMesh._lastColliderWorldVertices = [];
  8418. subMesh._trianglePlanes = [];
  8419. var start = subMesh.verticesStart;
  8420. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8421. for (var i = start; i < end; i++) {
  8422. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8423. }
  8424. }
  8425. // Collide
  8426. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8427. if (collider.collisionFound) {
  8428. collider.collidedMesh = this;
  8429. }
  8430. };
  8431. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8432. var subMeshes;
  8433. var len;
  8434. // Octrees
  8435. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8436. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8437. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8438. len = intersections.length;
  8439. subMeshes = intersections.data;
  8440. }
  8441. else {
  8442. subMeshes = this.subMeshes;
  8443. len = subMeshes.length;
  8444. }
  8445. for (var index = 0; index < len; index++) {
  8446. var subMesh = subMeshes[index];
  8447. // Bounding test
  8448. if (len > 1 && !subMesh._checkCollision(collider))
  8449. continue;
  8450. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8451. }
  8452. };
  8453. AbstractMesh.prototype._checkCollision = function (collider) {
  8454. // Bounding box test
  8455. if (!this._boundingInfo._checkCollision(collider))
  8456. return;
  8457. // Transformation matrix
  8458. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8459. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8460. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8461. };
  8462. // Picking
  8463. AbstractMesh.prototype._generatePointsArray = function () {
  8464. return false;
  8465. };
  8466. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8467. var pickingInfo = new BABYLON.PickingInfo();
  8468. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8469. return pickingInfo;
  8470. }
  8471. if (!this._generatePointsArray()) {
  8472. return pickingInfo;
  8473. }
  8474. var intersectInfo = null;
  8475. // Octrees
  8476. var subMeshes;
  8477. var len;
  8478. if (this._submeshesOctree && this.useOctreeForPicking) {
  8479. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8480. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8481. len = intersections.length;
  8482. subMeshes = intersections.data;
  8483. }
  8484. else {
  8485. subMeshes = this.subMeshes;
  8486. len = subMeshes.length;
  8487. }
  8488. for (var index = 0; index < len; index++) {
  8489. var subMesh = subMeshes[index];
  8490. // Bounding test
  8491. if (len > 1 && !subMesh.canIntersects(ray))
  8492. continue;
  8493. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8494. if (currentIntersectInfo) {
  8495. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8496. intersectInfo = currentIntersectInfo;
  8497. intersectInfo.subMeshId = index;
  8498. if (fastCheck) {
  8499. break;
  8500. }
  8501. }
  8502. }
  8503. }
  8504. if (intersectInfo) {
  8505. // Get picked point
  8506. var world = this.getWorldMatrix();
  8507. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8508. var direction = ray.direction.clone();
  8509. direction = direction.scale(intersectInfo.distance);
  8510. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8511. var pickedPoint = worldOrigin.add(worldDirection);
  8512. // Return result
  8513. pickingInfo.hit = true;
  8514. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8515. pickingInfo.pickedPoint = pickedPoint;
  8516. pickingInfo.pickedMesh = this;
  8517. pickingInfo.bu = intersectInfo.bu;
  8518. pickingInfo.bv = intersectInfo.bv;
  8519. pickingInfo.faceId = intersectInfo.faceId;
  8520. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8521. return pickingInfo;
  8522. }
  8523. return pickingInfo;
  8524. };
  8525. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8526. return null;
  8527. };
  8528. AbstractMesh.prototype.releaseSubMeshes = function () {
  8529. if (this.subMeshes) {
  8530. while (this.subMeshes.length) {
  8531. this.subMeshes[0].dispose();
  8532. }
  8533. }
  8534. else {
  8535. this.subMeshes = new Array();
  8536. }
  8537. };
  8538. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8539. var index;
  8540. // Physics
  8541. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8542. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8543. }
  8544. // Intersections in progress
  8545. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8546. var other = this._intersectionsInProgress[index];
  8547. var pos = other._intersectionsInProgress.indexOf(this);
  8548. other._intersectionsInProgress.splice(pos, 1);
  8549. }
  8550. this._intersectionsInProgress = [];
  8551. // SubMeshes
  8552. this.releaseSubMeshes();
  8553. // Remove from scene
  8554. this.getScene().removeMesh(this);
  8555. if (!doNotRecurse) {
  8556. // Particles
  8557. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8558. if (this.getScene().particleSystems[index].emitter === this) {
  8559. this.getScene().particleSystems[index].dispose();
  8560. index--;
  8561. }
  8562. }
  8563. // Children
  8564. var objects = this.getScene().meshes.slice(0);
  8565. for (index = 0; index < objects.length; index++) {
  8566. if (objects[index].parent === this) {
  8567. objects[index].dispose();
  8568. }
  8569. }
  8570. }
  8571. else {
  8572. for (index = 0; index < this.getScene().meshes.length; index++) {
  8573. var obj = this.getScene().meshes[index];
  8574. if (obj.parent === this) {
  8575. obj.parent = null;
  8576. obj.computeWorldMatrix(true);
  8577. }
  8578. }
  8579. }
  8580. this._onAfterWorldMatrixUpdate = [];
  8581. this._isDisposed = true;
  8582. // Callback
  8583. if (this.onDispose) {
  8584. this.onDispose();
  8585. }
  8586. };
  8587. // Statics
  8588. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8589. AbstractMesh._BILLBOARDMODE_X = 1;
  8590. AbstractMesh._BILLBOARDMODE_Y = 2;
  8591. AbstractMesh._BILLBOARDMODE_Z = 4;
  8592. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8593. return AbstractMesh;
  8594. })(BABYLON.Node);
  8595. BABYLON.AbstractMesh = AbstractMesh;
  8596. })(BABYLON || (BABYLON = {}));
  8597. var BABYLON;
  8598. (function (BABYLON) {
  8599. var Light = (function (_super) {
  8600. __extends(Light, _super);
  8601. function Light(name, scene) {
  8602. _super.call(this, name, scene);
  8603. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8604. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8605. this.intensity = 1.0;
  8606. this.range = Number.MAX_VALUE;
  8607. this.includeOnlyWithLayerMask = 0;
  8608. this.includedOnlyMeshes = new Array();
  8609. this.excludedMeshes = new Array();
  8610. this.excludeWithLayerMask = 0;
  8611. this._excludedMeshesIds = new Array();
  8612. this._includedOnlyMeshesIds = new Array();
  8613. scene.addLight(this);
  8614. }
  8615. Light.prototype.getShadowGenerator = function () {
  8616. return this._shadowGenerator;
  8617. };
  8618. Light.prototype.getAbsolutePosition = function () {
  8619. return BABYLON.Vector3.Zero();
  8620. };
  8621. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8622. };
  8623. Light.prototype._getWorldMatrix = function () {
  8624. return BABYLON.Matrix.Identity();
  8625. };
  8626. Light.prototype.canAffectMesh = function (mesh) {
  8627. if (!mesh) {
  8628. return true;
  8629. }
  8630. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8631. return false;
  8632. }
  8633. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8634. return false;
  8635. }
  8636. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8637. return false;
  8638. }
  8639. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8640. return false;
  8641. }
  8642. return true;
  8643. };
  8644. Light.prototype.getWorldMatrix = function () {
  8645. this._currentRenderId = this.getScene().getRenderId();
  8646. var worldMatrix = this._getWorldMatrix();
  8647. if (this.parent && this.parent.getWorldMatrix) {
  8648. if (!this._parentedWorldMatrix) {
  8649. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8650. }
  8651. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8652. this._markSyncedWithParent();
  8653. return this._parentedWorldMatrix;
  8654. }
  8655. return worldMatrix;
  8656. };
  8657. Light.prototype.dispose = function () {
  8658. if (this._shadowGenerator) {
  8659. this._shadowGenerator.dispose();
  8660. this._shadowGenerator = null;
  8661. }
  8662. // Remove from scene
  8663. this.getScene().removeLight(this);
  8664. };
  8665. return Light;
  8666. })(BABYLON.Node);
  8667. BABYLON.Light = Light;
  8668. })(BABYLON || (BABYLON = {}));
  8669. var BABYLON;
  8670. (function (BABYLON) {
  8671. var PointLight = (function (_super) {
  8672. __extends(PointLight, _super);
  8673. function PointLight(name, position, scene) {
  8674. _super.call(this, name, scene);
  8675. this.position = position;
  8676. }
  8677. PointLight.prototype.getAbsolutePosition = function () {
  8678. return this._transformedPosition ? this._transformedPosition : this.position;
  8679. };
  8680. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8681. if (this.parent && this.parent.getWorldMatrix) {
  8682. if (!this._transformedPosition) {
  8683. this._transformedPosition = BABYLON.Vector3.Zero();
  8684. }
  8685. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8686. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8687. return;
  8688. }
  8689. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8690. };
  8691. PointLight.prototype.getShadowGenerator = function () {
  8692. return null;
  8693. };
  8694. PointLight.prototype._getWorldMatrix = function () {
  8695. if (!this._worldMatrix) {
  8696. this._worldMatrix = BABYLON.Matrix.Identity();
  8697. }
  8698. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8699. return this._worldMatrix;
  8700. };
  8701. return PointLight;
  8702. })(BABYLON.Light);
  8703. BABYLON.PointLight = PointLight;
  8704. })(BABYLON || (BABYLON = {}));
  8705. var BABYLON;
  8706. (function (BABYLON) {
  8707. var SpotLight = (function (_super) {
  8708. __extends(SpotLight, _super);
  8709. function SpotLight(name, position, direction, angle, exponent, scene) {
  8710. _super.call(this, name, scene);
  8711. this.position = position;
  8712. this.direction = direction;
  8713. this.angle = angle;
  8714. this.exponent = exponent;
  8715. }
  8716. SpotLight.prototype.getAbsolutePosition = function () {
  8717. return this.transformedPosition ? this.transformedPosition : this.position;
  8718. };
  8719. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8720. var activeCamera = this.getScene().activeCamera;
  8721. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8722. };
  8723. SpotLight.prototype.supportsVSM = function () {
  8724. return true;
  8725. };
  8726. SpotLight.prototype.needRefreshPerFrame = function () {
  8727. return false;
  8728. };
  8729. SpotLight.prototype.setDirectionToTarget = function (target) {
  8730. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8731. return this.direction;
  8732. };
  8733. SpotLight.prototype.computeTransformedPosition = function () {
  8734. if (this.parent && this.parent.getWorldMatrix) {
  8735. if (!this.transformedPosition) {
  8736. this.transformedPosition = BABYLON.Vector3.Zero();
  8737. }
  8738. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8739. return true;
  8740. }
  8741. return false;
  8742. };
  8743. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8744. var normalizeDirection;
  8745. if (this.parent && this.parent.getWorldMatrix) {
  8746. if (!this._transformedDirection) {
  8747. this._transformedDirection = BABYLON.Vector3.Zero();
  8748. }
  8749. this.computeTransformedPosition();
  8750. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8751. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8752. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8753. }
  8754. else {
  8755. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8756. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8757. }
  8758. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8759. };
  8760. SpotLight.prototype._getWorldMatrix = function () {
  8761. if (!this._worldMatrix) {
  8762. this._worldMatrix = BABYLON.Matrix.Identity();
  8763. }
  8764. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8765. return this._worldMatrix;
  8766. };
  8767. return SpotLight;
  8768. })(BABYLON.Light);
  8769. BABYLON.SpotLight = SpotLight;
  8770. })(BABYLON || (BABYLON = {}));
  8771. var BABYLON;
  8772. (function (BABYLON) {
  8773. var HemisphericLight = (function (_super) {
  8774. __extends(HemisphericLight, _super);
  8775. function HemisphericLight(name, direction, scene) {
  8776. _super.call(this, name, scene);
  8777. this.direction = direction;
  8778. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8779. }
  8780. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8781. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8782. return this.direction;
  8783. };
  8784. HemisphericLight.prototype.getShadowGenerator = function () {
  8785. return null;
  8786. };
  8787. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8788. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8789. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8790. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8791. };
  8792. HemisphericLight.prototype._getWorldMatrix = function () {
  8793. if (!this._worldMatrix) {
  8794. this._worldMatrix = BABYLON.Matrix.Identity();
  8795. }
  8796. return this._worldMatrix;
  8797. };
  8798. return HemisphericLight;
  8799. })(BABYLON.Light);
  8800. BABYLON.HemisphericLight = HemisphericLight;
  8801. })(BABYLON || (BABYLON = {}));
  8802. var BABYLON;
  8803. (function (BABYLON) {
  8804. var DirectionalLight = (function (_super) {
  8805. __extends(DirectionalLight, _super);
  8806. function DirectionalLight(name, direction, scene) {
  8807. _super.call(this, name, scene);
  8808. this.direction = direction;
  8809. this.shadowOrthoScale = 0.5;
  8810. this.position = direction.scale(-1);
  8811. }
  8812. DirectionalLight.prototype.getAbsolutePosition = function () {
  8813. return this.transformedPosition ? this.transformedPosition : this.position;
  8814. };
  8815. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8816. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8817. return this.direction;
  8818. };
  8819. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8820. var orthoLeft = Number.MAX_VALUE;
  8821. var orthoRight = Number.MIN_VALUE;
  8822. var orthoTop = Number.MIN_VALUE;
  8823. var orthoBottom = Number.MAX_VALUE;
  8824. var tempVector3 = BABYLON.Vector3.Zero();
  8825. var activeCamera = this.getScene().activeCamera;
  8826. // Check extends
  8827. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8828. var mesh = renderList[meshIndex];
  8829. if (!mesh) {
  8830. continue;
  8831. }
  8832. var boundingInfo = mesh.getBoundingInfo();
  8833. if (!boundingInfo) {
  8834. continue;
  8835. }
  8836. var boundingBox = boundingInfo.boundingBox;
  8837. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8838. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8839. if (tempVector3.x < orthoLeft)
  8840. orthoLeft = tempVector3.x;
  8841. if (tempVector3.y < orthoBottom)
  8842. orthoBottom = tempVector3.y;
  8843. if (tempVector3.x > orthoRight)
  8844. orthoRight = tempVector3.x;
  8845. if (tempVector3.y > orthoTop)
  8846. orthoTop = tempVector3.y;
  8847. }
  8848. }
  8849. var xOffset = orthoRight - orthoLeft;
  8850. var yOffset = orthoTop - orthoBottom;
  8851. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8852. };
  8853. DirectionalLight.prototype.supportsVSM = function () {
  8854. return true;
  8855. };
  8856. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8857. return true;
  8858. };
  8859. DirectionalLight.prototype.computeTransformedPosition = function () {
  8860. if (this.parent && this.parent.getWorldMatrix) {
  8861. if (!this.transformedPosition) {
  8862. this.transformedPosition = BABYLON.Vector3.Zero();
  8863. }
  8864. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8865. return true;
  8866. }
  8867. return false;
  8868. };
  8869. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8870. if (this.parent && this.parent.getWorldMatrix) {
  8871. if (!this._transformedDirection) {
  8872. this._transformedDirection = BABYLON.Vector3.Zero();
  8873. }
  8874. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8875. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8876. return;
  8877. }
  8878. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8879. };
  8880. DirectionalLight.prototype._getWorldMatrix = function () {
  8881. if (!this._worldMatrix) {
  8882. this._worldMatrix = BABYLON.Matrix.Identity();
  8883. }
  8884. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8885. return this._worldMatrix;
  8886. };
  8887. return DirectionalLight;
  8888. })(BABYLON.Light);
  8889. BABYLON.DirectionalLight = DirectionalLight;
  8890. })(BABYLON || (BABYLON = {}));
  8891. var BABYLON;
  8892. (function (BABYLON) {
  8893. var ShadowGenerator = (function () {
  8894. function ShadowGenerator(mapSize, light) {
  8895. var _this = this;
  8896. // Members
  8897. this._filter = ShadowGenerator.FILTER_NONE;
  8898. this.blurScale = 2;
  8899. this._blurBoxOffset = 0;
  8900. this._bias = 0.00005;
  8901. this._lightDirection = BABYLON.Vector3.Zero();
  8902. this._darkness = 0;
  8903. this._transparencyShadow = false;
  8904. this._viewMatrix = BABYLON.Matrix.Zero();
  8905. this._projectionMatrix = BABYLON.Matrix.Zero();
  8906. this._transformMatrix = BABYLON.Matrix.Zero();
  8907. this._worldViewProjection = BABYLON.Matrix.Zero();
  8908. this._light = light;
  8909. this._scene = light.getScene();
  8910. this._mapSize = mapSize;
  8911. light._shadowGenerator = this;
  8912. // Render target
  8913. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8914. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8915. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8916. this._shadowMap.anisotropicFilteringLevel = 1;
  8917. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8918. this._shadowMap.renderParticles = false;
  8919. this._shadowMap.onAfterUnbind = function () {
  8920. if (!_this.useBlurVarianceShadowMap) {
  8921. return;
  8922. }
  8923. if (!_this._shadowMap2) {
  8924. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8925. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8926. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8927. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8928. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8929. _this._downSamplePostprocess.onApply = function (effect) {
  8930. effect.setTexture("textureSampler", _this._shadowMap);
  8931. };
  8932. _this.blurBoxOffset = 1;
  8933. }
  8934. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8935. };
  8936. // Custom render function
  8937. var renderSubMesh = function (subMesh) {
  8938. var mesh = subMesh.getRenderingMesh();
  8939. var scene = _this._scene;
  8940. var engine = scene.getEngine();
  8941. // Culling
  8942. engine.setState(subMesh.getMaterial().backFaceCulling);
  8943. // Managing instances
  8944. var batch = mesh._getInstancesRenderList(subMesh._id);
  8945. if (batch.mustReturn) {
  8946. return;
  8947. }
  8948. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8949. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8950. engine.enableEffect(_this._effect);
  8951. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8952. var material = subMesh.getMaterial();
  8953. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8954. // Alpha test
  8955. if (material && material.needAlphaTesting()) {
  8956. var alphaTexture = material.getAlphaTestTexture();
  8957. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8958. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8959. }
  8960. // Bones
  8961. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8962. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8963. }
  8964. // Draw
  8965. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8966. }
  8967. else {
  8968. // Need to reset refresh rate of the shadowMap
  8969. _this._shadowMap.resetRefreshCounter();
  8970. }
  8971. };
  8972. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8973. var index;
  8974. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8975. renderSubMesh(opaqueSubMeshes.data[index]);
  8976. }
  8977. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8978. renderSubMesh(alphaTestSubMeshes.data[index]);
  8979. }
  8980. if (_this._transparencyShadow) {
  8981. for (index = 0; index < transparentSubMeshes.length; index++) {
  8982. renderSubMesh(transparentSubMeshes.data[index]);
  8983. }
  8984. }
  8985. };
  8986. this._shadowMap.onClear = function (engine) {
  8987. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8988. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8989. }
  8990. else {
  8991. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8992. }
  8993. };
  8994. }
  8995. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8996. // Static
  8997. get: function () {
  8998. return ShadowGenerator._FILTER_NONE;
  8999. },
  9000. enumerable: true,
  9001. configurable: true
  9002. });
  9003. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9004. get: function () {
  9005. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9006. },
  9007. enumerable: true,
  9008. configurable: true
  9009. });
  9010. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9011. get: function () {
  9012. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9013. },
  9014. enumerable: true,
  9015. configurable: true
  9016. });
  9017. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9018. get: function () {
  9019. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9020. },
  9021. enumerable: true,
  9022. configurable: true
  9023. });
  9024. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9025. get: function () {
  9026. return this._bias;
  9027. },
  9028. set: function (bias) {
  9029. this._bias = bias;
  9030. },
  9031. enumerable: true,
  9032. configurable: true
  9033. });
  9034. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9035. get: function () {
  9036. return this._blurBoxOffset;
  9037. },
  9038. set: function (value) {
  9039. var _this = this;
  9040. if (this._blurBoxOffset === value) {
  9041. return;
  9042. }
  9043. this._blurBoxOffset = value;
  9044. if (this._boxBlurPostprocess) {
  9045. this._boxBlurPostprocess.dispose();
  9046. }
  9047. 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);
  9048. this._boxBlurPostprocess.onApply = function (effect) {
  9049. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9050. };
  9051. },
  9052. enumerable: true,
  9053. configurable: true
  9054. });
  9055. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9056. get: function () {
  9057. return this._filter;
  9058. },
  9059. set: function (value) {
  9060. if (this._filter === value) {
  9061. return;
  9062. }
  9063. this._filter = value;
  9064. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9065. this._shadowMap.anisotropicFilteringLevel = 16;
  9066. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9067. }
  9068. else {
  9069. this._shadowMap.anisotropicFilteringLevel = 1;
  9070. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9071. }
  9072. },
  9073. enumerable: true,
  9074. configurable: true
  9075. });
  9076. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9077. get: function () {
  9078. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9079. },
  9080. set: function (value) {
  9081. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9082. },
  9083. enumerable: true,
  9084. configurable: true
  9085. });
  9086. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9087. get: function () {
  9088. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9089. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9090. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9091. },
  9092. set: function (value) {
  9093. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9094. },
  9095. enumerable: true,
  9096. configurable: true
  9097. });
  9098. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9099. get: function () {
  9100. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9101. },
  9102. set: function (value) {
  9103. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9104. },
  9105. enumerable: true,
  9106. configurable: true
  9107. });
  9108. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9109. var defines = [];
  9110. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9111. defines.push("#define VSM");
  9112. }
  9113. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9114. var mesh = subMesh.getMesh();
  9115. var material = subMesh.getMaterial();
  9116. // Alpha test
  9117. if (material && material.needAlphaTesting()) {
  9118. defines.push("#define ALPHATEST");
  9119. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9120. attribs.push(BABYLON.VertexBuffer.UVKind);
  9121. defines.push("#define UV1");
  9122. }
  9123. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9124. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9125. defines.push("#define UV2");
  9126. }
  9127. }
  9128. // Bones
  9129. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9130. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9131. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9132. defines.push("#define BONES");
  9133. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9134. }
  9135. // Instances
  9136. if (useInstances) {
  9137. defines.push("#define INSTANCES");
  9138. attribs.push("world0");
  9139. attribs.push("world1");
  9140. attribs.push("world2");
  9141. attribs.push("world3");
  9142. }
  9143. // Get correct effect
  9144. var join = defines.join("\n");
  9145. if (this._cachedDefines !== join) {
  9146. this._cachedDefines = join;
  9147. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9148. }
  9149. return this._effect.isReady();
  9150. };
  9151. ShadowGenerator.prototype.getShadowMap = function () {
  9152. return this._shadowMap;
  9153. };
  9154. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9155. if (this._shadowMap2) {
  9156. return this._shadowMap2;
  9157. }
  9158. return this._shadowMap;
  9159. };
  9160. ShadowGenerator.prototype.getLight = function () {
  9161. return this._light;
  9162. };
  9163. // Methods
  9164. ShadowGenerator.prototype.getTransformMatrix = function () {
  9165. var scene = this._scene;
  9166. if (this._currentRenderID === scene.getRenderId()) {
  9167. return this._transformMatrix;
  9168. }
  9169. this._currentRenderID = scene.getRenderId();
  9170. var lightPosition = this._light.position;
  9171. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9172. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9173. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9174. }
  9175. if (this._light.computeTransformedPosition()) {
  9176. lightPosition = this._light.transformedPosition;
  9177. }
  9178. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9179. this._cachedPosition = lightPosition.clone();
  9180. this._cachedDirection = this._lightDirection.clone();
  9181. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9182. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9183. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9184. }
  9185. return this._transformMatrix;
  9186. };
  9187. ShadowGenerator.prototype.getDarkness = function () {
  9188. return this._darkness;
  9189. };
  9190. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9191. if (darkness >= 1.0)
  9192. this._darkness = 1.0;
  9193. else if (darkness <= 0.0)
  9194. this._darkness = 0.0;
  9195. else
  9196. this._darkness = darkness;
  9197. };
  9198. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9199. this._transparencyShadow = hasShadow;
  9200. };
  9201. ShadowGenerator.prototype._packHalf = function (depth) {
  9202. var scale = depth * 255.0;
  9203. var fract = scale - Math.floor(scale);
  9204. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9205. };
  9206. ShadowGenerator.prototype.dispose = function () {
  9207. this._shadowMap.dispose();
  9208. if (this._shadowMap2) {
  9209. this._shadowMap2.dispose();
  9210. }
  9211. if (this._downSamplePostprocess) {
  9212. this._downSamplePostprocess.dispose();
  9213. }
  9214. if (this._boxBlurPostprocess) {
  9215. this._boxBlurPostprocess.dispose();
  9216. }
  9217. };
  9218. ShadowGenerator._FILTER_NONE = 0;
  9219. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9220. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9221. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9222. return ShadowGenerator;
  9223. })();
  9224. BABYLON.ShadowGenerator = ShadowGenerator;
  9225. })(BABYLON || (BABYLON = {}));
  9226. var BABYLON;
  9227. (function (BABYLON) {
  9228. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9229. if (boxMin.x > sphereCenter.x + sphereRadius)
  9230. return false;
  9231. if (sphereCenter.x - sphereRadius > boxMax.x)
  9232. return false;
  9233. if (boxMin.y > sphereCenter.y + sphereRadius)
  9234. return false;
  9235. if (sphereCenter.y - sphereRadius > boxMax.y)
  9236. return false;
  9237. if (boxMin.z > sphereCenter.z + sphereRadius)
  9238. return false;
  9239. if (sphereCenter.z - sphereRadius > boxMax.z)
  9240. return false;
  9241. return true;
  9242. };
  9243. var getLowestRoot = function (a, b, c, maxR) {
  9244. var determinant = b * b - 4.0 * a * c;
  9245. var result = { root: 0, found: false };
  9246. if (determinant < 0)
  9247. return result;
  9248. var sqrtD = Math.sqrt(determinant);
  9249. var r1 = (-b - sqrtD) / (2.0 * a);
  9250. var r2 = (-b + sqrtD) / (2.0 * a);
  9251. if (r1 > r2) {
  9252. var temp = r2;
  9253. r2 = r1;
  9254. r1 = temp;
  9255. }
  9256. if (r1 > 0 && r1 < maxR) {
  9257. result.root = r1;
  9258. result.found = true;
  9259. return result;
  9260. }
  9261. if (r2 > 0 && r2 < maxR) {
  9262. result.root = r2;
  9263. result.found = true;
  9264. return result;
  9265. }
  9266. return result;
  9267. };
  9268. var Collider = (function () {
  9269. function Collider() {
  9270. this.radius = new BABYLON.Vector3(1, 1, 1);
  9271. this.retry = 0;
  9272. this.basePointWorld = BABYLON.Vector3.Zero();
  9273. this.velocityWorld = BABYLON.Vector3.Zero();
  9274. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9275. this._collisionPoint = BABYLON.Vector3.Zero();
  9276. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9277. this._tempVector = BABYLON.Vector3.Zero();
  9278. this._tempVector2 = BABYLON.Vector3.Zero();
  9279. this._tempVector3 = BABYLON.Vector3.Zero();
  9280. this._tempVector4 = BABYLON.Vector3.Zero();
  9281. this._edge = BABYLON.Vector3.Zero();
  9282. this._baseToVertex = BABYLON.Vector3.Zero();
  9283. this._destinationPoint = BABYLON.Vector3.Zero();
  9284. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9285. this._displacementVector = BABYLON.Vector3.Zero();
  9286. }
  9287. // Methods
  9288. Collider.prototype._initialize = function (source, dir, e) {
  9289. this.velocity = dir;
  9290. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9291. this.basePoint = source;
  9292. source.multiplyToRef(this.radius, this.basePointWorld);
  9293. dir.multiplyToRef(this.radius, this.velocityWorld);
  9294. this.velocityWorldLength = this.velocityWorld.length();
  9295. this.epsilon = e;
  9296. this.collisionFound = false;
  9297. };
  9298. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9299. pa.subtractToRef(point, this._tempVector);
  9300. pb.subtractToRef(point, this._tempVector2);
  9301. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9302. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9303. if (d < 0)
  9304. return false;
  9305. pc.subtractToRef(point, this._tempVector3);
  9306. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9307. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9308. if (d < 0)
  9309. return false;
  9310. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9311. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9312. return d >= 0;
  9313. };
  9314. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9315. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9316. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9317. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9318. return false;
  9319. }
  9320. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9321. return false;
  9322. return true;
  9323. };
  9324. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9325. var t0;
  9326. var embeddedInPlane = false;
  9327. //defensive programming, actually not needed.
  9328. if (!trianglePlaneArray) {
  9329. trianglePlaneArray = [];
  9330. }
  9331. if (!trianglePlaneArray[faceIndex]) {
  9332. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9333. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9334. }
  9335. var trianglePlane = trianglePlaneArray[faceIndex];
  9336. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9337. return;
  9338. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9339. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9340. if (normalDotVelocity == 0) {
  9341. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9342. return;
  9343. embeddedInPlane = true;
  9344. t0 = 0;
  9345. }
  9346. else {
  9347. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9348. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9349. if (t0 > t1) {
  9350. var temp = t1;
  9351. t1 = t0;
  9352. t0 = temp;
  9353. }
  9354. if (t0 > 1.0 || t1 < 0.0)
  9355. return;
  9356. if (t0 < 0)
  9357. t0 = 0;
  9358. if (t0 > 1.0)
  9359. t0 = 1.0;
  9360. }
  9361. this._collisionPoint.copyFromFloats(0, 0, 0);
  9362. var found = false;
  9363. var t = 1.0;
  9364. if (!embeddedInPlane) {
  9365. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9366. this.velocity.scaleToRef(t0, this._tempVector);
  9367. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9368. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9369. found = true;
  9370. t = t0;
  9371. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9372. }
  9373. }
  9374. if (!found) {
  9375. var velocitySquaredLength = this.velocity.lengthSquared();
  9376. var a = velocitySquaredLength;
  9377. this.basePoint.subtractToRef(p1, this._tempVector);
  9378. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9379. var c = this._tempVector.lengthSquared() - 1.0;
  9380. var lowestRoot = getLowestRoot(a, b, c, t);
  9381. if (lowestRoot.found) {
  9382. t = lowestRoot.root;
  9383. found = true;
  9384. this._collisionPoint.copyFrom(p1);
  9385. }
  9386. this.basePoint.subtractToRef(p2, this._tempVector);
  9387. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9388. c = this._tempVector.lengthSquared() - 1.0;
  9389. lowestRoot = getLowestRoot(a, b, c, t);
  9390. if (lowestRoot.found) {
  9391. t = lowestRoot.root;
  9392. found = true;
  9393. this._collisionPoint.copyFrom(p2);
  9394. }
  9395. this.basePoint.subtractToRef(p3, this._tempVector);
  9396. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9397. c = this._tempVector.lengthSquared() - 1.0;
  9398. lowestRoot = getLowestRoot(a, b, c, t);
  9399. if (lowestRoot.found) {
  9400. t = lowestRoot.root;
  9401. found = true;
  9402. this._collisionPoint.copyFrom(p3);
  9403. }
  9404. p2.subtractToRef(p1, this._edge);
  9405. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9406. var edgeSquaredLength = this._edge.lengthSquared();
  9407. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9408. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9409. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9410. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9411. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9412. lowestRoot = getLowestRoot(a, b, c, t);
  9413. if (lowestRoot.found) {
  9414. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9415. if (f >= 0.0 && f <= 1.0) {
  9416. t = lowestRoot.root;
  9417. found = true;
  9418. this._edge.scaleInPlace(f);
  9419. p1.addToRef(this._edge, this._collisionPoint);
  9420. }
  9421. }
  9422. p3.subtractToRef(p2, this._edge);
  9423. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9424. edgeSquaredLength = this._edge.lengthSquared();
  9425. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9426. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9427. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9428. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9429. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9430. lowestRoot = getLowestRoot(a, b, c, t);
  9431. if (lowestRoot.found) {
  9432. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9433. if (f >= 0.0 && f <= 1.0) {
  9434. t = lowestRoot.root;
  9435. found = true;
  9436. this._edge.scaleInPlace(f);
  9437. p2.addToRef(this._edge, this._collisionPoint);
  9438. }
  9439. }
  9440. p1.subtractToRef(p3, this._edge);
  9441. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9442. edgeSquaredLength = this._edge.lengthSquared();
  9443. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9444. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9445. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9446. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9447. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9448. lowestRoot = getLowestRoot(a, b, c, t);
  9449. if (lowestRoot.found) {
  9450. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9451. if (f >= 0.0 && f <= 1.0) {
  9452. t = lowestRoot.root;
  9453. found = true;
  9454. this._edge.scaleInPlace(f);
  9455. p3.addToRef(this._edge, this._collisionPoint);
  9456. }
  9457. }
  9458. }
  9459. if (found) {
  9460. var distToCollision = t * this.velocity.length();
  9461. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9462. if (!this.intersectionPoint) {
  9463. this.intersectionPoint = this._collisionPoint.clone();
  9464. }
  9465. else {
  9466. this.intersectionPoint.copyFrom(this._collisionPoint);
  9467. }
  9468. this.nearestDistance = distToCollision;
  9469. this.collisionFound = true;
  9470. }
  9471. }
  9472. };
  9473. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9474. for (var i = indexStart; i < indexEnd; i += 3) {
  9475. var p1 = pts[indices[i] - decal];
  9476. var p2 = pts[indices[i + 1] - decal];
  9477. var p3 = pts[indices[i + 2] - decal];
  9478. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9479. }
  9480. };
  9481. Collider.prototype._getResponse = function (pos, vel) {
  9482. pos.addToRef(vel, this._destinationPoint);
  9483. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9484. this.basePoint.addToRef(vel, pos);
  9485. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9486. this._slidePlaneNormal.normalize();
  9487. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9488. pos.addInPlace(this._displacementVector);
  9489. this.intersectionPoint.addInPlace(this._displacementVector);
  9490. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9491. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9492. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9493. };
  9494. return Collider;
  9495. })();
  9496. BABYLON.Collider = Collider;
  9497. })(BABYLON || (BABYLON = {}));
  9498. var BABYLON;
  9499. (function (BABYLON) {
  9500. //WebWorker code will be inserted to this variable.
  9501. BABYLON.CollisionWorker = "";
  9502. (function (WorkerTaskType) {
  9503. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9504. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9505. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9506. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9507. var WorkerTaskType = BABYLON.WorkerTaskType;
  9508. (function (WorkerReplyType) {
  9509. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9510. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9511. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9512. var WorkerReplyType = BABYLON.WorkerReplyType;
  9513. var CollisionCoordinatorWorker = (function () {
  9514. function CollisionCoordinatorWorker() {
  9515. var _this = this;
  9516. this._scaledPosition = BABYLON.Vector3.Zero();
  9517. this._scaledVelocity = BABYLON.Vector3.Zero();
  9518. this.onMeshUpdated = function (mesh) {
  9519. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9520. };
  9521. this.onGeometryUpdated = function (geometry) {
  9522. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9523. };
  9524. this._afterRender = function () {
  9525. if (!_this._init)
  9526. return;
  9527. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9528. return;
  9529. }
  9530. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9531. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9532. if (_this._runningUpdated > 4) {
  9533. return;
  9534. }
  9535. ++_this._runningUpdated;
  9536. var payload = {
  9537. updatedMeshes: _this._addUpdateMeshesList,
  9538. updatedGeometries: _this._addUpdateGeometriesList,
  9539. removedGeometries: _this._toRemoveGeometryArray,
  9540. removedMeshes: _this._toRemoveMeshesArray
  9541. };
  9542. var message = {
  9543. payload: payload,
  9544. taskType: WorkerTaskType.UPDATE
  9545. };
  9546. var serializable = [];
  9547. for (var id in payload.updatedGeometries) {
  9548. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9549. //prepare transferables
  9550. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9551. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9552. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9553. }
  9554. }
  9555. _this._worker.postMessage(message, serializable);
  9556. _this._addUpdateMeshesList = {};
  9557. _this._addUpdateGeometriesList = {};
  9558. _this._toRemoveGeometryArray = [];
  9559. _this._toRemoveMeshesArray = [];
  9560. };
  9561. this._onMessageFromWorker = function (e) {
  9562. var returnData = e.data;
  9563. if (returnData.error != WorkerReplyType.SUCCESS) {
  9564. //TODO what errors can be returned from the worker?
  9565. BABYLON.Tools.Warn("error returned from worker!");
  9566. return;
  9567. }
  9568. switch (returnData.taskType) {
  9569. case WorkerTaskType.INIT:
  9570. _this._init = true;
  9571. //Update the worked with ALL of the scene's current state
  9572. _this._scene.meshes.forEach(function (mesh) {
  9573. _this.onMeshAdded(mesh);
  9574. });
  9575. _this._scene.getGeometries().forEach(function (geometry) {
  9576. _this.onGeometryAdded(geometry);
  9577. });
  9578. break;
  9579. case WorkerTaskType.UPDATE:
  9580. _this._runningUpdated--;
  9581. break;
  9582. case WorkerTaskType.COLLIDE:
  9583. _this._runningCollisionTask = false;
  9584. var returnPayload = returnData.payload;
  9585. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9586. return;
  9587. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9588. //cleanup
  9589. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9590. break;
  9591. }
  9592. };
  9593. this._collisionsCallbackArray = [];
  9594. this._init = false;
  9595. this._runningUpdated = 0;
  9596. this._runningCollisionTask = false;
  9597. this._addUpdateMeshesList = {};
  9598. this._addUpdateGeometriesList = {};
  9599. this._toRemoveGeometryArray = [];
  9600. this._toRemoveMeshesArray = [];
  9601. }
  9602. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9603. if (!this._init)
  9604. return;
  9605. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9606. return;
  9607. position.divideToRef(collider.radius, this._scaledPosition);
  9608. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9609. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9610. var payload = {
  9611. collider: {
  9612. position: this._scaledPosition.asArray(),
  9613. velocity: this._scaledVelocity.asArray(),
  9614. radius: collider.radius.asArray()
  9615. },
  9616. collisionId: collisionIndex,
  9617. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9618. maximumRetry: maximumRetry
  9619. };
  9620. var message = {
  9621. payload: payload,
  9622. taskType: WorkerTaskType.COLLIDE
  9623. };
  9624. this._worker.postMessage(message);
  9625. };
  9626. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9627. this._scene = scene;
  9628. this._scene.registerAfterRender(this._afterRender);
  9629. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9630. this._worker = new Worker(workerUrl);
  9631. this._worker.onmessage = this._onMessageFromWorker;
  9632. var message = {
  9633. payload: {},
  9634. taskType: WorkerTaskType.INIT
  9635. };
  9636. this._worker.postMessage(message);
  9637. };
  9638. CollisionCoordinatorWorker.prototype.destroy = function () {
  9639. this._scene.unregisterAfterRender(this._afterRender);
  9640. this._worker.terminate();
  9641. };
  9642. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9643. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9644. this.onMeshUpdated(mesh);
  9645. };
  9646. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9647. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9648. };
  9649. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9650. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9651. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9652. this.onGeometryUpdated(geometry);
  9653. };
  9654. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9655. this._toRemoveGeometryArray.push(geometry.id);
  9656. };
  9657. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9658. var submeshes = [];
  9659. if (mesh.subMeshes) {
  9660. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9661. return {
  9662. position: idx,
  9663. verticesStart: sm.verticesStart,
  9664. verticesCount: sm.verticesCount,
  9665. indexStart: sm.indexStart,
  9666. indexCount: sm.indexCount,
  9667. hasMaterial: !!sm.getMaterial(),
  9668. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9669. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9670. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9671. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9672. };
  9673. });
  9674. }
  9675. var geometryId = null;
  9676. if (mesh instanceof BABYLON.Mesh) {
  9677. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9678. }
  9679. else if (mesh instanceof BABYLON.InstancedMesh) {
  9680. geometryId = mesh.sourceMesh.geometry ? mesh.sourceMesh.geometry.id : null;
  9681. }
  9682. return {
  9683. uniqueId: mesh.uniqueId,
  9684. id: mesh.id,
  9685. name: mesh.name,
  9686. geometryId: geometryId,
  9687. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9688. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9689. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9690. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9691. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9692. subMeshes: submeshes,
  9693. checkCollisions: mesh.checkCollisions
  9694. };
  9695. };
  9696. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9697. return {
  9698. id: geometry.id,
  9699. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9700. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9701. indices: new Int32Array(geometry.getIndices() || []),
  9702. };
  9703. };
  9704. return CollisionCoordinatorWorker;
  9705. })();
  9706. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9707. var CollisionCoordinatorLegacy = (function () {
  9708. function CollisionCoordinatorLegacy() {
  9709. this._scaledPosition = BABYLON.Vector3.Zero();
  9710. this._scaledVelocity = BABYLON.Vector3.Zero();
  9711. this._finalPosition = BABYLON.Vector3.Zero();
  9712. }
  9713. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9714. position.divideToRef(collider.radius, this._scaledPosition);
  9715. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9716. collider.collidedMesh = null;
  9717. collider.retry = 0;
  9718. collider.initialVelocity = this._scaledVelocity;
  9719. collider.initialPosition = this._scaledPosition;
  9720. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9721. this._finalPosition.multiplyInPlace(collider.radius);
  9722. //run the callback
  9723. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9724. };
  9725. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9726. this._scene = scene;
  9727. };
  9728. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9729. //Legacy need no destruction method.
  9730. };
  9731. //No update in legacy mode
  9732. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9733. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9734. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9735. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9736. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9737. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9738. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9739. if (excludedMesh === void 0) { excludedMesh = null; }
  9740. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9741. if (collider.retry >= maximumRetry) {
  9742. finalPosition.copyFrom(position);
  9743. return;
  9744. }
  9745. collider._initialize(position, velocity, closeDistance);
  9746. // Check all meshes
  9747. for (var index = 0; index < this._scene.meshes.length; index++) {
  9748. var mesh = this._scene.meshes[index];
  9749. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9750. mesh._checkCollision(collider);
  9751. }
  9752. }
  9753. if (!collider.collisionFound) {
  9754. position.addToRef(velocity, finalPosition);
  9755. return;
  9756. }
  9757. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9758. collider._getResponse(position, velocity);
  9759. }
  9760. if (velocity.length() <= closeDistance) {
  9761. finalPosition.copyFrom(position);
  9762. return;
  9763. }
  9764. collider.retry++;
  9765. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9766. };
  9767. return CollisionCoordinatorLegacy;
  9768. })();
  9769. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9770. })(BABYLON || (BABYLON = {}));
  9771. var BABYLON;
  9772. (function (BABYLON) {
  9773. var VRCameraMetrics = (function () {
  9774. function VRCameraMetrics() {
  9775. this.compensateDistorsion = true;
  9776. }
  9777. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9778. get: function () {
  9779. return this.hResolution / (2 * this.vResolution);
  9780. },
  9781. enumerable: true,
  9782. configurable: true
  9783. });
  9784. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9785. get: function () {
  9786. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9792. get: function () {
  9793. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9794. var h = (4 * meters) / this.hScreenSize;
  9795. return BABYLON.Matrix.Translation(h, 0, 0);
  9796. },
  9797. enumerable: true,
  9798. configurable: true
  9799. });
  9800. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9801. get: function () {
  9802. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9803. var h = (4 * meters) / this.hScreenSize;
  9804. return BABYLON.Matrix.Translation(-h, 0, 0);
  9805. },
  9806. enumerable: true,
  9807. configurable: true
  9808. });
  9809. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9810. get: function () {
  9811. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9812. },
  9813. enumerable: true,
  9814. configurable: true
  9815. });
  9816. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9817. get: function () {
  9818. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9819. },
  9820. enumerable: true,
  9821. configurable: true
  9822. });
  9823. VRCameraMetrics.GetDefault = function () {
  9824. var result = new VRCameraMetrics();
  9825. result.hResolution = 1280;
  9826. result.vResolution = 800;
  9827. result.hScreenSize = 0.149759993;
  9828. result.vScreenSize = 0.0935999975;
  9829. result.vScreenCenter = 0.0467999987,
  9830. result.eyeToScreenDistance = 0.0410000011;
  9831. result.lensSeparationDistance = 0.0635000020;
  9832. result.interpupillaryDistance = 0.0640000030;
  9833. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9834. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9835. result.postProcessScaleFactor = 1.714605507808412;
  9836. result.lensCenterOffset = 0.151976421;
  9837. return result;
  9838. };
  9839. return VRCameraMetrics;
  9840. })();
  9841. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9842. var Camera = (function (_super) {
  9843. __extends(Camera, _super);
  9844. function Camera(name, position, scene) {
  9845. _super.call(this, name, scene);
  9846. this.position = position;
  9847. // Members
  9848. this.upVector = BABYLON.Vector3.Up();
  9849. this.orthoLeft = null;
  9850. this.orthoRight = null;
  9851. this.orthoBottom = null;
  9852. this.orthoTop = null;
  9853. this.fov = 0.8;
  9854. this.minZ = 1.0;
  9855. this.maxZ = 10000.0;
  9856. this.inertia = 0.9;
  9857. this.mode = Camera.PERSPECTIVE_CAMERA;
  9858. this.isIntermediate = false;
  9859. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9860. this.layerMask = 0x0FFFFFFF;
  9861. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9862. // Camera rig members
  9863. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9864. this._rigCameras = new Array();
  9865. // Cache
  9866. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9867. this._projectionMatrix = new BABYLON.Matrix();
  9868. this._postProcesses = new Array();
  9869. this._postProcessesTakenIndices = [];
  9870. this._activeMeshes = new BABYLON.SmartArray(256);
  9871. this._globalPosition = BABYLON.Vector3.Zero();
  9872. scene.addCamera(this);
  9873. if (!scene.activeCamera) {
  9874. scene.activeCamera = this;
  9875. }
  9876. }
  9877. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9878. get: function () {
  9879. return Camera._PERSPECTIVE_CAMERA;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9885. get: function () {
  9886. return Camera._ORTHOGRAPHIC_CAMERA;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9892. get: function () {
  9893. return Camera._FOVMODE_VERTICAL_FIXED;
  9894. },
  9895. enumerable: true,
  9896. configurable: true
  9897. });
  9898. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9899. get: function () {
  9900. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9906. get: function () {
  9907. return Camera._RIG_MODE_NONE;
  9908. },
  9909. enumerable: true,
  9910. configurable: true
  9911. });
  9912. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9913. get: function () {
  9914. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9920. get: function () {
  9921. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9927. get: function () {
  9928. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9934. get: function () {
  9935. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9936. },
  9937. enumerable: true,
  9938. configurable: true
  9939. });
  9940. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9941. get: function () {
  9942. return Camera._RIG_MODE_VR;
  9943. },
  9944. enumerable: true,
  9945. configurable: true
  9946. });
  9947. Object.defineProperty(Camera.prototype, "globalPosition", {
  9948. get: function () {
  9949. return this._globalPosition;
  9950. },
  9951. enumerable: true,
  9952. configurable: true
  9953. });
  9954. Camera.prototype.getActiveMeshes = function () {
  9955. return this._activeMeshes;
  9956. };
  9957. Camera.prototype.isActiveMesh = function (mesh) {
  9958. return (this._activeMeshes.indexOf(mesh) !== -1);
  9959. };
  9960. //Cache
  9961. Camera.prototype._initCache = function () {
  9962. _super.prototype._initCache.call(this);
  9963. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9964. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9965. this._cache.mode = undefined;
  9966. this._cache.minZ = undefined;
  9967. this._cache.maxZ = undefined;
  9968. this._cache.fov = undefined;
  9969. this._cache.aspectRatio = undefined;
  9970. this._cache.orthoLeft = undefined;
  9971. this._cache.orthoRight = undefined;
  9972. this._cache.orthoBottom = undefined;
  9973. this._cache.orthoTop = undefined;
  9974. this._cache.renderWidth = undefined;
  9975. this._cache.renderHeight = undefined;
  9976. };
  9977. Camera.prototype._updateCache = function (ignoreParentClass) {
  9978. if (!ignoreParentClass) {
  9979. _super.prototype._updateCache.call(this);
  9980. }
  9981. var engine = this.getEngine();
  9982. this._cache.position.copyFrom(this.position);
  9983. this._cache.upVector.copyFrom(this.upVector);
  9984. this._cache.mode = this.mode;
  9985. this._cache.minZ = this.minZ;
  9986. this._cache.maxZ = this.maxZ;
  9987. this._cache.fov = this.fov;
  9988. this._cache.aspectRatio = engine.getAspectRatio(this);
  9989. this._cache.orthoLeft = this.orthoLeft;
  9990. this._cache.orthoRight = this.orthoRight;
  9991. this._cache.orthoBottom = this.orthoBottom;
  9992. this._cache.orthoTop = this.orthoTop;
  9993. this._cache.renderWidth = engine.getRenderWidth();
  9994. this._cache.renderHeight = engine.getRenderHeight();
  9995. };
  9996. Camera.prototype._updateFromScene = function () {
  9997. this.updateCache();
  9998. this._update();
  9999. };
  10000. // Synchronized
  10001. Camera.prototype._isSynchronized = function () {
  10002. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10003. };
  10004. Camera.prototype._isSynchronizedViewMatrix = function () {
  10005. if (!_super.prototype._isSynchronized.call(this))
  10006. return false;
  10007. return this._cache.position.equals(this.position)
  10008. && this._cache.upVector.equals(this.upVector)
  10009. && this.isSynchronizedWithParent();
  10010. };
  10011. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10012. var check = this._cache.mode === this.mode
  10013. && this._cache.minZ === this.minZ
  10014. && this._cache.maxZ === this.maxZ;
  10015. if (!check) {
  10016. return false;
  10017. }
  10018. var engine = this.getEngine();
  10019. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10020. check = this._cache.fov === this.fov
  10021. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10022. }
  10023. else {
  10024. check = this._cache.orthoLeft === this.orthoLeft
  10025. && this._cache.orthoRight === this.orthoRight
  10026. && this._cache.orthoBottom === this.orthoBottom
  10027. && this._cache.orthoTop === this.orthoTop
  10028. && this._cache.renderWidth === engine.getRenderWidth()
  10029. && this._cache.renderHeight === engine.getRenderHeight();
  10030. }
  10031. return check;
  10032. };
  10033. // Controls
  10034. Camera.prototype.attachControl = function (element) {
  10035. };
  10036. Camera.prototype.detachControl = function (element) {
  10037. };
  10038. Camera.prototype._update = function () {
  10039. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10040. this._updateRigCameras();
  10041. }
  10042. this._checkInputs();
  10043. };
  10044. Camera.prototype._checkInputs = function () {
  10045. };
  10046. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10047. if (insertAt === void 0) { insertAt = null; }
  10048. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10049. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10050. return 0;
  10051. }
  10052. if (insertAt == null || insertAt < 0) {
  10053. this._postProcesses.push(postProcess);
  10054. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10055. return this._postProcesses.length - 1;
  10056. }
  10057. var add = 0;
  10058. if (this._postProcesses[insertAt]) {
  10059. var start = this._postProcesses.length - 1;
  10060. for (var i = start; i >= insertAt + 1; --i) {
  10061. this._postProcesses[i + 1] = this._postProcesses[i];
  10062. }
  10063. add = 1;
  10064. }
  10065. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10066. if (this._postProcessesTakenIndices[i] < insertAt) {
  10067. continue;
  10068. }
  10069. start = this._postProcessesTakenIndices.length - 1;
  10070. for (var j = start; j >= i; --j) {
  10071. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10072. }
  10073. this._postProcessesTakenIndices[i] = insertAt;
  10074. break;
  10075. }
  10076. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  10077. this._postProcessesTakenIndices.push(insertAt);
  10078. }
  10079. var result = insertAt + add;
  10080. this._postProcesses[result] = postProcess;
  10081. return result;
  10082. };
  10083. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10084. if (atIndices === void 0) { atIndices = null; }
  10085. var result = [];
  10086. if (!atIndices) {
  10087. var length = this._postProcesses.length;
  10088. for (var i = 0; i < length; i++) {
  10089. if (this._postProcesses[i] !== postProcess) {
  10090. continue;
  10091. }
  10092. delete this._postProcesses[i];
  10093. var index = this._postProcessesTakenIndices.indexOf(i);
  10094. this._postProcessesTakenIndices.splice(index, 1);
  10095. }
  10096. }
  10097. else {
  10098. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10099. for (i = 0; i < atIndices.length; i++) {
  10100. var foundPostProcess = this._postProcesses[atIndices[i]];
  10101. if (foundPostProcess !== postProcess) {
  10102. result.push(i);
  10103. continue;
  10104. }
  10105. delete this._postProcesses[atIndices[i]];
  10106. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10107. this._postProcessesTakenIndices.splice(index, 1);
  10108. }
  10109. }
  10110. return result;
  10111. };
  10112. Camera.prototype.getWorldMatrix = function () {
  10113. if (!this._worldMatrix) {
  10114. this._worldMatrix = BABYLON.Matrix.Identity();
  10115. }
  10116. var viewMatrix = this.getViewMatrix();
  10117. viewMatrix.invertToRef(this._worldMatrix);
  10118. return this._worldMatrix;
  10119. };
  10120. Camera.prototype._getViewMatrix = function () {
  10121. return BABYLON.Matrix.Identity();
  10122. };
  10123. Camera.prototype.getViewMatrix = function (force) {
  10124. this._computedViewMatrix = this._computeViewMatrix(force);
  10125. if (!force && this._isSynchronizedViewMatrix()) {
  10126. return this._computedViewMatrix;
  10127. }
  10128. if (!this.parent || !this.parent.getWorldMatrix) {
  10129. this._globalPosition.copyFrom(this.position);
  10130. }
  10131. else {
  10132. if (!this._worldMatrix) {
  10133. this._worldMatrix = BABYLON.Matrix.Identity();
  10134. }
  10135. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10136. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10137. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10138. this._computedViewMatrix.invert();
  10139. this._markSyncedWithParent();
  10140. }
  10141. this._currentRenderId = this.getScene().getRenderId();
  10142. return this._computedViewMatrix;
  10143. };
  10144. Camera.prototype._computeViewMatrix = function (force) {
  10145. if (!force && this._isSynchronizedViewMatrix()) {
  10146. return this._computedViewMatrix;
  10147. }
  10148. this._computedViewMatrix = this._getViewMatrix();
  10149. this._currentRenderId = this.getScene().getRenderId();
  10150. return this._computedViewMatrix;
  10151. };
  10152. Camera.prototype.getProjectionMatrix = function (force) {
  10153. if (!force && this._isSynchronizedProjectionMatrix()) {
  10154. return this._projectionMatrix;
  10155. }
  10156. var engine = this.getEngine();
  10157. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10158. if (this.minZ <= 0) {
  10159. this.minZ = 0.1;
  10160. }
  10161. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10162. return this._projectionMatrix;
  10163. }
  10164. var halfWidth = engine.getRenderWidth() / 2.0;
  10165. var halfHeight = engine.getRenderHeight() / 2.0;
  10166. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10167. return this._projectionMatrix;
  10168. };
  10169. Camera.prototype.dispose = function () {
  10170. // Remove from scene
  10171. this.getScene().removeCamera(this);
  10172. while (this._rigCameras.length > 0) {
  10173. this._rigCameras.pop().dispose();
  10174. }
  10175. // Postprocesses
  10176. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10177. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10178. }
  10179. };
  10180. // ---- Camera rigs section ----
  10181. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10182. while (this._rigCameras.length > 0) {
  10183. this._rigCameras.pop().dispose();
  10184. }
  10185. this.cameraRigMode = mode;
  10186. this._cameraRigParams = {};
  10187. switch (this.cameraRigMode) {
  10188. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10189. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10190. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10191. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10192. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10193. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10194. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10195. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10196. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10197. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10198. break;
  10199. }
  10200. var postProcesses = new Array();
  10201. switch (this.cameraRigMode) {
  10202. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10203. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10204. this._rigCameras[0].isIntermediate = true;
  10205. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10206. postProcesses[1].onApply = function (effect) {
  10207. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10208. };
  10209. break;
  10210. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10211. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10212. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10213. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10214. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10215. var secondCamIndex = 1 - firstCamIndex;
  10216. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10217. this._rigCameras[firstCamIndex].isIntermediate = true;
  10218. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10219. break;
  10220. case Camera.RIG_MODE_VR:
  10221. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10222. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10223. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10224. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10225. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10226. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10227. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10228. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10229. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10230. if (metrics.compensateDistorsion) {
  10231. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10232. }
  10233. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10234. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10235. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10236. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10237. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10238. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10239. if (metrics.compensateDistorsion) {
  10240. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10241. }
  10242. break;
  10243. }
  10244. this._update();
  10245. };
  10246. Camera.prototype._getVRProjectionMatrix = function () {
  10247. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10248. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10249. return this._projectionMatrix;
  10250. };
  10251. Camera.prototype.setCameraRigParameter = function (name, value) {
  10252. this._cameraRigParams[name] = value;
  10253. //provisionnally:
  10254. if (name === "interaxialDistance") {
  10255. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10256. }
  10257. };
  10258. /**
  10259. * May needs to be overridden by children so sub has required properties to be copied
  10260. */
  10261. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10262. return null;
  10263. };
  10264. /**
  10265. * May needs to be overridden by children
  10266. */
  10267. Camera.prototype._updateRigCameras = function () {
  10268. for (var i = 0; i < this._rigCameras.length; i++) {
  10269. this._rigCameras[i].minZ = this.minZ;
  10270. this._rigCameras[i].maxZ = this.maxZ;
  10271. this._rigCameras[i].fov = this.fov;
  10272. }
  10273. // only update viewport when ANAGLYPH
  10274. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10275. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10276. }
  10277. };
  10278. // Statics
  10279. Camera._PERSPECTIVE_CAMERA = 0;
  10280. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10281. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10282. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10283. Camera._RIG_MODE_NONE = 0;
  10284. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10285. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10286. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10287. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10288. Camera._RIG_MODE_VR = 20;
  10289. return Camera;
  10290. })(BABYLON.Node);
  10291. BABYLON.Camera = Camera;
  10292. })(BABYLON || (BABYLON = {}));
  10293. var BABYLON;
  10294. (function (BABYLON) {
  10295. var TargetCamera = (function (_super) {
  10296. __extends(TargetCamera, _super);
  10297. function TargetCamera(name, position, scene) {
  10298. _super.call(this, name, position, scene);
  10299. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10300. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10301. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10302. this.speed = 2.0;
  10303. this.noRotationConstraint = false;
  10304. this.lockedTarget = null;
  10305. this._currentTarget = BABYLON.Vector3.Zero();
  10306. this._viewMatrix = BABYLON.Matrix.Zero();
  10307. this._camMatrix = BABYLON.Matrix.Zero();
  10308. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10309. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10310. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10311. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10312. this._lookAtTemp = BABYLON.Matrix.Zero();
  10313. this._tempMatrix = BABYLON.Matrix.Zero();
  10314. }
  10315. TargetCamera.prototype._getLockedTargetPosition = function () {
  10316. if (!this.lockedTarget) {
  10317. return null;
  10318. }
  10319. return this.lockedTarget.position || this.lockedTarget;
  10320. };
  10321. // Cache
  10322. TargetCamera.prototype._initCache = function () {
  10323. _super.prototype._initCache.call(this);
  10324. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10325. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10326. };
  10327. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10328. if (!ignoreParentClass) {
  10329. _super.prototype._updateCache.call(this);
  10330. }
  10331. var lockedTargetPosition = this._getLockedTargetPosition();
  10332. if (!lockedTargetPosition) {
  10333. this._cache.lockedTarget = null;
  10334. }
  10335. else {
  10336. if (!this._cache.lockedTarget) {
  10337. this._cache.lockedTarget = lockedTargetPosition.clone();
  10338. }
  10339. else {
  10340. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10341. }
  10342. }
  10343. this._cache.rotation.copyFrom(this.rotation);
  10344. };
  10345. // Synchronized
  10346. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10347. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10348. return false;
  10349. }
  10350. var lockedTargetPosition = this._getLockedTargetPosition();
  10351. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10352. && this._cache.rotation.equals(this.rotation);
  10353. };
  10354. // Methods
  10355. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10356. var engine = this.getEngine();
  10357. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10358. };
  10359. // Target
  10360. TargetCamera.prototype.setTarget = function (target) {
  10361. this.upVector.normalize();
  10362. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10363. this._camMatrix.invert();
  10364. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10365. var vDir = target.subtract(this.position);
  10366. if (vDir.x >= 0.0) {
  10367. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10368. }
  10369. else {
  10370. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10371. }
  10372. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10373. if (isNaN(this.rotation.x)) {
  10374. this.rotation.x = 0;
  10375. }
  10376. if (isNaN(this.rotation.y)) {
  10377. this.rotation.y = 0;
  10378. }
  10379. if (isNaN(this.rotation.z)) {
  10380. this.rotation.z = 0;
  10381. }
  10382. };
  10383. TargetCamera.prototype.getTarget = function () {
  10384. return this._currentTarget;
  10385. };
  10386. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10387. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10388. };
  10389. TargetCamera.prototype._updatePosition = function () {
  10390. this.position.addInPlace(this.cameraDirection);
  10391. };
  10392. TargetCamera.prototype._checkInputs = function () {
  10393. var needToMove = this._decideIfNeedsToMove();
  10394. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10395. // Move
  10396. if (needToMove) {
  10397. this._updatePosition();
  10398. }
  10399. // Rotate
  10400. if (needToRotate) {
  10401. this.rotation.x += this.cameraRotation.x;
  10402. this.rotation.y += this.cameraRotation.y;
  10403. if (!this.noRotationConstraint) {
  10404. var limit = (Math.PI / 2) * 0.95;
  10405. if (this.rotation.x > limit)
  10406. this.rotation.x = limit;
  10407. if (this.rotation.x < -limit)
  10408. this.rotation.x = -limit;
  10409. }
  10410. }
  10411. // Inertia
  10412. if (needToMove) {
  10413. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10414. this.cameraDirection.x = 0;
  10415. }
  10416. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10417. this.cameraDirection.y = 0;
  10418. }
  10419. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10420. this.cameraDirection.z = 0;
  10421. }
  10422. this.cameraDirection.scaleInPlace(this.inertia);
  10423. }
  10424. if (needToRotate) {
  10425. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10426. this.cameraRotation.x = 0;
  10427. }
  10428. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10429. this.cameraRotation.y = 0;
  10430. }
  10431. this.cameraRotation.scaleInPlace(this.inertia);
  10432. }
  10433. _super.prototype._checkInputs.call(this);
  10434. };
  10435. TargetCamera.prototype._getViewMatrix = function () {
  10436. if (!this.lockedTarget) {
  10437. // Compute
  10438. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10439. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10440. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10441. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10442. this._lookAtTemp.invert();
  10443. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10444. }
  10445. else {
  10446. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10447. }
  10448. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10449. // Computing target and final matrix
  10450. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10451. }
  10452. else {
  10453. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10454. }
  10455. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10456. return this._viewMatrix;
  10457. };
  10458. TargetCamera.prototype._getVRViewMatrix = function () {
  10459. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10460. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10461. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10462. // Computing target and final matrix
  10463. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10464. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10465. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10466. return this._viewMatrix;
  10467. };
  10468. /**
  10469. * @override
  10470. * Override Camera.createRigCamera
  10471. */
  10472. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10473. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10474. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10475. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10476. rigCamera._cameraRigParams = {};
  10477. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10478. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10479. }
  10480. return rigCamera;
  10481. }
  10482. return null;
  10483. };
  10484. /**
  10485. * @override
  10486. * Override Camera._updateRigCameras
  10487. */
  10488. TargetCamera.prototype._updateRigCameras = function () {
  10489. switch (this.cameraRigMode) {
  10490. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10491. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10492. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10493. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10494. case BABYLON.Camera.RIG_MODE_VR:
  10495. var camLeft = this._rigCameras[0];
  10496. var camRight = this._rigCameras[1];
  10497. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10498. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10499. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10500. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10501. camLeft.position.copyFrom(this.position);
  10502. camRight.position.copyFrom(this.position);
  10503. }
  10504. else {
  10505. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10506. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10507. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10508. camLeft.setTarget(this.getTarget());
  10509. camRight.setTarget(this.getTarget());
  10510. }
  10511. break;
  10512. }
  10513. _super.prototype._updateRigCameras.call(this);
  10514. };
  10515. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10516. if (!this._rigCamTransformMatrix) {
  10517. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10518. }
  10519. var target = this.getTarget();
  10520. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10521. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10522. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10523. };
  10524. return TargetCamera;
  10525. })(BABYLON.Camera);
  10526. BABYLON.TargetCamera = TargetCamera;
  10527. })(BABYLON || (BABYLON = {}));
  10528. var BABYLON;
  10529. (function (BABYLON) {
  10530. var FreeCamera = (function (_super) {
  10531. __extends(FreeCamera, _super);
  10532. function FreeCamera(name, position, scene) {
  10533. var _this = this;
  10534. _super.call(this, name, position, scene);
  10535. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10536. this.keysUp = [38];
  10537. this.keysDown = [40];
  10538. this.keysLeft = [37];
  10539. this.keysRight = [39];
  10540. this.checkCollisions = false;
  10541. this.applyGravity = false;
  10542. this.angularSensibility = 2000.0;
  10543. this._keys = [];
  10544. this._collider = new BABYLON.Collider();
  10545. this._needMoveForGravity = false;
  10546. this._oldPosition = BABYLON.Vector3.Zero();
  10547. this._diffPosition = BABYLON.Vector3.Zero();
  10548. this._newPosition = BABYLON.Vector3.Zero();
  10549. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10550. if (collidedMesh === void 0) { collidedMesh = null; }
  10551. //TODO move this to the collision coordinator!
  10552. if (_this.getScene().workerCollisions)
  10553. newPosition.multiplyInPlace(_this._collider.radius);
  10554. var updatePosition = function (newPos) {
  10555. _this._newPosition.copyFrom(newPos);
  10556. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10557. var oldPosition = _this.position.clone();
  10558. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10559. _this.position.addInPlace(_this._diffPosition);
  10560. if (_this.onCollide && collidedMesh) {
  10561. _this.onCollide(collidedMesh);
  10562. }
  10563. }
  10564. };
  10565. updatePosition(newPosition);
  10566. };
  10567. }
  10568. // Controls
  10569. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10570. var _this = this;
  10571. var previousPosition;
  10572. var engine = this.getEngine();
  10573. if (this._attachedElement) {
  10574. return;
  10575. }
  10576. this._attachedElement = element;
  10577. if (this._onMouseDown === undefined) {
  10578. this._onMouseDown = function (evt) {
  10579. previousPosition = {
  10580. x: evt.clientX,
  10581. y: evt.clientY
  10582. };
  10583. if (!noPreventDefault) {
  10584. evt.preventDefault();
  10585. }
  10586. };
  10587. this._onMouseUp = function (evt) {
  10588. previousPosition = null;
  10589. if (!noPreventDefault) {
  10590. evt.preventDefault();
  10591. }
  10592. };
  10593. this._onMouseOut = function (evt) {
  10594. previousPosition = null;
  10595. _this._keys = [];
  10596. if (!noPreventDefault) {
  10597. evt.preventDefault();
  10598. }
  10599. };
  10600. this._onMouseMove = function (evt) {
  10601. if (!previousPosition && !engine.isPointerLock) {
  10602. return;
  10603. }
  10604. var offsetX;
  10605. var offsetY;
  10606. if (!engine.isPointerLock) {
  10607. offsetX = evt.clientX - previousPosition.x;
  10608. offsetY = evt.clientY - previousPosition.y;
  10609. }
  10610. else {
  10611. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10612. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10613. }
  10614. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10615. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10616. previousPosition = {
  10617. x: evt.clientX,
  10618. y: evt.clientY
  10619. };
  10620. if (!noPreventDefault) {
  10621. evt.preventDefault();
  10622. }
  10623. };
  10624. this._onKeyDown = function (evt) {
  10625. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10626. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10627. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10628. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10629. var index = _this._keys.indexOf(evt.keyCode);
  10630. if (index === -1) {
  10631. _this._keys.push(evt.keyCode);
  10632. }
  10633. if (!noPreventDefault) {
  10634. evt.preventDefault();
  10635. }
  10636. }
  10637. };
  10638. this._onKeyUp = function (evt) {
  10639. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10640. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10641. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10642. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10643. var index = _this._keys.indexOf(evt.keyCode);
  10644. if (index >= 0) {
  10645. _this._keys.splice(index, 1);
  10646. }
  10647. if (!noPreventDefault) {
  10648. evt.preventDefault();
  10649. }
  10650. }
  10651. };
  10652. this._onLostFocus = function () {
  10653. _this._keys = [];
  10654. };
  10655. this._reset = function () {
  10656. _this._keys = [];
  10657. previousPosition = null;
  10658. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10659. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10660. };
  10661. }
  10662. element.addEventListener("mousedown", this._onMouseDown, false);
  10663. element.addEventListener("mouseup", this._onMouseUp, false);
  10664. element.addEventListener("mouseout", this._onMouseOut, false);
  10665. element.addEventListener("mousemove", this._onMouseMove, false);
  10666. BABYLON.Tools.RegisterTopRootEvents([
  10667. { name: "keydown", handler: this._onKeyDown },
  10668. { name: "keyup", handler: this._onKeyUp },
  10669. { name: "blur", handler: this._onLostFocus }
  10670. ]);
  10671. };
  10672. FreeCamera.prototype.detachControl = function (element) {
  10673. if (this._attachedElement != element) {
  10674. return;
  10675. }
  10676. element.removeEventListener("mousedown", this._onMouseDown);
  10677. element.removeEventListener("mouseup", this._onMouseUp);
  10678. element.removeEventListener("mouseout", this._onMouseOut);
  10679. element.removeEventListener("mousemove", this._onMouseMove);
  10680. BABYLON.Tools.UnregisterTopRootEvents([
  10681. { name: "keydown", handler: this._onKeyDown },
  10682. { name: "keyup", handler: this._onKeyUp },
  10683. { name: "blur", handler: this._onLostFocus }
  10684. ]);
  10685. this._attachedElement = null;
  10686. if (this._reset) {
  10687. this._reset();
  10688. }
  10689. };
  10690. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10691. var globalPosition;
  10692. if (this.parent) {
  10693. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10694. }
  10695. else {
  10696. globalPosition = this.position;
  10697. }
  10698. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10699. this._collider.radius = this.ellipsoid;
  10700. //add gravity to the velocity to prevent the dual-collision checking
  10701. if (this.applyGravity) {
  10702. velocity.addInPlace(this.getScene().gravity);
  10703. }
  10704. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10705. };
  10706. FreeCamera.prototype._checkInputs = function () {
  10707. if (!this._localDirection) {
  10708. this._localDirection = BABYLON.Vector3.Zero();
  10709. this._transformedDirection = BABYLON.Vector3.Zero();
  10710. }
  10711. // Keyboard
  10712. for (var index = 0; index < this._keys.length; index++) {
  10713. var keyCode = this._keys[index];
  10714. var speed = this._computeLocalCameraSpeed();
  10715. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10716. this._localDirection.copyFromFloats(-speed, 0, 0);
  10717. }
  10718. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10719. this._localDirection.copyFromFloats(0, 0, speed);
  10720. }
  10721. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10722. this._localDirection.copyFromFloats(speed, 0, 0);
  10723. }
  10724. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10725. this._localDirection.copyFromFloats(0, 0, -speed);
  10726. }
  10727. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10728. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10729. this.cameraDirection.addInPlace(this._transformedDirection);
  10730. }
  10731. _super.prototype._checkInputs.call(this);
  10732. };
  10733. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10734. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10735. };
  10736. FreeCamera.prototype._updatePosition = function () {
  10737. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10738. this._collideWithWorld(this.cameraDirection);
  10739. }
  10740. else {
  10741. this.position.addInPlace(this.cameraDirection);
  10742. }
  10743. };
  10744. return FreeCamera;
  10745. })(BABYLON.TargetCamera);
  10746. BABYLON.FreeCamera = FreeCamera;
  10747. })(BABYLON || (BABYLON = {}));
  10748. var BABYLON;
  10749. (function (BABYLON) {
  10750. var FollowCamera = (function (_super) {
  10751. __extends(FollowCamera, _super);
  10752. function FollowCamera(name, position, scene) {
  10753. _super.call(this, name, position, scene);
  10754. this.radius = 12;
  10755. this.rotationOffset = 0;
  10756. this.heightOffset = 4;
  10757. this.cameraAcceleration = 0.05;
  10758. this.maxCameraSpeed = 20;
  10759. }
  10760. FollowCamera.prototype.getRadians = function (degrees) {
  10761. return degrees * Math.PI / 180;
  10762. };
  10763. FollowCamera.prototype.follow = function (cameraTarget) {
  10764. if (!cameraTarget)
  10765. return;
  10766. var yRotation;
  10767. if (cameraTarget.rotationQuaternion) {
  10768. var rotMatrix = new BABYLON.Matrix();
  10769. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10770. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10771. }
  10772. else {
  10773. yRotation = cameraTarget.rotation.y;
  10774. }
  10775. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10776. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10777. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10778. var dx = targetX - this.position.x;
  10779. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10780. var dz = (targetZ) - this.position.z;
  10781. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10782. var vy = dy * this.cameraAcceleration;
  10783. var vz = dz * this.cameraAcceleration * 2;
  10784. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10785. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10786. }
  10787. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10788. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10789. }
  10790. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10791. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10792. }
  10793. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10794. this.setTarget(cameraTarget.position);
  10795. };
  10796. FollowCamera.prototype._checkInputs = function () {
  10797. _super.prototype._checkInputs.call(this);
  10798. this.follow(this.target);
  10799. };
  10800. return FollowCamera;
  10801. })(BABYLON.TargetCamera);
  10802. BABYLON.FollowCamera = FollowCamera;
  10803. var ArcFollowCamera = (function (_super) {
  10804. __extends(ArcFollowCamera, _super);
  10805. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10806. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10807. this.alpha = alpha;
  10808. this.beta = beta;
  10809. this.radius = radius;
  10810. this.target = target;
  10811. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10812. this.follow();
  10813. }
  10814. ArcFollowCamera.prototype.follow = function () {
  10815. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10816. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10817. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10818. this.position = this.target.position.add(this._cartesianCoordinates);
  10819. this.setTarget(this.target.position);
  10820. };
  10821. ArcFollowCamera.prototype._checkInputs = function () {
  10822. _super.prototype._checkInputs.call(this);
  10823. this.follow();
  10824. };
  10825. return ArcFollowCamera;
  10826. })(BABYLON.TargetCamera);
  10827. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10828. })(BABYLON || (BABYLON = {}));
  10829. var BABYLON;
  10830. (function (BABYLON) {
  10831. // We're mainly based on the logic defined into the FreeCamera code
  10832. var TouchCamera = (function (_super) {
  10833. __extends(TouchCamera, _super);
  10834. function TouchCamera(name, position, scene) {
  10835. _super.call(this, name, position, scene);
  10836. this._offsetX = null;
  10837. this._offsetY = null;
  10838. this._pointerCount = 0;
  10839. this._pointerPressed = [];
  10840. this.angularSensibility = 200000.0;
  10841. this.moveSensibility = 500.0;
  10842. }
  10843. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10844. var _this = this;
  10845. var previousPosition;
  10846. if (this._attachedCanvas) {
  10847. return;
  10848. }
  10849. this._attachedCanvas = canvas;
  10850. if (this._onPointerDown === undefined) {
  10851. this._onPointerDown = function (evt) {
  10852. if (!noPreventDefault) {
  10853. evt.preventDefault();
  10854. }
  10855. _this._pointerPressed.push(evt.pointerId);
  10856. if (_this._pointerPressed.length !== 1) {
  10857. return;
  10858. }
  10859. previousPosition = {
  10860. x: evt.clientX,
  10861. y: evt.clientY
  10862. };
  10863. };
  10864. this._onPointerUp = function (evt) {
  10865. if (!noPreventDefault) {
  10866. evt.preventDefault();
  10867. }
  10868. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10869. if (index === -1) {
  10870. return;
  10871. }
  10872. _this._pointerPressed.splice(index, 1);
  10873. if (index != 0) {
  10874. return;
  10875. }
  10876. previousPosition = null;
  10877. _this._offsetX = null;
  10878. _this._offsetY = null;
  10879. };
  10880. this._onPointerMove = function (evt) {
  10881. if (!noPreventDefault) {
  10882. evt.preventDefault();
  10883. }
  10884. if (!previousPosition) {
  10885. return;
  10886. }
  10887. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10888. if (index != 0) {
  10889. return;
  10890. }
  10891. _this._offsetX = evt.clientX - previousPosition.x;
  10892. _this._offsetY = -(evt.clientY - previousPosition.y);
  10893. };
  10894. this._onLostFocus = function () {
  10895. _this._offsetX = null;
  10896. _this._offsetY = null;
  10897. };
  10898. }
  10899. canvas.addEventListener("pointerdown", this._onPointerDown);
  10900. canvas.addEventListener("pointerup", this._onPointerUp);
  10901. canvas.addEventListener("pointerout", this._onPointerUp);
  10902. canvas.addEventListener("pointermove", this._onPointerMove);
  10903. BABYLON.Tools.RegisterTopRootEvents([
  10904. { name: "blur", handler: this._onLostFocus }
  10905. ]);
  10906. };
  10907. TouchCamera.prototype.detachControl = function (canvas) {
  10908. if (this._attachedCanvas != canvas) {
  10909. return;
  10910. }
  10911. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10912. canvas.removeEventListener("pointerup", this._onPointerUp);
  10913. canvas.removeEventListener("pointerout", this._onPointerUp);
  10914. canvas.removeEventListener("pointermove", this._onPointerMove);
  10915. BABYLON.Tools.UnregisterTopRootEvents([
  10916. { name: "blur", handler: this._onLostFocus }
  10917. ]);
  10918. this._attachedCanvas = null;
  10919. };
  10920. TouchCamera.prototype._checkInputs = function () {
  10921. if (this._offsetX) {
  10922. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10923. if (this._pointerPressed.length > 1) {
  10924. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10925. }
  10926. else {
  10927. var speed = this._computeLocalCameraSpeed();
  10928. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10929. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10930. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10931. }
  10932. }
  10933. _super.prototype._checkInputs.call(this);
  10934. };
  10935. return TouchCamera;
  10936. })(BABYLON.FreeCamera);
  10937. BABYLON.TouchCamera = TouchCamera;
  10938. })(BABYLON || (BABYLON = {}));
  10939. var BABYLON;
  10940. (function (BABYLON) {
  10941. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10942. var ArcRotateCamera = (function (_super) {
  10943. __extends(ArcRotateCamera, _super);
  10944. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10945. var _this = this;
  10946. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10947. this.alpha = alpha;
  10948. this.beta = beta;
  10949. this.radius = radius;
  10950. this.target = target;
  10951. this.inertialAlphaOffset = 0;
  10952. this.inertialBetaOffset = 0;
  10953. this.inertialRadiusOffset = 0;
  10954. this.lowerAlphaLimit = null;
  10955. this.upperAlphaLimit = null;
  10956. this.lowerBetaLimit = 0.01;
  10957. this.upperBetaLimit = Math.PI;
  10958. this.lowerRadiusLimit = null;
  10959. this.upperRadiusLimit = null;
  10960. this.angularSensibility = 1000.0;
  10961. this.wheelPrecision = 3.0;
  10962. this.pinchPrecision = 2.0;
  10963. this.panningSensibility = 50.0;
  10964. this.inertialPanningX = 0;
  10965. this.inertialPanningY = 0;
  10966. this.keysUp = [38];
  10967. this.keysDown = [40];
  10968. this.keysLeft = [37];
  10969. this.keysRight = [39];
  10970. this.zoomOnFactor = 1;
  10971. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10972. this.pinchInwards = true;
  10973. this.allowUpsideDown = true;
  10974. this._keys = [];
  10975. this._viewMatrix = new BABYLON.Matrix();
  10976. this._isRightClick = false;
  10977. this._isCtrlPushed = false;
  10978. this.checkCollisions = false;
  10979. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10980. this._collider = new BABYLON.Collider();
  10981. this._previousPosition = BABYLON.Vector3.Zero();
  10982. this._collisionVelocity = BABYLON.Vector3.Zero();
  10983. this._newPosition = BABYLON.Vector3.Zero();
  10984. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10985. if (collidedMesh === void 0) { collidedMesh = null; }
  10986. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10987. newPosition.multiplyInPlace(_this._collider.radius);
  10988. }
  10989. if (!collidedMesh) {
  10990. _this._previousPosition.copyFrom(_this.position);
  10991. }
  10992. else {
  10993. _this.setPosition(_this.position);
  10994. if (_this.onCollide) {
  10995. _this.onCollide(collidedMesh);
  10996. }
  10997. }
  10998. // Recompute because of constraints
  10999. var cosa = Math.cos(_this.alpha);
  11000. var sina = Math.sin(_this.alpha);
  11001. var cosb = Math.cos(_this.beta);
  11002. var sinb = Math.sin(_this.beta);
  11003. var target = _this._getTargetPosition();
  11004. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11005. _this.position.copyFrom(_this._newPosition);
  11006. var up = _this.upVector;
  11007. if (_this.allowUpsideDown && _this.beta < 0) {
  11008. var up = up.clone();
  11009. up = up.negate();
  11010. }
  11011. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11012. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11013. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11014. _this._collisionTriggered = false;
  11015. };
  11016. if (!this.target) {
  11017. this.target = BABYLON.Vector3.Zero();
  11018. }
  11019. this.getViewMatrix();
  11020. }
  11021. ArcRotateCamera.prototype._getTargetPosition = function () {
  11022. return this.target.position || this.target;
  11023. };
  11024. // Cache
  11025. ArcRotateCamera.prototype._initCache = function () {
  11026. _super.prototype._initCache.call(this);
  11027. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11028. this._cache.alpha = undefined;
  11029. this._cache.beta = undefined;
  11030. this._cache.radius = undefined;
  11031. this._cache.targetScreenOffset = undefined;
  11032. };
  11033. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11034. if (!ignoreParentClass) {
  11035. _super.prototype._updateCache.call(this);
  11036. }
  11037. this._cache.target.copyFrom(this._getTargetPosition());
  11038. this._cache.alpha = this.alpha;
  11039. this._cache.beta = this.beta;
  11040. this._cache.radius = this.radius;
  11041. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11042. };
  11043. // Synchronized
  11044. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11045. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11046. return false;
  11047. return this._cache.target.equals(this._getTargetPosition())
  11048. && this._cache.alpha === this.alpha
  11049. && this._cache.beta === this.beta
  11050. && this._cache.radius === this.radius
  11051. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11052. };
  11053. // Methods
  11054. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11055. var _this = this;
  11056. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11057. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11058. var previousPinchDistance = 0;
  11059. var pointers = new BABYLON.SmartCollection();
  11060. if (this._attachedElement) {
  11061. return;
  11062. }
  11063. this._attachedElement = element;
  11064. var engine = this.getEngine();
  11065. if (this._onPointerDown === undefined) {
  11066. this._onPointerDown = function (evt) {
  11067. // Manage panning with right click
  11068. _this._isRightClick = evt.button === 2 ? true : false;
  11069. // manage pointers
  11070. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11071. cacheSoloPointer = pointers.item(evt.pointerId);
  11072. if (!noPreventDefault) {
  11073. evt.preventDefault();
  11074. }
  11075. };
  11076. this._onPointerUp = function (evt) {
  11077. cacheSoloPointer = null;
  11078. previousPinchDistance = 0;
  11079. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11080. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11081. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11082. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11083. pointers.empty();
  11084. if (!noPreventDefault) {
  11085. evt.preventDefault();
  11086. }
  11087. };
  11088. this._onContextMenu = function (evt) {
  11089. evt.preventDefault();
  11090. };
  11091. this._onPointerMove = function (evt) {
  11092. if (!noPreventDefault) {
  11093. evt.preventDefault();
  11094. }
  11095. switch (pointers.count) {
  11096. case 1:
  11097. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11098. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11099. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11100. }
  11101. else {
  11102. var offsetX = evt.clientX - cacheSoloPointer.x;
  11103. var offsetY = evt.clientY - cacheSoloPointer.y;
  11104. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  11105. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  11106. }
  11107. cacheSoloPointer.x = evt.clientX;
  11108. cacheSoloPointer.y = evt.clientY;
  11109. break;
  11110. case 2:
  11111. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11112. pointers.item(evt.pointerId).x = evt.clientX;
  11113. pointers.item(evt.pointerId).y = evt.clientY;
  11114. var direction = _this.pinchInwards ? 1 : -1;
  11115. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11116. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11117. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11118. if (previousPinchDistance === 0) {
  11119. previousPinchDistance = pinchSquaredDistance;
  11120. return;
  11121. }
  11122. if (pinchSquaredDistance !== previousPinchDistance) {
  11123. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  11124. previousPinchDistance = pinchSquaredDistance;
  11125. }
  11126. break;
  11127. default:
  11128. if (pointers.item(evt.pointerId)) {
  11129. pointers.item(evt.pointerId).x = evt.clientX;
  11130. pointers.item(evt.pointerId).y = evt.clientY;
  11131. }
  11132. }
  11133. };
  11134. this._onMouseMove = function (evt) {
  11135. if (!engine.isPointerLock) {
  11136. return;
  11137. }
  11138. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11139. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11140. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  11141. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  11142. if (!noPreventDefault) {
  11143. evt.preventDefault();
  11144. }
  11145. };
  11146. this._wheel = function (event) {
  11147. var delta = 0;
  11148. if (event.wheelDelta) {
  11149. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11150. }
  11151. else if (event.detail) {
  11152. delta = -event.detail / _this.wheelPrecision;
  11153. }
  11154. if (delta)
  11155. _this.inertialRadiusOffset += delta;
  11156. if (event.preventDefault) {
  11157. if (!noPreventDefault) {
  11158. event.preventDefault();
  11159. }
  11160. }
  11161. };
  11162. this._onKeyDown = function (evt) {
  11163. _this._isCtrlPushed = evt.ctrlKey;
  11164. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11165. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11166. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11167. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11168. var index = _this._keys.indexOf(evt.keyCode);
  11169. if (index === -1) {
  11170. _this._keys.push(evt.keyCode);
  11171. }
  11172. if (evt.preventDefault) {
  11173. if (!noPreventDefault) {
  11174. evt.preventDefault();
  11175. }
  11176. }
  11177. }
  11178. };
  11179. this._onKeyUp = function (evt) {
  11180. _this._isCtrlPushed = evt.ctrlKey;
  11181. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11182. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11183. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11184. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11185. var index = _this._keys.indexOf(evt.keyCode);
  11186. if (index >= 0) {
  11187. _this._keys.splice(index, 1);
  11188. }
  11189. if (evt.preventDefault) {
  11190. if (!noPreventDefault) {
  11191. evt.preventDefault();
  11192. }
  11193. }
  11194. }
  11195. };
  11196. this._onLostFocus = function () {
  11197. _this._keys = [];
  11198. pointers.empty();
  11199. previousPinchDistance = 0;
  11200. cacheSoloPointer = null;
  11201. };
  11202. this._onGestureStart = function (e) {
  11203. if (window.MSGesture === undefined) {
  11204. return;
  11205. }
  11206. if (!_this._MSGestureHandler) {
  11207. _this._MSGestureHandler = new MSGesture();
  11208. _this._MSGestureHandler.target = element;
  11209. }
  11210. _this._MSGestureHandler.addPointer(e.pointerId);
  11211. };
  11212. this._onGesture = function (e) {
  11213. _this.radius *= e.scale;
  11214. if (e.preventDefault) {
  11215. if (!noPreventDefault) {
  11216. e.stopPropagation();
  11217. e.preventDefault();
  11218. }
  11219. }
  11220. };
  11221. this._reset = function () {
  11222. _this._keys = [];
  11223. _this.inertialAlphaOffset = 0;
  11224. _this.inertialBetaOffset = 0;
  11225. _this.inertialRadiusOffset = 0;
  11226. pointers.empty();
  11227. previousPinchDistance = 0;
  11228. cacheSoloPointer = null;
  11229. };
  11230. }
  11231. if (!useCtrlForPanning) {
  11232. element.addEventListener("contextmenu", this._onContextMenu, false);
  11233. }
  11234. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11235. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11236. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11237. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11238. element.addEventListener("mousemove", this._onMouseMove, false);
  11239. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11240. element.addEventListener("MSGestureChange", this._onGesture, false);
  11241. element.addEventListener('mousewheel', this._wheel, false);
  11242. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11243. BABYLON.Tools.RegisterTopRootEvents([
  11244. { name: "keydown", handler: this._onKeyDown },
  11245. { name: "keyup", handler: this._onKeyUp },
  11246. { name: "blur", handler: this._onLostFocus }
  11247. ]);
  11248. };
  11249. ArcRotateCamera.prototype.detachControl = function (element) {
  11250. if (this._attachedElement !== element) {
  11251. return;
  11252. }
  11253. element.removeEventListener("contextmenu", this._onContextMenu);
  11254. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11255. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11256. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11257. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11258. element.removeEventListener("mousemove", this._onMouseMove);
  11259. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11260. element.removeEventListener("MSGestureChange", this._onGesture);
  11261. element.removeEventListener('mousewheel', this._wheel);
  11262. element.removeEventListener('DOMMouseScroll', this._wheel);
  11263. BABYLON.Tools.UnregisterTopRootEvents([
  11264. { name: "keydown", handler: this._onKeyDown },
  11265. { name: "keyup", handler: this._onKeyUp },
  11266. { name: "blur", handler: this._onLostFocus }
  11267. ]);
  11268. this._MSGestureHandler = null;
  11269. this._attachedElement = null;
  11270. if (this._reset) {
  11271. this._reset();
  11272. }
  11273. };
  11274. ArcRotateCamera.prototype._checkInputs = function () {
  11275. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11276. if (this._collisionTriggered) {
  11277. return;
  11278. }
  11279. // Keyboard
  11280. for (var index = 0; index < this._keys.length; index++) {
  11281. var keyCode = this._keys[index];
  11282. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11283. this.inertialAlphaOffset -= 0.01;
  11284. }
  11285. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11286. this.inertialBetaOffset -= 0.01;
  11287. }
  11288. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11289. this.inertialAlphaOffset += 0.01;
  11290. }
  11291. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11292. this.inertialBetaOffset += 0.01;
  11293. }
  11294. }
  11295. // Inertia
  11296. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11297. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11298. this.beta += this.inertialBetaOffset;
  11299. this.radius -= this.inertialRadiusOffset;
  11300. this.inertialAlphaOffset *= this.inertia;
  11301. this.inertialBetaOffset *= this.inertia;
  11302. this.inertialRadiusOffset *= this.inertia;
  11303. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11304. this.inertialAlphaOffset = 0;
  11305. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11306. this.inertialBetaOffset = 0;
  11307. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11308. this.inertialRadiusOffset = 0;
  11309. }
  11310. // Panning inertia
  11311. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11312. if (!this._localDirection) {
  11313. this._localDirection = BABYLON.Vector3.Zero();
  11314. this._transformedDirection = BABYLON.Vector3.Zero();
  11315. }
  11316. this.inertialPanningX *= this.inertia;
  11317. this.inertialPanningY *= this.inertia;
  11318. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11319. this.inertialPanningX = 0;
  11320. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11321. this.inertialPanningY = 0;
  11322. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11323. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11324. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11325. this.target.addInPlace(this._transformedDirection);
  11326. }
  11327. // Limits
  11328. this._checkLimits();
  11329. _super.prototype._checkInputs.call(this);
  11330. };
  11331. ArcRotateCamera.prototype._checkLimits = function () {
  11332. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11333. if (this.allowUpsideDown && this.beta > Math.PI) {
  11334. this.beta = this.beta - (2 * Math.PI);
  11335. }
  11336. }
  11337. else {
  11338. if (this.beta < this.lowerBetaLimit) {
  11339. this.beta = this.lowerBetaLimit;
  11340. }
  11341. }
  11342. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11343. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11344. this.beta = this.beta + (2 * Math.PI);
  11345. }
  11346. }
  11347. else {
  11348. if (this.beta > this.upperBetaLimit) {
  11349. this.beta = this.upperBetaLimit;
  11350. }
  11351. }
  11352. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11353. this.alpha = this.lowerAlphaLimit;
  11354. }
  11355. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11356. this.alpha = this.upperAlphaLimit;
  11357. }
  11358. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11359. this.radius = this.lowerRadiusLimit;
  11360. }
  11361. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11362. this.radius = this.upperRadiusLimit;
  11363. }
  11364. };
  11365. ArcRotateCamera.prototype.setPosition = function (position) {
  11366. var radiusv3 = position.subtract(this._getTargetPosition());
  11367. this.radius = radiusv3.length();
  11368. // Alpha
  11369. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11370. if (radiusv3.z < 0) {
  11371. this.alpha = 2 * Math.PI - this.alpha;
  11372. }
  11373. // Beta
  11374. this.beta = Math.acos(radiusv3.y / this.radius);
  11375. this._checkLimits();
  11376. };
  11377. ArcRotateCamera.prototype._getViewMatrix = function () {
  11378. // Compute
  11379. var cosa = Math.cos(this.alpha);
  11380. var sina = Math.sin(this.alpha);
  11381. var cosb = Math.cos(this.beta);
  11382. var sinb = Math.sin(this.beta);
  11383. var target = this._getTargetPosition();
  11384. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11385. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11386. this._collider.radius = this.collisionRadius;
  11387. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11388. this._collisionTriggered = true;
  11389. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11390. }
  11391. else {
  11392. this.position.copyFrom(this._newPosition);
  11393. var up = this.upVector;
  11394. if (this.allowUpsideDown && this.beta < 0) {
  11395. var up = up.clone();
  11396. up = up.negate();
  11397. }
  11398. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11399. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11400. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11401. }
  11402. return this._viewMatrix;
  11403. };
  11404. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11405. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11406. meshes = meshes || this.getScene().meshes;
  11407. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11408. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11409. this.radius = distance * this.zoomOnFactor;
  11410. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11411. };
  11412. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11413. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11414. var meshesOrMinMaxVector;
  11415. var distance;
  11416. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11417. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11418. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11419. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11420. }
  11421. else {
  11422. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11423. distance = meshesOrMinMaxVectorAndDistance.distance;
  11424. }
  11425. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11426. if (!doNotUpdateMaxZ) {
  11427. this.maxZ = distance * 2;
  11428. }
  11429. };
  11430. /**
  11431. * @override
  11432. * Override Camera.createRigCamera
  11433. */
  11434. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11435. switch (this.cameraRigMode) {
  11436. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11437. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11438. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11439. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11440. case BABYLON.Camera.RIG_MODE_VR:
  11441. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11442. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11443. }
  11444. };
  11445. /**
  11446. * @override
  11447. * Override Camera._updateRigCameras
  11448. */
  11449. ArcRotateCamera.prototype._updateRigCameras = function () {
  11450. switch (this.cameraRigMode) {
  11451. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11452. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11453. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11454. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11455. case BABYLON.Camera.RIG_MODE_VR:
  11456. var camLeft = this._rigCameras[0];
  11457. var camRight = this._rigCameras[1];
  11458. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11459. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11460. camLeft.beta = camRight.beta = this.beta;
  11461. camLeft.radius = camRight.radius = this.radius;
  11462. break;
  11463. }
  11464. _super.prototype._updateRigCameras.call(this);
  11465. };
  11466. return ArcRotateCamera;
  11467. })(BABYLON.TargetCamera);
  11468. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11469. })(BABYLON || (BABYLON = {}));
  11470. var BABYLON;
  11471. (function (BABYLON) {
  11472. // We're mainly based on the logic defined into the FreeCamera code
  11473. var DeviceOrientationCamera = (function (_super) {
  11474. __extends(DeviceOrientationCamera, _super);
  11475. function DeviceOrientationCamera(name, position, scene) {
  11476. var _this = this;
  11477. _super.call(this, name, position, scene);
  11478. this._offsetX = null;
  11479. this._offsetY = null;
  11480. this._orientationGamma = 0;
  11481. this._orientationBeta = 0;
  11482. this._initialOrientationGamma = 0;
  11483. this._initialOrientationBeta = 0;
  11484. this.angularSensibility = 10000.0;
  11485. this.moveSensibility = 50.0;
  11486. window.addEventListener("resize", function () {
  11487. _this._initialOrientationGamma = null;
  11488. }, false);
  11489. }
  11490. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11491. var _this = this;
  11492. if (this._attachedCanvas) {
  11493. return;
  11494. }
  11495. this._attachedCanvas = canvas;
  11496. if (!this._orientationChanged) {
  11497. this._orientationChanged = function (evt) {
  11498. if (!_this._initialOrientationGamma) {
  11499. _this._initialOrientationGamma = evt.gamma;
  11500. _this._initialOrientationBeta = evt.beta;
  11501. }
  11502. _this._orientationGamma = evt.gamma;
  11503. _this._orientationBeta = evt.beta;
  11504. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11505. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11506. };
  11507. }
  11508. window.addEventListener("deviceorientation", this._orientationChanged);
  11509. };
  11510. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11511. if (this._attachedCanvas != canvas) {
  11512. return;
  11513. }
  11514. window.removeEventListener("deviceorientation", this._orientationChanged);
  11515. this._attachedCanvas = null;
  11516. this._orientationGamma = 0;
  11517. this._orientationBeta = 0;
  11518. this._initialOrientationGamma = 0;
  11519. this._initialOrientationBeta = 0;
  11520. };
  11521. DeviceOrientationCamera.prototype._checkInputs = function () {
  11522. if (!this._offsetX) {
  11523. return;
  11524. }
  11525. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11526. var speed = this._computeLocalCameraSpeed();
  11527. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11528. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11529. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11530. _super.prototype._checkInputs.call(this);
  11531. };
  11532. return DeviceOrientationCamera;
  11533. })(BABYLON.FreeCamera);
  11534. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11535. })(BABYLON || (BABYLON = {}));
  11536. var BABYLON;
  11537. (function (BABYLON) {
  11538. var Gamepads = (function () {
  11539. function Gamepads(ongamedpadconnected) {
  11540. var _this = this;
  11541. this.babylonGamepads = [];
  11542. this.oneGamepadConnected = false;
  11543. this.isMonitoring = false;
  11544. this.gamepadEventSupported = 'GamepadEvent' in window;
  11545. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11546. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11547. 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=";
  11548. this._callbackGamepadConnected = ongamedpadconnected;
  11549. if (this.gamepadSupportAvailable) {
  11550. // Checking if the gamepad connected event is supported (like in Firefox)
  11551. if (this.gamepadEventSupported) {
  11552. window.addEventListener('gamepadconnected', function (evt) {
  11553. _this._onGamepadConnected(evt);
  11554. }, false);
  11555. window.addEventListener('gamepaddisconnected', function (evt) {
  11556. _this._onGamepadDisconnected(evt);
  11557. }, false);
  11558. }
  11559. else {
  11560. this._startMonitoringGamepads();
  11561. }
  11562. if (!this.oneGamepadConnected) {
  11563. this._insertGamepadDOMInstructions();
  11564. }
  11565. }
  11566. else {
  11567. this._insertGamepadDOMNotSupported();
  11568. }
  11569. }
  11570. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11571. Gamepads.gamepadDOMInfo = document.createElement("div");
  11572. var buttonAImage = document.createElement("img");
  11573. buttonAImage.src = this.buttonADataURL;
  11574. var spanMessage = document.createElement("span");
  11575. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11576. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11577. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11578. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11579. Gamepads.gamepadDOMInfo.style.width = "100%";
  11580. Gamepads.gamepadDOMInfo.style.height = "48px";
  11581. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11582. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11583. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11584. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11585. buttonAImage.style.position = "relative";
  11586. buttonAImage.style.bottom = "8px";
  11587. spanMessage.style.position = "relative";
  11588. spanMessage.style.fontSize = "32px";
  11589. spanMessage.style.bottom = "32px";
  11590. spanMessage.style.color = "green";
  11591. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11592. };
  11593. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11594. Gamepads.gamepadDOMInfo = document.createElement("div");
  11595. var spanMessage = document.createElement("span");
  11596. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11597. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11598. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11599. Gamepads.gamepadDOMInfo.style.width = "100%";
  11600. Gamepads.gamepadDOMInfo.style.height = "40px";
  11601. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11602. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11603. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11604. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11605. spanMessage.style.position = "relative";
  11606. spanMessage.style.fontSize = "32px";
  11607. spanMessage.style.color = "red";
  11608. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11609. };
  11610. Gamepads.prototype.dispose = function () {
  11611. if (Gamepads.gamepadDOMInfo) {
  11612. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11613. }
  11614. };
  11615. Gamepads.prototype._onGamepadConnected = function (evt) {
  11616. var newGamepad = this._addNewGamepad(evt.gamepad);
  11617. if (this._callbackGamepadConnected)
  11618. this._callbackGamepadConnected(newGamepad);
  11619. this._startMonitoringGamepads();
  11620. };
  11621. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11622. if (!this.oneGamepadConnected) {
  11623. this.oneGamepadConnected = true;
  11624. if (Gamepads.gamepadDOMInfo) {
  11625. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11626. Gamepads.gamepadDOMInfo = null;
  11627. }
  11628. }
  11629. var newGamepad;
  11630. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11631. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11632. }
  11633. else {
  11634. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11635. }
  11636. this.babylonGamepads.push(newGamepad);
  11637. return newGamepad;
  11638. };
  11639. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11640. // Remove the gamepad from the list of gamepads to monitor.
  11641. for (var i in this.babylonGamepads) {
  11642. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11643. this.babylonGamepads.splice(i, 1);
  11644. break;
  11645. }
  11646. }
  11647. // If no gamepads are left, stop the polling loop.
  11648. if (this.babylonGamepads.length == 0) {
  11649. this._stopMonitoringGamepads();
  11650. }
  11651. };
  11652. Gamepads.prototype._startMonitoringGamepads = function () {
  11653. if (!this.isMonitoring) {
  11654. this.isMonitoring = true;
  11655. this._checkGamepadsStatus();
  11656. }
  11657. };
  11658. Gamepads.prototype._stopMonitoringGamepads = function () {
  11659. this.isMonitoring = false;
  11660. };
  11661. Gamepads.prototype._checkGamepadsStatus = function () {
  11662. var _this = this;
  11663. // updating gamepad objects
  11664. this._updateGamepadObjects();
  11665. for (var i in this.babylonGamepads) {
  11666. this.babylonGamepads[i].update();
  11667. }
  11668. if (this.isMonitoring) {
  11669. if (window.requestAnimationFrame) {
  11670. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11671. }
  11672. else if (window.mozRequestAnimationFrame) {
  11673. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11674. }
  11675. else if (window.webkitRequestAnimationFrame) {
  11676. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11677. }
  11678. }
  11679. };
  11680. // This function is called only on Chrome, which does not yet support
  11681. // connection/disconnection events, but requires you to monitor
  11682. // an array for changes.
  11683. Gamepads.prototype._updateGamepadObjects = function () {
  11684. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11685. for (var i = 0; i < gamepads.length; i++) {
  11686. if (gamepads[i]) {
  11687. if (!(gamepads[i].index in this.babylonGamepads)) {
  11688. var newGamepad = this._addNewGamepad(gamepads[i]);
  11689. if (this._callbackGamepadConnected) {
  11690. this._callbackGamepadConnected(newGamepad);
  11691. }
  11692. }
  11693. else {
  11694. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11695. }
  11696. }
  11697. }
  11698. };
  11699. return Gamepads;
  11700. })();
  11701. BABYLON.Gamepads = Gamepads;
  11702. var StickValues = (function () {
  11703. function StickValues(x, y) {
  11704. this.x = x;
  11705. this.y = y;
  11706. }
  11707. return StickValues;
  11708. })();
  11709. BABYLON.StickValues = StickValues;
  11710. var Gamepad = (function () {
  11711. function Gamepad(id, index, browserGamepad) {
  11712. this.id = id;
  11713. this.index = index;
  11714. this.browserGamepad = browserGamepad;
  11715. if (this.browserGamepad.axes.length >= 2) {
  11716. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11717. }
  11718. if (this.browserGamepad.axes.length >= 4) {
  11719. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11720. }
  11721. }
  11722. Gamepad.prototype.onleftstickchanged = function (callback) {
  11723. this._onleftstickchanged = callback;
  11724. };
  11725. Gamepad.prototype.onrightstickchanged = function (callback) {
  11726. this._onrightstickchanged = callback;
  11727. };
  11728. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11729. get: function () {
  11730. return this._leftStick;
  11731. },
  11732. set: function (newValues) {
  11733. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11734. this._onleftstickchanged(newValues);
  11735. }
  11736. this._leftStick = newValues;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11742. get: function () {
  11743. return this._rightStick;
  11744. },
  11745. set: function (newValues) {
  11746. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11747. this._onrightstickchanged(newValues);
  11748. }
  11749. this._rightStick = newValues;
  11750. },
  11751. enumerable: true,
  11752. configurable: true
  11753. });
  11754. Gamepad.prototype.update = function () {
  11755. if (this._leftStick) {
  11756. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11757. }
  11758. if (this._rightStick) {
  11759. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11760. }
  11761. };
  11762. return Gamepad;
  11763. })();
  11764. BABYLON.Gamepad = Gamepad;
  11765. var GenericPad = (function (_super) {
  11766. __extends(GenericPad, _super);
  11767. function GenericPad(id, index, gamepad) {
  11768. _super.call(this, id, index, gamepad);
  11769. this.id = id;
  11770. this.index = index;
  11771. this.gamepad = gamepad;
  11772. this._buttons = new Array(gamepad.buttons.length);
  11773. }
  11774. GenericPad.prototype.onbuttondown = function (callback) {
  11775. this._onbuttondown = callback;
  11776. };
  11777. GenericPad.prototype.onbuttonup = function (callback) {
  11778. this._onbuttonup = callback;
  11779. };
  11780. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11781. if (newValue !== currentValue) {
  11782. if (this._onbuttondown && newValue === 1) {
  11783. this._onbuttondown(buttonIndex);
  11784. }
  11785. if (this._onbuttonup && newValue === 0) {
  11786. this._onbuttonup(buttonIndex);
  11787. }
  11788. }
  11789. return newValue;
  11790. };
  11791. GenericPad.prototype.update = function () {
  11792. _super.prototype.update.call(this);
  11793. for (var index = 0; index < this._buttons.length; index++) {
  11794. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11795. }
  11796. };
  11797. return GenericPad;
  11798. })(Gamepad);
  11799. BABYLON.GenericPad = GenericPad;
  11800. (function (Xbox360Button) {
  11801. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11802. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11803. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11804. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11805. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11806. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11807. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11808. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11809. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11810. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11811. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11812. var Xbox360Button = BABYLON.Xbox360Button;
  11813. (function (Xbox360Dpad) {
  11814. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11815. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11816. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11817. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11818. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11819. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11820. var Xbox360Pad = (function (_super) {
  11821. __extends(Xbox360Pad, _super);
  11822. function Xbox360Pad() {
  11823. _super.apply(this, arguments);
  11824. this._leftTrigger = 0;
  11825. this._rightTrigger = 0;
  11826. this._buttonA = 0;
  11827. this._buttonB = 0;
  11828. this._buttonX = 0;
  11829. this._buttonY = 0;
  11830. this._buttonBack = 0;
  11831. this._buttonStart = 0;
  11832. this._buttonLB = 0;
  11833. this._buttonRB = 0;
  11834. this._buttonLeftStick = 0;
  11835. this._buttonRightStick = 0;
  11836. this._dPadUp = 0;
  11837. this._dPadDown = 0;
  11838. this._dPadLeft = 0;
  11839. this._dPadRight = 0;
  11840. }
  11841. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11842. this._onlefttriggerchanged = callback;
  11843. };
  11844. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11845. this._onrighttriggerchanged = callback;
  11846. };
  11847. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11848. get: function () {
  11849. return this._leftTrigger;
  11850. },
  11851. set: function (newValue) {
  11852. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11853. this._onlefttriggerchanged(newValue);
  11854. }
  11855. this._leftTrigger = newValue;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11861. get: function () {
  11862. return this._rightTrigger;
  11863. },
  11864. set: function (newValue) {
  11865. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11866. this._onrighttriggerchanged(newValue);
  11867. }
  11868. this._rightTrigger = newValue;
  11869. },
  11870. enumerable: true,
  11871. configurable: true
  11872. });
  11873. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11874. this._onbuttondown = callback;
  11875. };
  11876. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11877. this._onbuttonup = callback;
  11878. };
  11879. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11880. this._ondpaddown = callback;
  11881. };
  11882. Xbox360Pad.prototype.ondpadup = function (callback) {
  11883. this._ondpadup = callback;
  11884. };
  11885. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11886. if (newValue !== currentValue) {
  11887. if (this._onbuttondown && newValue === 1) {
  11888. this._onbuttondown(buttonType);
  11889. }
  11890. if (this._onbuttonup && newValue === 0) {
  11891. this._onbuttonup(buttonType);
  11892. }
  11893. }
  11894. return newValue;
  11895. };
  11896. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11897. if (newValue !== currentValue) {
  11898. if (this._ondpaddown && newValue === 1) {
  11899. this._ondpaddown(buttonType);
  11900. }
  11901. if (this._ondpadup && newValue === 0) {
  11902. this._ondpadup(buttonType);
  11903. }
  11904. }
  11905. return newValue;
  11906. };
  11907. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11908. get: function () {
  11909. return this._buttonA;
  11910. },
  11911. set: function (value) {
  11912. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11913. },
  11914. enumerable: true,
  11915. configurable: true
  11916. });
  11917. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11918. get: function () {
  11919. return this._buttonB;
  11920. },
  11921. set: function (value) {
  11922. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11928. get: function () {
  11929. return this._buttonX;
  11930. },
  11931. set: function (value) {
  11932. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11938. get: function () {
  11939. return this._buttonY;
  11940. },
  11941. set: function (value) {
  11942. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11943. },
  11944. enumerable: true,
  11945. configurable: true
  11946. });
  11947. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11948. get: function () {
  11949. return this._buttonStart;
  11950. },
  11951. set: function (value) {
  11952. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11953. },
  11954. enumerable: true,
  11955. configurable: true
  11956. });
  11957. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11958. get: function () {
  11959. return this._buttonBack;
  11960. },
  11961. set: function (value) {
  11962. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11968. get: function () {
  11969. return this._buttonLB;
  11970. },
  11971. set: function (value) {
  11972. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11978. get: function () {
  11979. return this._buttonRB;
  11980. },
  11981. set: function (value) {
  11982. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11988. get: function () {
  11989. return this._buttonLeftStick;
  11990. },
  11991. set: function (value) {
  11992. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  11993. },
  11994. enumerable: true,
  11995. configurable: true
  11996. });
  11997. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11998. get: function () {
  11999. return this._buttonRightStick;
  12000. },
  12001. set: function (value) {
  12002. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12003. },
  12004. enumerable: true,
  12005. configurable: true
  12006. });
  12007. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12008. get: function () {
  12009. return this._dPadUp;
  12010. },
  12011. set: function (value) {
  12012. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12018. get: function () {
  12019. return this._dPadDown;
  12020. },
  12021. set: function (value) {
  12022. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12023. },
  12024. enumerable: true,
  12025. configurable: true
  12026. });
  12027. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12028. get: function () {
  12029. return this._dPadLeft;
  12030. },
  12031. set: function (value) {
  12032. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12038. get: function () {
  12039. return this._dPadRight;
  12040. },
  12041. set: function (value) {
  12042. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12043. },
  12044. enumerable: true,
  12045. configurable: true
  12046. });
  12047. Xbox360Pad.prototype.update = function () {
  12048. _super.prototype.update.call(this);
  12049. this.buttonA = this.browserGamepad.buttons[0].value;
  12050. this.buttonB = this.browserGamepad.buttons[1].value;
  12051. this.buttonX = this.browserGamepad.buttons[2].value;
  12052. this.buttonY = this.browserGamepad.buttons[3].value;
  12053. this.buttonLB = this.browserGamepad.buttons[4].value;
  12054. this.buttonRB = this.browserGamepad.buttons[5].value;
  12055. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12056. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12057. this.buttonBack = this.browserGamepad.buttons[8].value;
  12058. this.buttonStart = this.browserGamepad.buttons[9].value;
  12059. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12060. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12061. this.dPadUp = this.browserGamepad.buttons[12].value;
  12062. this.dPadDown = this.browserGamepad.buttons[13].value;
  12063. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12064. this.dPadRight = this.browserGamepad.buttons[15].value;
  12065. };
  12066. return Xbox360Pad;
  12067. })(Gamepad);
  12068. BABYLON.Xbox360Pad = Xbox360Pad;
  12069. })(BABYLON || (BABYLON = {}));
  12070. var BABYLON;
  12071. (function (BABYLON) {
  12072. // We're mainly based on the logic defined into the FreeCamera code
  12073. var GamepadCamera = (function (_super) {
  12074. __extends(GamepadCamera, _super);
  12075. function GamepadCamera(name, position, scene) {
  12076. var _this = this;
  12077. _super.call(this, name, position, scene);
  12078. this.angularSensibility = 200;
  12079. this.moveSensibility = 75;
  12080. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12081. }
  12082. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12083. // Only the first gamepad can control the camera
  12084. if (gamepad.index === 0) {
  12085. this._gamepad = gamepad;
  12086. }
  12087. };
  12088. GamepadCamera.prototype._checkInputs = function () {
  12089. if (this._gamepad) {
  12090. var LSValues = this._gamepad.leftStick;
  12091. var normalizedLX = LSValues.x / this.moveSensibility;
  12092. var normalizedLY = LSValues.y / this.moveSensibility;
  12093. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12094. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12095. var RSValues = this._gamepad.rightStick;
  12096. var normalizedRX = RSValues.x / this.angularSensibility;
  12097. var normalizedRY = RSValues.y / this.angularSensibility;
  12098. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12099. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12100. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12101. var speed = this._computeLocalCameraSpeed() * 50.0;
  12102. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12103. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12104. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12105. }
  12106. _super.prototype._checkInputs.call(this);
  12107. };
  12108. GamepadCamera.prototype.dispose = function () {
  12109. this._gamepads.dispose();
  12110. _super.prototype.dispose.call(this);
  12111. };
  12112. return GamepadCamera;
  12113. })(BABYLON.FreeCamera);
  12114. BABYLON.GamepadCamera = GamepadCamera;
  12115. })(BABYLON || (BABYLON = {}));
  12116. var BABYLON;
  12117. (function (BABYLON) {
  12118. var RenderingManager = (function () {
  12119. function RenderingManager(scene) {
  12120. this._renderingGroups = new Array();
  12121. this._scene = scene;
  12122. }
  12123. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12124. if (this._scene._activeParticleSystems.length === 0) {
  12125. return;
  12126. }
  12127. // Particles
  12128. var beforeParticlesDate = BABYLON.Tools.Now;
  12129. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12130. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12131. if (particleSystem.renderingGroupId !== index) {
  12132. continue;
  12133. }
  12134. this._clearDepthBuffer();
  12135. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12136. this._scene._activeParticles += particleSystem.render();
  12137. }
  12138. }
  12139. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12140. };
  12141. RenderingManager.prototype._renderSprites = function (index) {
  12142. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12143. return;
  12144. }
  12145. // Sprites
  12146. var beforeSpritessDate = BABYLON.Tools.Now;
  12147. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12148. var spriteManager = this._scene.spriteManagers[id];
  12149. if (spriteManager.renderingGroupId === index) {
  12150. this._clearDepthBuffer();
  12151. spriteManager.render();
  12152. }
  12153. }
  12154. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12155. };
  12156. RenderingManager.prototype._clearDepthBuffer = function () {
  12157. if (this._depthBufferAlreadyCleaned) {
  12158. return;
  12159. }
  12160. this._scene.getEngine().clear(0, false, true);
  12161. this._depthBufferAlreadyCleaned = true;
  12162. };
  12163. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12164. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12165. this._depthBufferAlreadyCleaned = false;
  12166. var renderingGroup = this._renderingGroups[index];
  12167. var needToStepBack = false;
  12168. if (renderingGroup) {
  12169. this._clearDepthBuffer();
  12170. if (!renderingGroup.render(customRenderFunction)) {
  12171. this._renderingGroups.splice(index, 1);
  12172. needToStepBack = true;
  12173. }
  12174. }
  12175. if (renderSprites) {
  12176. this._renderSprites(index);
  12177. }
  12178. if (renderParticles) {
  12179. this._renderParticles(index, activeMeshes);
  12180. }
  12181. if (needToStepBack) {
  12182. index--;
  12183. }
  12184. }
  12185. };
  12186. RenderingManager.prototype.reset = function () {
  12187. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12188. if (renderingGroup) {
  12189. renderingGroup.prepare();
  12190. }
  12191. });
  12192. };
  12193. RenderingManager.prototype.dispatch = function (subMesh) {
  12194. var mesh = subMesh.getMesh();
  12195. var renderingGroupId = mesh.renderingGroupId || 0;
  12196. if (!this._renderingGroups[renderingGroupId]) {
  12197. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12198. }
  12199. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12200. };
  12201. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12202. return RenderingManager;
  12203. })();
  12204. BABYLON.RenderingManager = RenderingManager;
  12205. })(BABYLON || (BABYLON = {}));
  12206. var BABYLON;
  12207. (function (BABYLON) {
  12208. var RenderingGroup = (function () {
  12209. function RenderingGroup(index, scene) {
  12210. this.index = index;
  12211. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12212. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12213. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12214. this._scene = scene;
  12215. }
  12216. RenderingGroup.prototype.render = function (customRenderFunction) {
  12217. if (customRenderFunction) {
  12218. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12219. return true;
  12220. }
  12221. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12222. return false;
  12223. }
  12224. var engine = this._scene.getEngine();
  12225. // Opaque
  12226. var subIndex;
  12227. var submesh;
  12228. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12229. submesh = this._opaqueSubMeshes.data[subIndex];
  12230. submesh.render(false);
  12231. }
  12232. // Alpha test
  12233. engine.setAlphaTesting(true);
  12234. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12235. submesh = this._alphaTestSubMeshes.data[subIndex];
  12236. submesh.render(false);
  12237. }
  12238. engine.setAlphaTesting(false);
  12239. // Transparent
  12240. if (this._transparentSubMeshes.length) {
  12241. // Sorting
  12242. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12243. submesh = this._transparentSubMeshes.data[subIndex];
  12244. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12245. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12246. }
  12247. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12248. sortedArray.sort(function (a, b) {
  12249. // Alpha index first
  12250. if (a._alphaIndex > b._alphaIndex) {
  12251. return 1;
  12252. }
  12253. if (a._alphaIndex < b._alphaIndex) {
  12254. return -1;
  12255. }
  12256. // Then distance to camera
  12257. if (a._distanceToCamera < b._distanceToCamera) {
  12258. return 1;
  12259. }
  12260. if (a._distanceToCamera > b._distanceToCamera) {
  12261. return -1;
  12262. }
  12263. return 0;
  12264. });
  12265. // Rendering
  12266. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12267. submesh = sortedArray[subIndex];
  12268. submesh.render(true);
  12269. }
  12270. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12271. }
  12272. return true;
  12273. };
  12274. RenderingGroup.prototype.prepare = function () {
  12275. this._opaqueSubMeshes.reset();
  12276. this._transparentSubMeshes.reset();
  12277. this._alphaTestSubMeshes.reset();
  12278. };
  12279. RenderingGroup.prototype.dispatch = function (subMesh) {
  12280. var material = subMesh.getMaterial();
  12281. var mesh = subMesh.getMesh();
  12282. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12283. this._transparentSubMeshes.push(subMesh);
  12284. }
  12285. else if (material.needAlphaTesting()) {
  12286. this._alphaTestSubMeshes.push(subMesh);
  12287. }
  12288. else {
  12289. this._opaqueSubMeshes.push(subMesh); // Opaque
  12290. }
  12291. };
  12292. return RenderingGroup;
  12293. })();
  12294. BABYLON.RenderingGroup = RenderingGroup;
  12295. })(BABYLON || (BABYLON = {}));
  12296. var BABYLON;
  12297. (function (BABYLON) {
  12298. /**
  12299. * Represents a scene to be rendered by the engine.
  12300. * @see http://doc.babylonjs.com/page.php?p=21911
  12301. */
  12302. var Scene = (function () {
  12303. /**
  12304. * @constructor
  12305. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12306. */
  12307. function Scene(engine) {
  12308. // Members
  12309. this.autoClear = true;
  12310. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12311. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12312. this.forceWireframe = false;
  12313. this.forcePointsCloud = false;
  12314. this.forceShowBoundingBoxes = false;
  12315. this.animationsEnabled = true;
  12316. 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
  12317. // Fog
  12318. /**
  12319. * is fog enabled on this scene.
  12320. * @type {boolean}
  12321. */
  12322. this.fogEnabled = true;
  12323. this.fogMode = Scene.FOGMODE_NONE;
  12324. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12325. this.fogDensity = 0.1;
  12326. this.fogStart = 0;
  12327. this.fogEnd = 1000.0;
  12328. // Lights
  12329. /**
  12330. * is shadow enabled on this scene.
  12331. * @type {boolean}
  12332. */
  12333. this.shadowsEnabled = true;
  12334. /**
  12335. * is light enabled on this scene.
  12336. * @type {boolean}
  12337. */
  12338. this.lightsEnabled = true;
  12339. /**
  12340. * All of the lights added to this scene.
  12341. * @see BABYLON.Light
  12342. * @type {BABYLON.Light[]}
  12343. */
  12344. this.lights = new Array();
  12345. // Cameras
  12346. /**
  12347. * All of the cameras added to this scene.
  12348. * @see BABYLON.Camera
  12349. * @type {BABYLON.Camera[]}
  12350. */
  12351. this.cameras = new Array();
  12352. this.activeCameras = new Array();
  12353. // Meshes
  12354. /**
  12355. * All of the (abstract) meshes added to this scene.
  12356. * @see BABYLON.AbstractMesh
  12357. * @type {BABYLON.AbstractMesh[]}
  12358. */
  12359. this.meshes = new Array();
  12360. // Geometries
  12361. this._geometries = new Array();
  12362. this.materials = new Array();
  12363. this.multiMaterials = new Array();
  12364. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12365. // Textures
  12366. this.texturesEnabled = true;
  12367. this.textures = new Array();
  12368. // Particles
  12369. this.particlesEnabled = true;
  12370. this.particleSystems = new Array();
  12371. // Sprites
  12372. this.spritesEnabled = true;
  12373. this.spriteManagers = new Array();
  12374. // Layers
  12375. this.layers = new Array();
  12376. // Skeletons
  12377. this.skeletonsEnabled = true;
  12378. this.skeletons = new Array();
  12379. // Lens flares
  12380. this.lensFlaresEnabled = true;
  12381. this.lensFlareSystems = new Array();
  12382. // Collisions
  12383. this.collisionsEnabled = true;
  12384. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12385. // Postprocesses
  12386. this.postProcessesEnabled = true;
  12387. // Customs render targets
  12388. this.renderTargetsEnabled = true;
  12389. this.dumpNextRenderTargets = false;
  12390. this.customRenderTargets = new Array();
  12391. // Imported meshes
  12392. this.importedMeshesFiles = new Array();
  12393. this._actionManagers = new Array();
  12394. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12395. // Procedural textures
  12396. this.proceduralTexturesEnabled = true;
  12397. this._proceduralTextures = new Array();
  12398. this.soundTracks = new Array();
  12399. this._audioEnabled = true;
  12400. this._headphone = false;
  12401. this._totalVertices = 0;
  12402. this._activeIndices = 0;
  12403. this._activeParticles = 0;
  12404. this._lastFrameDuration = 0;
  12405. this._evaluateActiveMeshesDuration = 0;
  12406. this._renderTargetsDuration = 0;
  12407. this._particlesDuration = 0;
  12408. this._renderDuration = 0;
  12409. this._spritesDuration = 0;
  12410. this._animationRatio = 0;
  12411. this._renderId = 0;
  12412. this._executeWhenReadyTimeoutId = -1;
  12413. this._toBeDisposed = new BABYLON.SmartArray(256);
  12414. this._onReadyCallbacks = new Array();
  12415. this._pendingData = []; //ANY
  12416. this._onBeforeRenderCallbacks = new Array();
  12417. this._onAfterRenderCallbacks = new Array();
  12418. this._activeMeshes = new BABYLON.SmartArray(256);
  12419. this._processedMaterials = new BABYLON.SmartArray(256);
  12420. this._renderTargets = new BABYLON.SmartArray(256);
  12421. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12422. this._activeSkeletons = new BABYLON.SmartArray(32);
  12423. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12424. this._activeBones = 0;
  12425. this._activeAnimatables = new Array();
  12426. this._transformMatrix = BABYLON.Matrix.Zero();
  12427. this._uniqueIdCounter = 0;
  12428. this._engine = engine;
  12429. engine.scenes.push(this);
  12430. this._renderingManager = new BABYLON.RenderingManager(this);
  12431. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12432. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12433. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12434. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12435. this.attachControl();
  12436. this._debugLayer = new BABYLON.DebugLayer(this);
  12437. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12438. //simplification queue
  12439. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12440. //collision coordinator initialization. For now legacy per default.
  12441. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12442. }
  12443. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12444. get: function () {
  12445. return Scene._FOGMODE_NONE;
  12446. },
  12447. enumerable: true,
  12448. configurable: true
  12449. });
  12450. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12451. get: function () {
  12452. return Scene._FOGMODE_EXP;
  12453. },
  12454. enumerable: true,
  12455. configurable: true
  12456. });
  12457. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12458. get: function () {
  12459. return Scene._FOGMODE_EXP2;
  12460. },
  12461. enumerable: true,
  12462. configurable: true
  12463. });
  12464. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12465. get: function () {
  12466. return Scene._FOGMODE_LINEAR;
  12467. },
  12468. enumerable: true,
  12469. configurable: true
  12470. });
  12471. Object.defineProperty(Scene.prototype, "debugLayer", {
  12472. // Properties
  12473. get: function () {
  12474. return this._debugLayer;
  12475. },
  12476. enumerable: true,
  12477. configurable: true
  12478. });
  12479. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12480. get: function () {
  12481. return this._workerCollisions;
  12482. },
  12483. set: function (enabled) {
  12484. enabled = (enabled && !!Worker);
  12485. this._workerCollisions = enabled;
  12486. if (this.collisionCoordinator) {
  12487. this.collisionCoordinator.destroy();
  12488. }
  12489. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12490. this.collisionCoordinator.init(this);
  12491. },
  12492. enumerable: true,
  12493. configurable: true
  12494. });
  12495. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12496. get: function () {
  12497. return this._selectionOctree;
  12498. },
  12499. enumerable: true,
  12500. configurable: true
  12501. });
  12502. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12503. /**
  12504. * The mesh that is currently under the pointer.
  12505. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12506. */
  12507. get: function () {
  12508. return this._meshUnderPointer;
  12509. },
  12510. enumerable: true,
  12511. configurable: true
  12512. });
  12513. Object.defineProperty(Scene.prototype, "pointerX", {
  12514. /**
  12515. * Current on-screen X position of the pointer
  12516. * @return {number} X position of the pointer
  12517. */
  12518. get: function () {
  12519. return this._pointerX;
  12520. },
  12521. enumerable: true,
  12522. configurable: true
  12523. });
  12524. Object.defineProperty(Scene.prototype, "pointerY", {
  12525. /**
  12526. * Current on-screen Y position of the pointer
  12527. * @return {number} Y position of the pointer
  12528. */
  12529. get: function () {
  12530. return this._pointerY;
  12531. },
  12532. enumerable: true,
  12533. configurable: true
  12534. });
  12535. Scene.prototype.getCachedMaterial = function () {
  12536. return this._cachedMaterial;
  12537. };
  12538. Scene.prototype.getBoundingBoxRenderer = function () {
  12539. return this._boundingBoxRenderer;
  12540. };
  12541. Scene.prototype.getOutlineRenderer = function () {
  12542. return this._outlineRenderer;
  12543. };
  12544. Scene.prototype.getEngine = function () {
  12545. return this._engine;
  12546. };
  12547. Scene.prototype.getTotalVertices = function () {
  12548. return this._totalVertices;
  12549. };
  12550. Scene.prototype.getActiveIndices = function () {
  12551. return this._activeIndices;
  12552. };
  12553. Scene.prototype.getActiveParticles = function () {
  12554. return this._activeParticles;
  12555. };
  12556. Scene.prototype.getActiveBones = function () {
  12557. return this._activeBones;
  12558. };
  12559. // Stats
  12560. Scene.prototype.getLastFrameDuration = function () {
  12561. return this._lastFrameDuration;
  12562. };
  12563. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12564. return this._evaluateActiveMeshesDuration;
  12565. };
  12566. Scene.prototype.getActiveMeshes = function () {
  12567. return this._activeMeshes;
  12568. };
  12569. Scene.prototype.getRenderTargetsDuration = function () {
  12570. return this._renderTargetsDuration;
  12571. };
  12572. Scene.prototype.getRenderDuration = function () {
  12573. return this._renderDuration;
  12574. };
  12575. Scene.prototype.getParticlesDuration = function () {
  12576. return this._particlesDuration;
  12577. };
  12578. Scene.prototype.getSpritesDuration = function () {
  12579. return this._spritesDuration;
  12580. };
  12581. Scene.prototype.getAnimationRatio = function () {
  12582. return this._animationRatio;
  12583. };
  12584. Scene.prototype.getRenderId = function () {
  12585. return this._renderId;
  12586. };
  12587. Scene.prototype.incrementRenderId = function () {
  12588. this._renderId++;
  12589. };
  12590. Scene.prototype._updatePointerPosition = function (evt) {
  12591. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12592. this._pointerX = evt.clientX - canvasRect.left;
  12593. this._pointerY = evt.clientY - canvasRect.top;
  12594. if (this.cameraToUseForPointers) {
  12595. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12596. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12597. }
  12598. };
  12599. // Pointers handling
  12600. Scene.prototype.attachControl = function () {
  12601. var _this = this;
  12602. this._onPointerMove = function (evt) {
  12603. var canvas = _this._engine.getRenderingCanvas();
  12604. _this._updatePointerPosition(evt);
  12605. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12606. if (pickResult.hit) {
  12607. _this._meshUnderPointer = pickResult.pickedMesh;
  12608. _this.setPointerOverMesh(pickResult.pickedMesh);
  12609. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12610. canvas.style.cursor = "pointer";
  12611. }
  12612. else {
  12613. canvas.style.cursor = "";
  12614. }
  12615. }
  12616. else {
  12617. _this.setPointerOverMesh(null);
  12618. canvas.style.cursor = "";
  12619. _this._meshUnderPointer = null;
  12620. }
  12621. };
  12622. this._onPointerDown = function (evt) {
  12623. var predicate = null;
  12624. if (!_this.onPointerDown) {
  12625. predicate = function (mesh) {
  12626. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12627. };
  12628. }
  12629. _this._updatePointerPosition(evt);
  12630. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12631. if (pickResult.hit) {
  12632. if (pickResult.pickedMesh.actionManager) {
  12633. switch (evt.button) {
  12634. case 0:
  12635. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12636. break;
  12637. case 1:
  12638. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12639. break;
  12640. case 2:
  12641. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12642. break;
  12643. }
  12644. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12645. }
  12646. }
  12647. if (_this.onPointerDown) {
  12648. _this.onPointerDown(evt, pickResult);
  12649. }
  12650. };
  12651. this._onPointerUp = function (evt) {
  12652. var predicate = null;
  12653. if (!_this.onPointerUp) {
  12654. predicate = function (mesh) {
  12655. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12656. };
  12657. }
  12658. _this._updatePointerPosition(evt);
  12659. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12660. if (pickResult.hit) {
  12661. if (pickResult.pickedMesh.actionManager) {
  12662. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12663. }
  12664. }
  12665. if (_this.onPointerUp) {
  12666. _this.onPointerUp(evt, pickResult);
  12667. }
  12668. };
  12669. this._onKeyDown = function (evt) {
  12670. if (_this.actionManager) {
  12671. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12672. }
  12673. };
  12674. this._onKeyUp = function (evt) {
  12675. if (_this.actionManager) {
  12676. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12677. }
  12678. };
  12679. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12680. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12681. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12682. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12683. // Wheel
  12684. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12685. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12686. BABYLON.Tools.RegisterTopRootEvents([
  12687. { name: "keydown", handler: this._onKeyDown },
  12688. { name: "keyup", handler: this._onKeyUp }
  12689. ]);
  12690. };
  12691. Scene.prototype.detachControl = function () {
  12692. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12693. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12694. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12695. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12696. // Wheel
  12697. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12698. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12699. BABYLON.Tools.UnregisterTopRootEvents([
  12700. { name: "keydown", handler: this._onKeyDown },
  12701. { name: "keyup", handler: this._onKeyUp }
  12702. ]);
  12703. };
  12704. // Ready
  12705. Scene.prototype.isReady = function () {
  12706. if (this._pendingData.length > 0) {
  12707. return false;
  12708. }
  12709. for (var index = 0; index < this._geometries.length; index++) {
  12710. var geometry = this._geometries[index];
  12711. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12712. return false;
  12713. }
  12714. }
  12715. for (index = 0; index < this.meshes.length; index++) {
  12716. var mesh = this.meshes[index];
  12717. if (!mesh.isReady()) {
  12718. return false;
  12719. }
  12720. var mat = mesh.material;
  12721. if (mat) {
  12722. if (!mat.isReady(mesh)) {
  12723. return false;
  12724. }
  12725. }
  12726. }
  12727. return true;
  12728. };
  12729. Scene.prototype.resetCachedMaterial = function () {
  12730. this._cachedMaterial = null;
  12731. };
  12732. Scene.prototype.registerBeforeRender = function (func) {
  12733. this._onBeforeRenderCallbacks.push(func);
  12734. };
  12735. Scene.prototype.unregisterBeforeRender = function (func) {
  12736. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12737. if (index > -1) {
  12738. this._onBeforeRenderCallbacks.splice(index, 1);
  12739. }
  12740. };
  12741. Scene.prototype.registerAfterRender = function (func) {
  12742. this._onAfterRenderCallbacks.push(func);
  12743. };
  12744. Scene.prototype.unregisterAfterRender = function (func) {
  12745. var index = this._onAfterRenderCallbacks.indexOf(func);
  12746. if (index > -1) {
  12747. this._onAfterRenderCallbacks.splice(index, 1);
  12748. }
  12749. };
  12750. Scene.prototype._addPendingData = function (data) {
  12751. this._pendingData.push(data);
  12752. };
  12753. Scene.prototype._removePendingData = function (data) {
  12754. var index = this._pendingData.indexOf(data);
  12755. if (index !== -1) {
  12756. this._pendingData.splice(index, 1);
  12757. }
  12758. };
  12759. Scene.prototype.getWaitingItemsCount = function () {
  12760. return this._pendingData.length;
  12761. };
  12762. /**
  12763. * Registers a function to be executed when the scene is ready.
  12764. * @param {Function} func - the function to be executed.
  12765. */
  12766. Scene.prototype.executeWhenReady = function (func) {
  12767. var _this = this;
  12768. this._onReadyCallbacks.push(func);
  12769. if (this._executeWhenReadyTimeoutId !== -1) {
  12770. return;
  12771. }
  12772. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12773. _this._checkIsReady();
  12774. }, 150);
  12775. };
  12776. Scene.prototype._checkIsReady = function () {
  12777. var _this = this;
  12778. if (this.isReady()) {
  12779. this._onReadyCallbacks.forEach(function (func) {
  12780. func();
  12781. });
  12782. this._onReadyCallbacks = [];
  12783. this._executeWhenReadyTimeoutId = -1;
  12784. return;
  12785. }
  12786. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12787. _this._checkIsReady();
  12788. }, 150);
  12789. };
  12790. // Animations
  12791. /**
  12792. * Will start the animation sequence of a given target
  12793. * @param target - the target
  12794. * @param {number} from - from which frame should animation start
  12795. * @param {number} to - till which frame should animation run.
  12796. * @param {boolean} [loop] - should the animation loop
  12797. * @param {number} [speedRatio] - the speed in which to run the animation
  12798. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12799. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12800. * @return {BABYLON.Animatable} the animatable object created for this animation
  12801. * @see BABYLON.Animatable
  12802. * @see http://doc.babylonjs.com/page.php?p=22081
  12803. */
  12804. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12805. if (speedRatio === undefined) {
  12806. speedRatio = 1.0;
  12807. }
  12808. this.stopAnimation(target);
  12809. if (!animatable) {
  12810. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12811. }
  12812. // Local animations
  12813. if (target.animations) {
  12814. animatable.appendAnimations(target, target.animations);
  12815. }
  12816. // Children animations
  12817. if (target.getAnimatables) {
  12818. var animatables = target.getAnimatables();
  12819. for (var index = 0; index < animatables.length; index++) {
  12820. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12821. }
  12822. }
  12823. return animatable;
  12824. };
  12825. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12826. if (speedRatio === undefined) {
  12827. speedRatio = 1.0;
  12828. }
  12829. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12830. return animatable;
  12831. };
  12832. Scene.prototype.getAnimatableByTarget = function (target) {
  12833. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12834. if (this._activeAnimatables[index].target === target) {
  12835. return this._activeAnimatables[index];
  12836. }
  12837. }
  12838. return null;
  12839. };
  12840. /**
  12841. * Will stop the animation of the given target
  12842. * @param target - the target
  12843. * @see beginAnimation
  12844. */
  12845. Scene.prototype.stopAnimation = function (target) {
  12846. var animatable = this.getAnimatableByTarget(target);
  12847. if (animatable) {
  12848. animatable.stop();
  12849. }
  12850. };
  12851. Scene.prototype._animate = function () {
  12852. if (!this.animationsEnabled) {
  12853. return;
  12854. }
  12855. if (!this._animationStartDate) {
  12856. this._animationStartDate = BABYLON.Tools.Now;
  12857. }
  12858. // Getting time
  12859. var now = BABYLON.Tools.Now;
  12860. var delay = now - this._animationStartDate;
  12861. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12862. this._activeAnimatables[index]._animate(delay);
  12863. }
  12864. };
  12865. // Matrix
  12866. Scene.prototype.getViewMatrix = function () {
  12867. return this._viewMatrix;
  12868. };
  12869. Scene.prototype.getProjectionMatrix = function () {
  12870. return this._projectionMatrix;
  12871. };
  12872. Scene.prototype.getTransformMatrix = function () {
  12873. return this._transformMatrix;
  12874. };
  12875. Scene.prototype.setTransformMatrix = function (view, projection) {
  12876. this._viewMatrix = view;
  12877. this._projectionMatrix = projection;
  12878. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12879. };
  12880. // Methods
  12881. Scene.prototype.addMesh = function (newMesh) {
  12882. newMesh.uniqueId = this._uniqueIdCounter++;
  12883. var position = this.meshes.push(newMesh);
  12884. //notify the collision coordinator
  12885. this.collisionCoordinator.onMeshAdded(newMesh);
  12886. if (this.onNewMeshAdded) {
  12887. this.onNewMeshAdded(newMesh, position, this);
  12888. }
  12889. };
  12890. Scene.prototype.removeMesh = function (toRemove) {
  12891. var index = this.meshes.indexOf(toRemove);
  12892. if (index !== -1) {
  12893. // Remove from the scene if mesh found
  12894. this.meshes.splice(index, 1);
  12895. }
  12896. //notify the collision coordinator
  12897. this.collisionCoordinator.onMeshRemoved(toRemove);
  12898. if (this.onMeshRemoved) {
  12899. this.onMeshRemoved(toRemove);
  12900. }
  12901. return index;
  12902. };
  12903. Scene.prototype.removeLight = function (toRemove) {
  12904. var index = this.lights.indexOf(toRemove);
  12905. if (index !== -1) {
  12906. // Remove from the scene if mesh found
  12907. this.lights.splice(index, 1);
  12908. }
  12909. if (this.onLightRemoved) {
  12910. this.onLightRemoved(toRemove);
  12911. }
  12912. return index;
  12913. };
  12914. Scene.prototype.removeCamera = function (toRemove) {
  12915. var index = this.cameras.indexOf(toRemove);
  12916. if (index !== -1) {
  12917. // Remove from the scene if mesh found
  12918. this.cameras.splice(index, 1);
  12919. }
  12920. // Remove from activeCameras
  12921. var index2 = this.activeCameras.indexOf(toRemove);
  12922. if (index2 !== -1) {
  12923. // Remove from the scene if mesh found
  12924. this.activeCameras.splice(index2, 1);
  12925. }
  12926. // Reset the activeCamera
  12927. if (this.activeCamera === toRemove) {
  12928. if (this.cameras.length > 0) {
  12929. this.activeCamera = this.cameras[0];
  12930. }
  12931. else {
  12932. this.activeCamera = null;
  12933. }
  12934. }
  12935. if (this.onCameraRemoved) {
  12936. this.onCameraRemoved(toRemove);
  12937. }
  12938. return index;
  12939. };
  12940. Scene.prototype.addLight = function (newLight) {
  12941. newLight.uniqueId = this._uniqueIdCounter++;
  12942. var position = this.lights.push(newLight);
  12943. if (this.onNewLightAdded) {
  12944. this.onNewLightAdded(newLight, position, this);
  12945. }
  12946. };
  12947. Scene.prototype.addCamera = function (newCamera) {
  12948. newCamera.uniqueId = this._uniqueIdCounter++;
  12949. var position = this.cameras.push(newCamera);
  12950. if (this.onNewCameraAdded) {
  12951. this.onNewCameraAdded(newCamera, position, this);
  12952. }
  12953. };
  12954. /**
  12955. * sets the active camera of the scene using its ID
  12956. * @param {string} id - the camera's ID
  12957. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12958. * @see activeCamera
  12959. */
  12960. Scene.prototype.setActiveCameraByID = function (id) {
  12961. var camera = this.getCameraByID(id);
  12962. if (camera) {
  12963. this.activeCamera = camera;
  12964. return camera;
  12965. }
  12966. return null;
  12967. };
  12968. /**
  12969. * sets the active camera of the scene using its name
  12970. * @param {string} name - the camera's name
  12971. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12972. * @see activeCamera
  12973. */
  12974. Scene.prototype.setActiveCameraByName = function (name) {
  12975. var camera = this.getCameraByName(name);
  12976. if (camera) {
  12977. this.activeCamera = camera;
  12978. return camera;
  12979. }
  12980. return null;
  12981. };
  12982. /**
  12983. * get a material using its id
  12984. * @param {string} the material's ID
  12985. * @return {BABYLON.Material|null} the material or null if none found.
  12986. */
  12987. Scene.prototype.getMaterialByID = function (id) {
  12988. for (var index = 0; index < this.materials.length; index++) {
  12989. if (this.materials[index].id === id) {
  12990. return this.materials[index];
  12991. }
  12992. }
  12993. return null;
  12994. };
  12995. /**
  12996. * get a material using its name
  12997. * @param {string} the material's name
  12998. * @return {BABYLON.Material|null} the material or null if none found.
  12999. */
  13000. Scene.prototype.getMaterialByName = function (name) {
  13001. for (var index = 0; index < this.materials.length; index++) {
  13002. if (this.materials[index].name === name) {
  13003. return this.materials[index];
  13004. }
  13005. }
  13006. return null;
  13007. };
  13008. Scene.prototype.getLensFlareSystemByName = function (name) {
  13009. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13010. if (this.lensFlareSystems[index].name === name) {
  13011. return this.lensFlareSystems[index];
  13012. }
  13013. }
  13014. return null;
  13015. };
  13016. Scene.prototype.getCameraByID = function (id) {
  13017. for (var index = 0; index < this.cameras.length; index++) {
  13018. if (this.cameras[index].id === id) {
  13019. return this.cameras[index];
  13020. }
  13021. }
  13022. return null;
  13023. };
  13024. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13025. for (var index = 0; index < this.cameras.length; index++) {
  13026. if (this.cameras[index].uniqueId === uniqueId) {
  13027. return this.cameras[index];
  13028. }
  13029. }
  13030. return null;
  13031. };
  13032. /**
  13033. * get a camera using its name
  13034. * @param {string} the camera's name
  13035. * @return {BABYLON.Camera|null} the camera or null if none found.
  13036. */
  13037. Scene.prototype.getCameraByName = function (name) {
  13038. for (var index = 0; index < this.cameras.length; index++) {
  13039. if (this.cameras[index].name === name) {
  13040. return this.cameras[index];
  13041. }
  13042. }
  13043. return null;
  13044. };
  13045. /**
  13046. * get a light node using its name
  13047. * @param {string} the light's name
  13048. * @return {BABYLON.Light|null} the light or null if none found.
  13049. */
  13050. Scene.prototype.getLightByName = function (name) {
  13051. for (var index = 0; index < this.lights.length; index++) {
  13052. if (this.lights[index].name === name) {
  13053. return this.lights[index];
  13054. }
  13055. }
  13056. return null;
  13057. };
  13058. /**
  13059. * get a light node using its ID
  13060. * @param {string} the light's id
  13061. * @return {BABYLON.Light|null} the light or null if none found.
  13062. */
  13063. Scene.prototype.getLightByID = function (id) {
  13064. for (var index = 0; index < this.lights.length; index++) {
  13065. if (this.lights[index].id === id) {
  13066. return this.lights[index];
  13067. }
  13068. }
  13069. return null;
  13070. };
  13071. /**
  13072. * get a light node using its scene-generated unique ID
  13073. * @param {number} the light's unique id
  13074. * @return {BABYLON.Light|null} the light or null if none found.
  13075. */
  13076. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13077. for (var index = 0; index < this.lights.length; index++) {
  13078. if (this.lights[index].uniqueId === uniqueId) {
  13079. return this.lights[index];
  13080. }
  13081. }
  13082. return null;
  13083. };
  13084. /**
  13085. * get a geometry using its ID
  13086. * @param {string} the geometry's id
  13087. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13088. */
  13089. Scene.prototype.getGeometryByID = function (id) {
  13090. for (var index = 0; index < this._geometries.length; index++) {
  13091. if (this._geometries[index].id === id) {
  13092. return this._geometries[index];
  13093. }
  13094. }
  13095. return null;
  13096. };
  13097. /**
  13098. * add a new geometry to this scene.
  13099. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13100. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13101. * @return {boolean} was the geometry added or not
  13102. */
  13103. Scene.prototype.pushGeometry = function (geometry, force) {
  13104. if (!force && this.getGeometryByID(geometry.id)) {
  13105. return false;
  13106. }
  13107. this._geometries.push(geometry);
  13108. //notify the collision coordinator
  13109. this.collisionCoordinator.onGeometryAdded(geometry);
  13110. if (this.onGeometryAdded) {
  13111. this.onGeometryAdded(geometry);
  13112. }
  13113. return true;
  13114. };
  13115. /**
  13116. * Removes an existing geometry
  13117. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13118. * @return {boolean} was the geometry removed or not
  13119. */
  13120. Scene.prototype.removeGeometry = function (geometry) {
  13121. var index = this._geometries.indexOf(geometry);
  13122. if (index > -1) {
  13123. this._geometries.splice(index, 1);
  13124. //notify the collision coordinator
  13125. this.collisionCoordinator.onGeometryDeleted(geometry);
  13126. if (this.onGeometryRemoved) {
  13127. this.onGeometryRemoved(geometry);
  13128. }
  13129. return true;
  13130. }
  13131. return false;
  13132. };
  13133. Scene.prototype.getGeometries = function () {
  13134. return this._geometries;
  13135. };
  13136. /**
  13137. * Get the first added mesh found of a given ID
  13138. * @param {string} id - the id to search for
  13139. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13140. */
  13141. Scene.prototype.getMeshByID = function (id) {
  13142. for (var index = 0; index < this.meshes.length; index++) {
  13143. if (this.meshes[index].id === id) {
  13144. return this.meshes[index];
  13145. }
  13146. }
  13147. return null;
  13148. };
  13149. /**
  13150. * Get a mesh with its auto-generated unique id
  13151. * @param {number} uniqueId - the unique id to search for
  13152. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13153. */
  13154. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13155. for (var index = 0; index < this.meshes.length; index++) {
  13156. if (this.meshes[index].uniqueId === uniqueId) {
  13157. return this.meshes[index];
  13158. }
  13159. }
  13160. return null;
  13161. };
  13162. /**
  13163. * Get a the last added mesh found of a given ID
  13164. * @param {string} id - the id to search for
  13165. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13166. */
  13167. Scene.prototype.getLastMeshByID = function (id) {
  13168. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13169. if (this.meshes[index].id === id) {
  13170. return this.meshes[index];
  13171. }
  13172. }
  13173. return null;
  13174. };
  13175. /**
  13176. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13177. * @param {string} id - the id to search for
  13178. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13179. */
  13180. Scene.prototype.getLastEntryByID = function (id) {
  13181. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13182. if (this.meshes[index].id === id) {
  13183. return this.meshes[index];
  13184. }
  13185. }
  13186. for (index = this.cameras.length - 1; index >= 0; index--) {
  13187. if (this.cameras[index].id === id) {
  13188. return this.cameras[index];
  13189. }
  13190. }
  13191. for (index = this.lights.length - 1; index >= 0; index--) {
  13192. if (this.lights[index].id === id) {
  13193. return this.lights[index];
  13194. }
  13195. }
  13196. return null;
  13197. };
  13198. Scene.prototype.getNodeByID = function (id) {
  13199. var mesh = this.getMeshByID(id);
  13200. if (mesh) {
  13201. return mesh;
  13202. }
  13203. var light = this.getLightByID(id);
  13204. if (light) {
  13205. return light;
  13206. }
  13207. return this.getCameraByID(id);
  13208. };
  13209. Scene.prototype.getNodeByName = function (name) {
  13210. var mesh = this.getMeshByName(name);
  13211. if (mesh) {
  13212. return mesh;
  13213. }
  13214. var light = this.getLightByName(name);
  13215. if (light) {
  13216. return light;
  13217. }
  13218. return this.getCameraByName(name);
  13219. };
  13220. Scene.prototype.getMeshByName = function (name) {
  13221. for (var index = 0; index < this.meshes.length; index++) {
  13222. if (this.meshes[index].name === name) {
  13223. return this.meshes[index];
  13224. }
  13225. }
  13226. return null;
  13227. };
  13228. Scene.prototype.getSoundByName = function (name) {
  13229. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13230. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13231. return this.mainSoundTrack.soundCollection[index];
  13232. }
  13233. }
  13234. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13235. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13236. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13237. return this.soundTracks[sdIndex].soundCollection[index];
  13238. }
  13239. }
  13240. }
  13241. return null;
  13242. };
  13243. Scene.prototype.getLastSkeletonByID = function (id) {
  13244. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13245. if (this.skeletons[index].id === id) {
  13246. return this.skeletons[index];
  13247. }
  13248. }
  13249. return null;
  13250. };
  13251. Scene.prototype.getSkeletonById = function (id) {
  13252. for (var index = 0; index < this.skeletons.length; index++) {
  13253. if (this.skeletons[index].id === id) {
  13254. return this.skeletons[index];
  13255. }
  13256. }
  13257. return null;
  13258. };
  13259. Scene.prototype.getSkeletonByName = function (name) {
  13260. for (var index = 0; index < this.skeletons.length; index++) {
  13261. if (this.skeletons[index].name === name) {
  13262. return this.skeletons[index];
  13263. }
  13264. }
  13265. return null;
  13266. };
  13267. Scene.prototype.isActiveMesh = function (mesh) {
  13268. return (this._activeMeshes.indexOf(mesh) !== -1);
  13269. };
  13270. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13271. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13272. var material = subMesh.getMaterial();
  13273. if (mesh.showSubMeshesBoundingBox) {
  13274. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13275. }
  13276. if (material) {
  13277. // Render targets
  13278. if (material.getRenderTargetTextures) {
  13279. if (this._processedMaterials.indexOf(material) === -1) {
  13280. this._processedMaterials.push(material);
  13281. this._renderTargets.concat(material.getRenderTargetTextures());
  13282. }
  13283. }
  13284. // Dispatch
  13285. this._activeIndices += subMesh.indexCount;
  13286. this._renderingManager.dispatch(subMesh);
  13287. }
  13288. }
  13289. };
  13290. Scene.prototype._evaluateActiveMeshes = function () {
  13291. this.activeCamera._activeMeshes.reset();
  13292. this._activeMeshes.reset();
  13293. this._renderingManager.reset();
  13294. this._processedMaterials.reset();
  13295. this._activeParticleSystems.reset();
  13296. this._activeSkeletons.reset();
  13297. this._softwareSkinnedMeshes.reset();
  13298. this._boundingBoxRenderer.reset();
  13299. if (!this._frustumPlanes) {
  13300. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13301. }
  13302. else {
  13303. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13304. }
  13305. // Meshes
  13306. var meshes;
  13307. var len;
  13308. if (this._selectionOctree) {
  13309. var selection = this._selectionOctree.select(this._frustumPlanes);
  13310. meshes = selection.data;
  13311. len = selection.length;
  13312. }
  13313. else {
  13314. len = this.meshes.length;
  13315. meshes = this.meshes;
  13316. }
  13317. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13318. var mesh = meshes[meshIndex];
  13319. if (mesh.isBlocked) {
  13320. continue;
  13321. }
  13322. this._totalVertices += mesh.getTotalVertices();
  13323. if (!mesh.isReady() || !mesh.isEnabled()) {
  13324. continue;
  13325. }
  13326. mesh.computeWorldMatrix();
  13327. // Intersections
  13328. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13329. this._meshesForIntersections.pushNoDuplicate(mesh);
  13330. }
  13331. // Switch to current LOD
  13332. var meshLOD = mesh.getLOD(this.activeCamera);
  13333. if (!meshLOD) {
  13334. continue;
  13335. }
  13336. mesh._preActivate();
  13337. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13338. this._activeMeshes.push(mesh);
  13339. this.activeCamera._activeMeshes.push(mesh);
  13340. mesh._activate(this._renderId);
  13341. this._activeMesh(meshLOD);
  13342. }
  13343. }
  13344. // Particle systems
  13345. var beforeParticlesDate = BABYLON.Tools.Now;
  13346. if (this.particlesEnabled) {
  13347. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13348. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13349. var particleSystem = this.particleSystems[particleIndex];
  13350. if (!particleSystem.isStarted()) {
  13351. continue;
  13352. }
  13353. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13354. this._activeParticleSystems.push(particleSystem);
  13355. particleSystem.animate();
  13356. }
  13357. }
  13358. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13359. }
  13360. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13361. };
  13362. Scene.prototype._activeMesh = function (mesh) {
  13363. if (mesh.skeleton && this.skeletonsEnabled) {
  13364. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13365. if (!mesh.computeBonesUsingShaders) {
  13366. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13367. }
  13368. }
  13369. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13370. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13371. }
  13372. if (mesh && mesh.subMeshes) {
  13373. // Submeshes Octrees
  13374. var len;
  13375. var subMeshes;
  13376. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13377. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13378. len = intersections.length;
  13379. subMeshes = intersections.data;
  13380. }
  13381. else {
  13382. subMeshes = mesh.subMeshes;
  13383. len = subMeshes.length;
  13384. }
  13385. for (var subIndex = 0; subIndex < len; subIndex++) {
  13386. var subMesh = subMeshes[subIndex];
  13387. this._evaluateSubMesh(subMesh, mesh);
  13388. }
  13389. }
  13390. };
  13391. Scene.prototype.updateTransformMatrix = function (force) {
  13392. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13393. };
  13394. Scene.prototype._renderForCamera = function (camera) {
  13395. var engine = this._engine;
  13396. this.activeCamera = camera;
  13397. if (!this.activeCamera)
  13398. throw new Error("Active camera not set");
  13399. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13400. // Viewport
  13401. engine.setViewport(this.activeCamera.viewport);
  13402. // Camera
  13403. this.resetCachedMaterial();
  13404. this._renderId++;
  13405. this.updateTransformMatrix();
  13406. if (this.beforeCameraRender) {
  13407. this.beforeCameraRender(this.activeCamera);
  13408. }
  13409. // Meshes
  13410. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13411. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13412. this._evaluateActiveMeshes();
  13413. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13414. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13415. // Skeletons
  13416. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13417. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13418. skeleton.prepare();
  13419. }
  13420. // Software skinning
  13421. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13422. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13423. mesh.applySkeleton(mesh.skeleton);
  13424. }
  13425. // Render targets
  13426. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13427. if (this.renderTargetsEnabled) {
  13428. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13429. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13430. var renderTarget = this._renderTargets.data[renderIndex];
  13431. if (renderTarget._shouldRender()) {
  13432. this._renderId++;
  13433. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13434. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13435. }
  13436. }
  13437. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13438. this._renderId++;
  13439. }
  13440. if (this._renderTargets.length > 0) {
  13441. engine.restoreDefaultFramebuffer();
  13442. }
  13443. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13444. // Prepare Frame
  13445. this.postProcessManager._prepareFrame();
  13446. var beforeRenderDate = BABYLON.Tools.Now;
  13447. // Backgrounds
  13448. if (this.layers.length) {
  13449. engine.setDepthBuffer(false);
  13450. var layerIndex;
  13451. var layer;
  13452. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13453. layer = this.layers[layerIndex];
  13454. if (layer.isBackground) {
  13455. layer.render();
  13456. }
  13457. }
  13458. engine.setDepthBuffer(true);
  13459. }
  13460. // Render
  13461. BABYLON.Tools.StartPerformanceCounter("Main render");
  13462. this._renderingManager.render(null, null, true, true);
  13463. BABYLON.Tools.EndPerformanceCounter("Main render");
  13464. // Bounding boxes
  13465. this._boundingBoxRenderer.render();
  13466. // Lens flares
  13467. if (this.lensFlaresEnabled) {
  13468. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13469. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13470. this.lensFlareSystems[lensFlareSystemIndex].render();
  13471. }
  13472. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13473. }
  13474. // Foregrounds
  13475. if (this.layers.length) {
  13476. engine.setDepthBuffer(false);
  13477. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13478. layer = this.layers[layerIndex];
  13479. if (!layer.isBackground) {
  13480. layer.render();
  13481. }
  13482. }
  13483. engine.setDepthBuffer(true);
  13484. }
  13485. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13486. // Finalize frame
  13487. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13488. // Update camera
  13489. this.activeCamera._updateFromScene();
  13490. // Reset some special arrays
  13491. this._renderTargets.reset();
  13492. if (this.afterCameraRender) {
  13493. this.afterCameraRender(this.activeCamera);
  13494. }
  13495. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13496. };
  13497. Scene.prototype._processSubCameras = function (camera) {
  13498. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13499. this._renderForCamera(camera);
  13500. return;
  13501. }
  13502. // rig cameras
  13503. for (var index = 0; index < camera._rigCameras.length; index++) {
  13504. this._renderForCamera(camera._rigCameras[index]);
  13505. }
  13506. this.activeCamera = camera;
  13507. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13508. // Update camera
  13509. this.activeCamera._updateFromScene();
  13510. };
  13511. Scene.prototype._checkIntersections = function () {
  13512. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13513. var sourceMesh = this._meshesForIntersections.data[index];
  13514. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13515. var action = sourceMesh.actionManager.actions[actionIndex];
  13516. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13517. var parameters = action.getTriggerParameter();
  13518. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13519. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13520. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13521. if (areIntersecting && currentIntersectionInProgress === -1) {
  13522. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13523. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13524. sourceMesh._intersectionsInProgress.push(otherMesh);
  13525. }
  13526. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13527. sourceMesh._intersectionsInProgress.push(otherMesh);
  13528. }
  13529. }
  13530. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13531. //They intersected, and now they don't.
  13532. //is this trigger an exit trigger? execute an event.
  13533. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13534. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13535. }
  13536. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13537. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13538. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13539. }
  13540. }
  13541. }
  13542. }
  13543. }
  13544. };
  13545. Scene.prototype.render = function () {
  13546. var startDate = BABYLON.Tools.Now;
  13547. this._particlesDuration = 0;
  13548. this._spritesDuration = 0;
  13549. this._activeParticles = 0;
  13550. this._renderDuration = 0;
  13551. this._renderTargetsDuration = 0;
  13552. this._evaluateActiveMeshesDuration = 0;
  13553. this._totalVertices = 0;
  13554. this._activeIndices = 0;
  13555. this._activeBones = 0;
  13556. this.getEngine().resetDrawCalls();
  13557. this._meshesForIntersections.reset();
  13558. this.resetCachedMaterial();
  13559. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13560. // Actions
  13561. if (this.actionManager) {
  13562. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13563. }
  13564. //Simplification Queue
  13565. if (!this.simplificationQueue.running) {
  13566. this.simplificationQueue.executeNext();
  13567. }
  13568. // Before render
  13569. if (this.beforeRender) {
  13570. this.beforeRender();
  13571. }
  13572. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13573. this._onBeforeRenderCallbacks[callbackIndex]();
  13574. }
  13575. // Animations
  13576. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13577. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13578. this._animate();
  13579. // Physics
  13580. if (this._physicsEngine) {
  13581. BABYLON.Tools.StartPerformanceCounter("Physics");
  13582. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13583. BABYLON.Tools.EndPerformanceCounter("Physics");
  13584. }
  13585. // Customs render targets
  13586. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13587. var engine = this.getEngine();
  13588. var currentActiveCamera = this.activeCamera;
  13589. if (this.renderTargetsEnabled) {
  13590. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13591. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13592. var renderTarget = this.customRenderTargets[customIndex];
  13593. if (renderTarget._shouldRender()) {
  13594. this._renderId++;
  13595. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13596. if (!this.activeCamera)
  13597. throw new Error("Active camera not set");
  13598. // Viewport
  13599. engine.setViewport(this.activeCamera.viewport);
  13600. // Camera
  13601. this.updateTransformMatrix();
  13602. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13603. }
  13604. }
  13605. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13606. this._renderId++;
  13607. }
  13608. if (this.customRenderTargets.length > 0) {
  13609. engine.restoreDefaultFramebuffer();
  13610. }
  13611. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13612. this.activeCamera = currentActiveCamera;
  13613. // Procedural textures
  13614. if (this.proceduralTexturesEnabled) {
  13615. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13616. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13617. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13618. if (proceduralTexture._shouldRender()) {
  13619. proceduralTexture.render();
  13620. }
  13621. }
  13622. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13623. }
  13624. // Clear
  13625. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13626. // Shadows
  13627. if (this.shadowsEnabled) {
  13628. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13629. var light = this.lights[lightIndex];
  13630. var shadowGenerator = light.getShadowGenerator();
  13631. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13632. this._renderTargets.push(shadowGenerator.getShadowMap());
  13633. }
  13634. }
  13635. }
  13636. // Depth renderer
  13637. if (this._depthRenderer) {
  13638. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13639. }
  13640. // RenderPipeline
  13641. this.postProcessRenderPipelineManager.update();
  13642. // Multi-cameras?
  13643. if (this.activeCameras.length > 0) {
  13644. var currentRenderId = this._renderId;
  13645. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13646. this._renderId = currentRenderId;
  13647. this._processSubCameras(this.activeCameras[cameraIndex]);
  13648. }
  13649. }
  13650. else {
  13651. if (!this.activeCamera) {
  13652. throw new Error("No camera defined");
  13653. }
  13654. this._processSubCameras(this.activeCamera);
  13655. }
  13656. // Intersection checks
  13657. this._checkIntersections();
  13658. // Update the audio listener attached to the camera
  13659. this._updateAudioParameters();
  13660. // After render
  13661. if (this.afterRender) {
  13662. this.afterRender();
  13663. }
  13664. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13665. this._onAfterRenderCallbacks[callbackIndex]();
  13666. }
  13667. // Cleaning
  13668. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13669. this._toBeDisposed.data[index].dispose();
  13670. this._toBeDisposed[index] = null;
  13671. }
  13672. this._toBeDisposed.reset();
  13673. if (this.dumpNextRenderTargets) {
  13674. this.dumpNextRenderTargets = false;
  13675. }
  13676. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13677. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13678. };
  13679. Scene.prototype._updateAudioParameters = function () {
  13680. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13681. return;
  13682. }
  13683. var listeningCamera;
  13684. var audioEngine = BABYLON.Engine.audioEngine;
  13685. if (this.activeCameras.length > 0) {
  13686. listeningCamera = this.activeCameras[0];
  13687. }
  13688. else {
  13689. listeningCamera = this.activeCamera;
  13690. }
  13691. if (listeningCamera && audioEngine.canUseWebAudio) {
  13692. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13693. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13694. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13695. cameraDirection.normalize();
  13696. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13697. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13698. var sound = this.mainSoundTrack.soundCollection[i];
  13699. if (sound.useCustomAttenuation) {
  13700. sound.updateDistanceFromListener();
  13701. }
  13702. }
  13703. for (i = 0; i < this.soundTracks.length; i++) {
  13704. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13705. sound = this.soundTracks[i].soundCollection[j];
  13706. if (sound.useCustomAttenuation) {
  13707. sound.updateDistanceFromListener();
  13708. }
  13709. }
  13710. }
  13711. }
  13712. };
  13713. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13714. // Audio
  13715. get: function () {
  13716. return this._audioEnabled;
  13717. },
  13718. set: function (value) {
  13719. this._audioEnabled = value;
  13720. if (this._audioEnabled) {
  13721. this._enableAudio();
  13722. }
  13723. else {
  13724. this._disableAudio();
  13725. }
  13726. },
  13727. enumerable: true,
  13728. configurable: true
  13729. });
  13730. Scene.prototype._disableAudio = function () {
  13731. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13732. this.mainSoundTrack.soundCollection[i].pause();
  13733. }
  13734. for (i = 0; i < this.soundTracks.length; i++) {
  13735. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13736. this.soundTracks[i].soundCollection[j].pause();
  13737. }
  13738. }
  13739. };
  13740. Scene.prototype._enableAudio = function () {
  13741. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13742. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13743. this.mainSoundTrack.soundCollection[i].play();
  13744. }
  13745. }
  13746. for (i = 0; i < this.soundTracks.length; i++) {
  13747. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13748. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13749. this.soundTracks[i].soundCollection[j].play();
  13750. }
  13751. }
  13752. }
  13753. };
  13754. Object.defineProperty(Scene.prototype, "headphone", {
  13755. get: function () {
  13756. return this._headphone;
  13757. },
  13758. set: function (value) {
  13759. this._headphone = value;
  13760. if (this._headphone) {
  13761. this._switchAudioModeForHeadphones();
  13762. }
  13763. else {
  13764. this._switchAudioModeForNormalSpeakers();
  13765. }
  13766. },
  13767. enumerable: true,
  13768. configurable: true
  13769. });
  13770. Scene.prototype._switchAudioModeForHeadphones = function () {
  13771. this.mainSoundTrack.switchPanningModelToHRTF();
  13772. for (var i = 0; i < this.soundTracks.length; i++) {
  13773. this.soundTracks[i].switchPanningModelToHRTF();
  13774. }
  13775. };
  13776. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13777. this.mainSoundTrack.switchPanningModelToEqualPower();
  13778. for (var i = 0; i < this.soundTracks.length; i++) {
  13779. this.soundTracks[i].switchPanningModelToEqualPower();
  13780. }
  13781. };
  13782. Scene.prototype.enableDepthRenderer = function () {
  13783. if (this._depthRenderer) {
  13784. return this._depthRenderer;
  13785. }
  13786. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13787. return this._depthRenderer;
  13788. };
  13789. Scene.prototype.disableDepthRenderer = function () {
  13790. if (!this._depthRenderer) {
  13791. return;
  13792. }
  13793. this._depthRenderer.dispose();
  13794. this._depthRenderer = null;
  13795. };
  13796. Scene.prototype.dispose = function () {
  13797. this.beforeRender = null;
  13798. this.afterRender = null;
  13799. this.skeletons = [];
  13800. this._boundingBoxRenderer.dispose();
  13801. if (this._depthRenderer) {
  13802. this._depthRenderer.dispose();
  13803. }
  13804. // Debug layer
  13805. this.debugLayer.hide();
  13806. // Events
  13807. if (this.onDispose) {
  13808. this.onDispose();
  13809. }
  13810. this._onBeforeRenderCallbacks = [];
  13811. this._onAfterRenderCallbacks = [];
  13812. this.detachControl();
  13813. // Release sounds & sounds tracks
  13814. this.disposeSounds();
  13815. // Detach cameras
  13816. var canvas = this._engine.getRenderingCanvas();
  13817. var index;
  13818. for (index = 0; index < this.cameras.length; index++) {
  13819. this.cameras[index].detachControl(canvas);
  13820. }
  13821. // Release lights
  13822. while (this.lights.length) {
  13823. this.lights[0].dispose();
  13824. }
  13825. // Release meshes
  13826. while (this.meshes.length) {
  13827. this.meshes[0].dispose(true);
  13828. }
  13829. // Release cameras
  13830. while (this.cameras.length) {
  13831. this.cameras[0].dispose();
  13832. }
  13833. // Release materials
  13834. while (this.materials.length) {
  13835. this.materials[0].dispose();
  13836. }
  13837. // Release particles
  13838. while (this.particleSystems.length) {
  13839. this.particleSystems[0].dispose();
  13840. }
  13841. // Release sprites
  13842. while (this.spriteManagers.length) {
  13843. this.spriteManagers[0].dispose();
  13844. }
  13845. // Release layers
  13846. while (this.layers.length) {
  13847. this.layers[0].dispose();
  13848. }
  13849. // Release textures
  13850. while (this.textures.length) {
  13851. this.textures[0].dispose();
  13852. }
  13853. // Post-processes
  13854. this.postProcessManager.dispose();
  13855. // Physics
  13856. if (this._physicsEngine) {
  13857. this.disablePhysicsEngine();
  13858. }
  13859. // Remove from engine
  13860. index = this._engine.scenes.indexOf(this);
  13861. if (index > -1) {
  13862. this._engine.scenes.splice(index, 1);
  13863. }
  13864. this._engine.wipeCaches();
  13865. };
  13866. // Release sounds & sounds tracks
  13867. Scene.prototype.disposeSounds = function () {
  13868. this.mainSoundTrack.dispose();
  13869. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13870. this.soundTracks[scIndex].dispose();
  13871. }
  13872. };
  13873. // Octrees
  13874. Scene.prototype.getWorldExtends = function () {
  13875. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13876. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13877. for (var index = 0; index < this.meshes.length; index++) {
  13878. var mesh = this.meshes[index];
  13879. mesh.computeWorldMatrix(true);
  13880. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13881. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13882. BABYLON.Tools.CheckExtends(minBox, min, max);
  13883. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13884. }
  13885. return {
  13886. min: min,
  13887. max: max
  13888. };
  13889. };
  13890. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13891. if (maxCapacity === void 0) { maxCapacity = 64; }
  13892. if (maxDepth === void 0) { maxDepth = 2; }
  13893. if (!this._selectionOctree) {
  13894. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13895. }
  13896. var worldExtends = this.getWorldExtends();
  13897. // Update octree
  13898. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13899. return this._selectionOctree;
  13900. };
  13901. // Picking
  13902. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13903. var engine = this._engine;
  13904. if (!camera) {
  13905. if (!this.activeCamera)
  13906. throw new Error("Active camera not set");
  13907. camera = this.activeCamera;
  13908. }
  13909. var cameraViewport = camera.viewport;
  13910. var viewport = cameraViewport.toGlobal(engine);
  13911. // Moving coordinates to local viewport world
  13912. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13913. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13914. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13915. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13916. };
  13917. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13918. var pickingInfo = null;
  13919. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13920. var mesh = this.meshes[meshIndex];
  13921. if (predicate) {
  13922. if (!predicate(mesh)) {
  13923. continue;
  13924. }
  13925. }
  13926. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13927. continue;
  13928. }
  13929. var world = mesh.getWorldMatrix();
  13930. var ray = rayFunction(world);
  13931. var result = mesh.intersects(ray, fastCheck);
  13932. if (!result || !result.hit)
  13933. continue;
  13934. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13935. continue;
  13936. pickingInfo = result;
  13937. if (fastCheck) {
  13938. break;
  13939. }
  13940. }
  13941. return pickingInfo || new BABYLON.PickingInfo();
  13942. };
  13943. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13944. var _this = this;
  13945. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13946. /// <param name="x">X position on screen</param>
  13947. /// <param name="y">Y position on screen</param>
  13948. /// <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>
  13949. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13950. /// <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>
  13951. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13952. };
  13953. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13954. var _this = this;
  13955. return this._internalPick(function (world) {
  13956. if (!_this._pickWithRayInverseMatrix) {
  13957. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13958. }
  13959. world.invertToRef(_this._pickWithRayInverseMatrix);
  13960. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13961. }, predicate, fastCheck);
  13962. };
  13963. Scene.prototype.setPointerOverMesh = function (mesh) {
  13964. if (this._pointerOverMesh === mesh) {
  13965. return;
  13966. }
  13967. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13968. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13969. }
  13970. this._pointerOverMesh = mesh;
  13971. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13972. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13973. }
  13974. };
  13975. Scene.prototype.getPointerOverMesh = function () {
  13976. return this._pointerOverMesh;
  13977. };
  13978. // Physics
  13979. Scene.prototype.getPhysicsEngine = function () {
  13980. return this._physicsEngine;
  13981. };
  13982. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13983. if (this._physicsEngine) {
  13984. return true;
  13985. }
  13986. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13987. if (!this._physicsEngine.isSupported()) {
  13988. this._physicsEngine = null;
  13989. return false;
  13990. }
  13991. this._physicsEngine._initialize(gravity);
  13992. return true;
  13993. };
  13994. Scene.prototype.disablePhysicsEngine = function () {
  13995. if (!this._physicsEngine) {
  13996. return;
  13997. }
  13998. this._physicsEngine.dispose();
  13999. this._physicsEngine = undefined;
  14000. };
  14001. Scene.prototype.isPhysicsEnabled = function () {
  14002. return this._physicsEngine !== undefined;
  14003. };
  14004. Scene.prototype.setGravity = function (gravity) {
  14005. if (!this._physicsEngine) {
  14006. return;
  14007. }
  14008. this._physicsEngine._setGravity(gravity);
  14009. };
  14010. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14011. if (parts.parts) {
  14012. options = parts;
  14013. parts = parts.parts;
  14014. }
  14015. if (!this._physicsEngine) {
  14016. return null;
  14017. }
  14018. for (var index = 0; index < parts.length; index++) {
  14019. var mesh = parts[index].mesh;
  14020. mesh._physicImpostor = parts[index].impostor;
  14021. mesh._physicsMass = options.mass / parts.length;
  14022. mesh._physicsFriction = options.friction;
  14023. mesh._physicRestitution = options.restitution;
  14024. }
  14025. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14026. };
  14027. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14028. for (var index = 0; index < compound.parts.length; index++) {
  14029. var mesh = compound.parts[index].mesh;
  14030. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14031. this._physicsEngine._unregisterMesh(mesh);
  14032. }
  14033. };
  14034. // Misc.
  14035. Scene.prototype.createDefaultCameraOrLight = function () {
  14036. // Light
  14037. if (this.lights.length === 0) {
  14038. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14039. }
  14040. // Camera
  14041. if (!this.activeCamera) {
  14042. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14043. // Compute position
  14044. var worldExtends = this.getWorldExtends();
  14045. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14046. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14047. camera.setTarget(worldCenter);
  14048. this.activeCamera = camera;
  14049. }
  14050. };
  14051. // Tags
  14052. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14053. if (tagsQuery === undefined) {
  14054. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14055. return list;
  14056. }
  14057. var listByTags = [];
  14058. forEach = forEach || (function (item) { return; });
  14059. for (var i in list) {
  14060. var item = list[i];
  14061. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14062. listByTags.push(item);
  14063. forEach(item);
  14064. }
  14065. }
  14066. return listByTags;
  14067. };
  14068. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14069. return this._getByTags(this.meshes, tagsQuery, forEach);
  14070. };
  14071. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14072. return this._getByTags(this.cameras, tagsQuery, forEach);
  14073. };
  14074. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14075. return this._getByTags(this.lights, tagsQuery, forEach);
  14076. };
  14077. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14078. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14079. };
  14080. // Statics
  14081. Scene._FOGMODE_NONE = 0;
  14082. Scene._FOGMODE_EXP = 1;
  14083. Scene._FOGMODE_EXP2 = 2;
  14084. Scene._FOGMODE_LINEAR = 3;
  14085. Scene.MinDeltaTime = 1.0;
  14086. Scene.MaxDeltaTime = 1000.0;
  14087. return Scene;
  14088. })();
  14089. BABYLON.Scene = Scene;
  14090. })(BABYLON || (BABYLON = {}));
  14091. var BABYLON;
  14092. (function (BABYLON) {
  14093. var VertexBuffer = (function () {
  14094. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14095. if (engine instanceof BABYLON.Mesh) {
  14096. this._engine = engine.getScene().getEngine();
  14097. }
  14098. else {
  14099. this._engine = engine;
  14100. }
  14101. this._updatable = updatable;
  14102. this._data = data;
  14103. if (!postponeInternalCreation) {
  14104. this.create();
  14105. }
  14106. this._kind = kind;
  14107. if (stride) {
  14108. this._strideSize = stride;
  14109. return;
  14110. }
  14111. // Deduce stride from kind
  14112. switch (kind) {
  14113. case VertexBuffer.PositionKind:
  14114. this._strideSize = 3;
  14115. break;
  14116. case VertexBuffer.NormalKind:
  14117. this._strideSize = 3;
  14118. break;
  14119. case VertexBuffer.UVKind:
  14120. case VertexBuffer.UV2Kind:
  14121. case VertexBuffer.UV3Kind:
  14122. case VertexBuffer.UV4Kind:
  14123. case VertexBuffer.UV5Kind:
  14124. case VertexBuffer.UV6Kind:
  14125. this._strideSize = 2;
  14126. break;
  14127. case VertexBuffer.ColorKind:
  14128. this._strideSize = 4;
  14129. break;
  14130. case VertexBuffer.MatricesIndicesKind:
  14131. this._strideSize = 4;
  14132. break;
  14133. case VertexBuffer.MatricesWeightsKind:
  14134. this._strideSize = 4;
  14135. break;
  14136. }
  14137. }
  14138. // Properties
  14139. VertexBuffer.prototype.isUpdatable = function () {
  14140. return this._updatable;
  14141. };
  14142. VertexBuffer.prototype.getData = function () {
  14143. return this._data;
  14144. };
  14145. VertexBuffer.prototype.getBuffer = function () {
  14146. return this._buffer;
  14147. };
  14148. VertexBuffer.prototype.getStrideSize = function () {
  14149. return this._strideSize;
  14150. };
  14151. // Methods
  14152. VertexBuffer.prototype.create = function (data) {
  14153. if (!data && this._buffer) {
  14154. return; // nothing to do
  14155. }
  14156. data = data || this._data;
  14157. if (!this._buffer) {
  14158. if (this._updatable) {
  14159. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14160. }
  14161. else {
  14162. this._buffer = this._engine.createVertexBuffer(data);
  14163. }
  14164. }
  14165. if (this._updatable) {
  14166. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14167. this._data = data;
  14168. }
  14169. };
  14170. VertexBuffer.prototype.update = function (data) {
  14171. this.create(data);
  14172. };
  14173. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14174. if (!this._buffer) {
  14175. return;
  14176. }
  14177. if (this._updatable) {
  14178. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14179. this._data = null;
  14180. }
  14181. };
  14182. VertexBuffer.prototype.dispose = function () {
  14183. if (!this._buffer) {
  14184. return;
  14185. }
  14186. if (this._engine._releaseBuffer(this._buffer)) {
  14187. this._buffer = null;
  14188. }
  14189. };
  14190. Object.defineProperty(VertexBuffer, "PositionKind", {
  14191. get: function () {
  14192. return VertexBuffer._PositionKind;
  14193. },
  14194. enumerable: true,
  14195. configurable: true
  14196. });
  14197. Object.defineProperty(VertexBuffer, "NormalKind", {
  14198. get: function () {
  14199. return VertexBuffer._NormalKind;
  14200. },
  14201. enumerable: true,
  14202. configurable: true
  14203. });
  14204. Object.defineProperty(VertexBuffer, "UVKind", {
  14205. get: function () {
  14206. return VertexBuffer._UVKind;
  14207. },
  14208. enumerable: true,
  14209. configurable: true
  14210. });
  14211. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14212. get: function () {
  14213. return VertexBuffer._UV2Kind;
  14214. },
  14215. enumerable: true,
  14216. configurable: true
  14217. });
  14218. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14219. get: function () {
  14220. return VertexBuffer._UV3Kind;
  14221. },
  14222. enumerable: true,
  14223. configurable: true
  14224. });
  14225. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14226. get: function () {
  14227. return VertexBuffer._UV4Kind;
  14228. },
  14229. enumerable: true,
  14230. configurable: true
  14231. });
  14232. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14233. get: function () {
  14234. return VertexBuffer._UV5Kind;
  14235. },
  14236. enumerable: true,
  14237. configurable: true
  14238. });
  14239. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14240. get: function () {
  14241. return VertexBuffer._UV6Kind;
  14242. },
  14243. enumerable: true,
  14244. configurable: true
  14245. });
  14246. Object.defineProperty(VertexBuffer, "ColorKind", {
  14247. get: function () {
  14248. return VertexBuffer._ColorKind;
  14249. },
  14250. enumerable: true,
  14251. configurable: true
  14252. });
  14253. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14254. get: function () {
  14255. return VertexBuffer._MatricesIndicesKind;
  14256. },
  14257. enumerable: true,
  14258. configurable: true
  14259. });
  14260. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14261. get: function () {
  14262. return VertexBuffer._MatricesWeightsKind;
  14263. },
  14264. enumerable: true,
  14265. configurable: true
  14266. });
  14267. // Enums
  14268. VertexBuffer._PositionKind = "position";
  14269. VertexBuffer._NormalKind = "normal";
  14270. VertexBuffer._UVKind = "uv";
  14271. VertexBuffer._UV2Kind = "uv2";
  14272. VertexBuffer._UV3Kind = "uv3";
  14273. VertexBuffer._UV4Kind = "uv4";
  14274. VertexBuffer._UV5Kind = "uv5";
  14275. VertexBuffer._UV6Kind = "uv6";
  14276. VertexBuffer._ColorKind = "color";
  14277. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14278. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14279. return VertexBuffer;
  14280. })();
  14281. BABYLON.VertexBuffer = VertexBuffer;
  14282. })(BABYLON || (BABYLON = {}));
  14283. var BABYLON;
  14284. (function (BABYLON) {
  14285. /**
  14286. * Creates an instance based on a source mesh.
  14287. */
  14288. var InstancedMesh = (function (_super) {
  14289. __extends(InstancedMesh, _super);
  14290. function InstancedMesh(name, source) {
  14291. _super.call(this, name, source.getScene());
  14292. source.instances.push(this);
  14293. this._sourceMesh = source;
  14294. this.position.copyFrom(source.position);
  14295. this.rotation.copyFrom(source.rotation);
  14296. this.scaling.copyFrom(source.scaling);
  14297. if (source.rotationQuaternion) {
  14298. this.rotationQuaternion = source.rotationQuaternion.clone();
  14299. }
  14300. this.infiniteDistance = source.infiniteDistance;
  14301. this.setPivotMatrix(source.getPivotMatrix());
  14302. this.refreshBoundingInfo();
  14303. this._syncSubMeshes();
  14304. }
  14305. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14306. // Methods
  14307. get: function () {
  14308. return this._sourceMesh.receiveShadows;
  14309. },
  14310. enumerable: true,
  14311. configurable: true
  14312. });
  14313. Object.defineProperty(InstancedMesh.prototype, "material", {
  14314. get: function () {
  14315. return this._sourceMesh.material;
  14316. },
  14317. enumerable: true,
  14318. configurable: true
  14319. });
  14320. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14321. get: function () {
  14322. return this._sourceMesh.visibility;
  14323. },
  14324. enumerable: true,
  14325. configurable: true
  14326. });
  14327. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14328. get: function () {
  14329. return this._sourceMesh.skeleton;
  14330. },
  14331. enumerable: true,
  14332. configurable: true
  14333. });
  14334. InstancedMesh.prototype.getTotalVertices = function () {
  14335. return this._sourceMesh.getTotalVertices();
  14336. };
  14337. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14338. get: function () {
  14339. return this._sourceMesh;
  14340. },
  14341. enumerable: true,
  14342. configurable: true
  14343. });
  14344. InstancedMesh.prototype.getVerticesData = function (kind) {
  14345. return this._sourceMesh.getVerticesData(kind);
  14346. };
  14347. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14348. return this._sourceMesh.isVerticesDataPresent(kind);
  14349. };
  14350. InstancedMesh.prototype.getIndices = function () {
  14351. return this._sourceMesh.getIndices();
  14352. };
  14353. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14354. get: function () {
  14355. return this._sourceMesh._positions;
  14356. },
  14357. enumerable: true,
  14358. configurable: true
  14359. });
  14360. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14361. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14362. if (data) {
  14363. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14364. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14365. }
  14366. this._updateBoundingInfo();
  14367. };
  14368. InstancedMesh.prototype._preActivate = function () {
  14369. if (this._currentLOD) {
  14370. this._currentLOD._preActivate();
  14371. }
  14372. };
  14373. InstancedMesh.prototype._activate = function (renderId) {
  14374. if (this._currentLOD) {
  14375. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14376. }
  14377. };
  14378. InstancedMesh.prototype.getLOD = function (camera) {
  14379. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14380. if (this._currentLOD === this.sourceMesh) {
  14381. return this;
  14382. }
  14383. return this._currentLOD;
  14384. };
  14385. InstancedMesh.prototype._syncSubMeshes = function () {
  14386. this.releaseSubMeshes();
  14387. if (this._sourceMesh.subMeshes) {
  14388. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14389. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14390. }
  14391. }
  14392. };
  14393. InstancedMesh.prototype._generatePointsArray = function () {
  14394. return this._sourceMesh._generatePointsArray();
  14395. };
  14396. // Clone
  14397. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14398. var result = this._sourceMesh.createInstance(name);
  14399. // Deep copy
  14400. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14401. // Bounding info
  14402. this.refreshBoundingInfo();
  14403. // Parent
  14404. if (newParent) {
  14405. result.parent = newParent;
  14406. }
  14407. if (!doNotCloneChildren) {
  14408. // Children
  14409. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14410. var mesh = this.getScene().meshes[index];
  14411. if (mesh.parent === this) {
  14412. mesh.clone(mesh.name, result);
  14413. }
  14414. }
  14415. }
  14416. result.computeWorldMatrix(true);
  14417. return result;
  14418. };
  14419. // Dispoe
  14420. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14421. // Remove from mesh
  14422. var index = this._sourceMesh.instances.indexOf(this);
  14423. this._sourceMesh.instances.splice(index, 1);
  14424. _super.prototype.dispose.call(this, doNotRecurse);
  14425. };
  14426. return InstancedMesh;
  14427. })(BABYLON.AbstractMesh);
  14428. BABYLON.InstancedMesh = InstancedMesh;
  14429. })(BABYLON || (BABYLON = {}));
  14430. var BABYLON;
  14431. (function (BABYLON) {
  14432. var _InstancesBatch = (function () {
  14433. function _InstancesBatch() {
  14434. this.mustReturn = false;
  14435. this.visibleInstances = new Array();
  14436. this.renderSelf = new Array();
  14437. }
  14438. return _InstancesBatch;
  14439. })();
  14440. BABYLON._InstancesBatch = _InstancesBatch;
  14441. var Mesh = (function (_super) {
  14442. __extends(Mesh, _super);
  14443. /**
  14444. * @constructor
  14445. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14446. * @param {Scene} scene - The scene to add this mesh to.
  14447. * @param {Node} parent - The parent of this mesh, if it has one
  14448. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14449. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14450. * When false, achieved by calling a clone(), also passing False.
  14451. * This will make creation of children, recursive.
  14452. */
  14453. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14454. if (parent === void 0) { parent = null; }
  14455. _super.call(this, name, scene);
  14456. // Members
  14457. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14458. this.instances = new Array();
  14459. this._LODLevels = new Array();
  14460. this._onBeforeRenderCallbacks = new Array();
  14461. this._onAfterRenderCallbacks = new Array();
  14462. this._visibleInstances = {};
  14463. this._renderIdForInstances = new Array();
  14464. this._batchCache = new _InstancesBatch();
  14465. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14466. this._sideOrientation = Mesh._DEFAULTSIDE;
  14467. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14468. if (source) {
  14469. // Geometry
  14470. if (source._geometry) {
  14471. source._geometry.applyToMesh(this);
  14472. }
  14473. // Deep copy
  14474. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14475. // Material
  14476. this.material = source.material;
  14477. if (!doNotCloneChildren) {
  14478. // Children
  14479. for (var index = 0; index < scene.meshes.length; index++) {
  14480. var mesh = scene.meshes[index];
  14481. if (mesh.parent === source) {
  14482. // doNotCloneChildren is always going to be False
  14483. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14484. }
  14485. }
  14486. }
  14487. // Particles
  14488. for (index = 0; index < scene.particleSystems.length; index++) {
  14489. var system = scene.particleSystems[index];
  14490. if (system.emitter === source) {
  14491. system.clone(system.name, this);
  14492. }
  14493. }
  14494. this.computeWorldMatrix(true);
  14495. }
  14496. // Parent
  14497. if (parent !== null) {
  14498. this.parent = parent;
  14499. }
  14500. }
  14501. Object.defineProperty(Mesh, "FRONTSIDE", {
  14502. get: function () {
  14503. return Mesh._FRONTSIDE;
  14504. },
  14505. enumerable: true,
  14506. configurable: true
  14507. });
  14508. Object.defineProperty(Mesh, "BACKSIDE", {
  14509. get: function () {
  14510. return Mesh._BACKSIDE;
  14511. },
  14512. enumerable: true,
  14513. configurable: true
  14514. });
  14515. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14516. get: function () {
  14517. return Mesh._DOUBLESIDE;
  14518. },
  14519. enumerable: true,
  14520. configurable: true
  14521. });
  14522. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14523. get: function () {
  14524. return Mesh._DEFAULTSIDE;
  14525. },
  14526. enumerable: true,
  14527. configurable: true
  14528. });
  14529. Object.defineProperty(Mesh, "NO_CAP", {
  14530. get: function () {
  14531. return Mesh._NO_CAP;
  14532. },
  14533. enumerable: true,
  14534. configurable: true
  14535. });
  14536. Object.defineProperty(Mesh, "CAP_START", {
  14537. get: function () {
  14538. return Mesh._CAP_START;
  14539. },
  14540. enumerable: true,
  14541. configurable: true
  14542. });
  14543. Object.defineProperty(Mesh, "CAP_END", {
  14544. get: function () {
  14545. return Mesh._CAP_END;
  14546. },
  14547. enumerable: true,
  14548. configurable: true
  14549. });
  14550. Object.defineProperty(Mesh, "CAP_ALL", {
  14551. get: function () {
  14552. return Mesh._CAP_ALL;
  14553. },
  14554. enumerable: true,
  14555. configurable: true
  14556. });
  14557. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14558. // Methods
  14559. get: function () {
  14560. return this._LODLevels.length > 0;
  14561. },
  14562. enumerable: true,
  14563. configurable: true
  14564. });
  14565. Mesh.prototype._sortLODLevels = function () {
  14566. this._LODLevels.sort(function (a, b) {
  14567. if (a.distance < b.distance) {
  14568. return 1;
  14569. }
  14570. if (a.distance > b.distance) {
  14571. return -1;
  14572. }
  14573. return 0;
  14574. });
  14575. };
  14576. /**
  14577. * Add a mesh as LOD level triggered at the given distance.
  14578. * @param {number} distance - the distance from the center of the object to show this level
  14579. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14580. * @return {BABYLON.Mesh} this mesh (for chaining)
  14581. */
  14582. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14583. if (mesh && mesh._masterMesh) {
  14584. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14585. return this;
  14586. }
  14587. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14588. this._LODLevels.push(level);
  14589. if (mesh) {
  14590. mesh._masterMesh = this;
  14591. }
  14592. this._sortLODLevels();
  14593. return this;
  14594. };
  14595. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14596. for (var index = 0; index < this._LODLevels.length; index++) {
  14597. var level = this._LODLevels[index];
  14598. if (level.distance === distance) {
  14599. return level.mesh;
  14600. }
  14601. }
  14602. return null;
  14603. };
  14604. /**
  14605. * Remove a mesh from the LOD array
  14606. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14607. * @return {BABYLON.Mesh} this mesh (for chaining)
  14608. */
  14609. Mesh.prototype.removeLODLevel = function (mesh) {
  14610. for (var index = 0; index < this._LODLevels.length; index++) {
  14611. if (this._LODLevels[index].mesh === mesh) {
  14612. this._LODLevels.splice(index, 1);
  14613. if (mesh) {
  14614. mesh._masterMesh = null;
  14615. }
  14616. }
  14617. }
  14618. this._sortLODLevels();
  14619. return this;
  14620. };
  14621. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14622. if (!this._LODLevels || this._LODLevels.length === 0) {
  14623. return this;
  14624. }
  14625. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14626. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14627. if (this.onLODLevelSelection) {
  14628. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14629. }
  14630. return this;
  14631. }
  14632. for (var index = 0; index < this._LODLevels.length; index++) {
  14633. var level = this._LODLevels[index];
  14634. if (level.distance < distanceToCamera) {
  14635. if (level.mesh) {
  14636. level.mesh._preActivate();
  14637. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14638. }
  14639. if (this.onLODLevelSelection) {
  14640. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14641. }
  14642. return level.mesh;
  14643. }
  14644. }
  14645. if (this.onLODLevelSelection) {
  14646. this.onLODLevelSelection(distanceToCamera, this, this);
  14647. }
  14648. return this;
  14649. };
  14650. Object.defineProperty(Mesh.prototype, "geometry", {
  14651. get: function () {
  14652. return this._geometry;
  14653. },
  14654. enumerable: true,
  14655. configurable: true
  14656. });
  14657. Mesh.prototype.getTotalVertices = function () {
  14658. if (!this._geometry) {
  14659. return 0;
  14660. }
  14661. return this._geometry.getTotalVertices();
  14662. };
  14663. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14664. if (!this._geometry) {
  14665. return null;
  14666. }
  14667. return this._geometry.getVerticesData(kind, copyWhenShared);
  14668. };
  14669. Mesh.prototype.getVertexBuffer = function (kind) {
  14670. if (!this._geometry) {
  14671. return undefined;
  14672. }
  14673. return this._geometry.getVertexBuffer(kind);
  14674. };
  14675. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14676. if (!this._geometry) {
  14677. if (this._delayInfo) {
  14678. return this._delayInfo.indexOf(kind) !== -1;
  14679. }
  14680. return false;
  14681. }
  14682. return this._geometry.isVerticesDataPresent(kind);
  14683. };
  14684. Mesh.prototype.getVerticesDataKinds = function () {
  14685. if (!this._geometry) {
  14686. var result = [];
  14687. if (this._delayInfo) {
  14688. for (var kind in this._delayInfo) {
  14689. result.push(kind);
  14690. }
  14691. }
  14692. return result;
  14693. }
  14694. return this._geometry.getVerticesDataKinds();
  14695. };
  14696. Mesh.prototype.getTotalIndices = function () {
  14697. if (!this._geometry) {
  14698. return 0;
  14699. }
  14700. return this._geometry.getTotalIndices();
  14701. };
  14702. Mesh.prototype.getIndices = function (copyWhenShared) {
  14703. if (!this._geometry) {
  14704. return [];
  14705. }
  14706. return this._geometry.getIndices(copyWhenShared);
  14707. };
  14708. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14709. get: function () {
  14710. return this._masterMesh !== null && this._masterMesh !== undefined;
  14711. },
  14712. enumerable: true,
  14713. configurable: true
  14714. });
  14715. Mesh.prototype.isReady = function () {
  14716. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14717. return false;
  14718. }
  14719. return _super.prototype.isReady.call(this);
  14720. };
  14721. Mesh.prototype.isDisposed = function () {
  14722. return this._isDisposed;
  14723. };
  14724. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14725. get: function () {
  14726. return this._sideOrientation;
  14727. },
  14728. set: function (sideO) {
  14729. this._sideOrientation = sideO;
  14730. },
  14731. enumerable: true,
  14732. configurable: true
  14733. });
  14734. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14735. get: function () {
  14736. return this._areNormalsFrozen;
  14737. },
  14738. enumerable: true,
  14739. configurable: true
  14740. });
  14741. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14742. Mesh.prototype.freezeNormals = function () {
  14743. this._areNormalsFrozen = true;
  14744. };
  14745. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14746. Mesh.prototype.unfreezeNormals = function () {
  14747. this._areNormalsFrozen = false;
  14748. };
  14749. // Methods
  14750. Mesh.prototype._preActivate = function () {
  14751. var sceneRenderId = this.getScene().getRenderId();
  14752. if (this._preActivateId === sceneRenderId) {
  14753. return;
  14754. }
  14755. this._preActivateId = sceneRenderId;
  14756. this._visibleInstances = null;
  14757. };
  14758. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14759. if (!this._visibleInstances) {
  14760. this._visibleInstances = {};
  14761. this._visibleInstances.defaultRenderId = renderId;
  14762. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14763. }
  14764. if (!this._visibleInstances[renderId]) {
  14765. this._visibleInstances[renderId] = new Array();
  14766. }
  14767. this._visibleInstances[renderId].push(instance);
  14768. };
  14769. Mesh.prototype.refreshBoundingInfo = function () {
  14770. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14771. if (data) {
  14772. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14773. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14774. }
  14775. if (this.subMeshes) {
  14776. for (var index = 0; index < this.subMeshes.length; index++) {
  14777. this.subMeshes[index].refreshBoundingInfo();
  14778. }
  14779. }
  14780. this._updateBoundingInfo();
  14781. };
  14782. Mesh.prototype._createGlobalSubMesh = function () {
  14783. var totalVertices = this.getTotalVertices();
  14784. if (!totalVertices || !this.getIndices()) {
  14785. return null;
  14786. }
  14787. this.releaseSubMeshes();
  14788. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14789. };
  14790. Mesh.prototype.subdivide = function (count) {
  14791. if (count < 1) {
  14792. return;
  14793. }
  14794. var totalIndices = this.getTotalIndices();
  14795. var subdivisionSize = (totalIndices / count) | 0;
  14796. var offset = 0;
  14797. // Ensure that subdivisionSize is a multiple of 3
  14798. while (subdivisionSize % 3 !== 0) {
  14799. subdivisionSize++;
  14800. }
  14801. this.releaseSubMeshes();
  14802. for (var index = 0; index < count; index++) {
  14803. if (offset >= totalIndices) {
  14804. break;
  14805. }
  14806. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14807. offset += subdivisionSize;
  14808. }
  14809. this.synchronizeInstances();
  14810. };
  14811. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14812. if (kind instanceof Array) {
  14813. var temp = data;
  14814. data = kind;
  14815. kind = temp;
  14816. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14817. }
  14818. if (!this._geometry) {
  14819. var vertexData = new BABYLON.VertexData();
  14820. vertexData.set(data, kind);
  14821. var scene = this.getScene();
  14822. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14823. }
  14824. else {
  14825. this._geometry.setVerticesData(kind, data, updatable, stride);
  14826. }
  14827. };
  14828. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14829. if (!this._geometry) {
  14830. return;
  14831. }
  14832. if (!makeItUnique) {
  14833. this._geometry.updateVerticesData(kind, data, updateExtends);
  14834. }
  14835. else {
  14836. this.makeGeometryUnique();
  14837. this.updateVerticesData(kind, data, updateExtends, false);
  14838. }
  14839. };
  14840. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14841. if (!this._geometry) {
  14842. return;
  14843. }
  14844. if (!makeItUnique) {
  14845. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14846. }
  14847. else {
  14848. this.makeGeometryUnique();
  14849. this.updateVerticesDataDirectly(kind, data, offset, false);
  14850. }
  14851. };
  14852. // Mesh positions update function :
  14853. // updates the mesh positions according to the positionFunction returned values.
  14854. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14855. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14856. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14857. if (computeNormals === void 0) { computeNormals = true; }
  14858. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14859. positionFunction(positions);
  14860. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14861. if (computeNormals) {
  14862. var indices = this.getIndices();
  14863. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14864. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14865. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14866. }
  14867. };
  14868. Mesh.prototype.makeGeometryUnique = function () {
  14869. if (!this._geometry) {
  14870. return;
  14871. }
  14872. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14873. geometry.applyToMesh(this);
  14874. };
  14875. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14876. if (!this._geometry) {
  14877. var vertexData = new BABYLON.VertexData();
  14878. vertexData.indices = indices;
  14879. var scene = this.getScene();
  14880. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14881. }
  14882. else {
  14883. this._geometry.setIndices(indices, totalVertices);
  14884. }
  14885. };
  14886. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14887. var engine = this.getScene().getEngine();
  14888. // Wireframe
  14889. var indexToBind;
  14890. switch (fillMode) {
  14891. case BABYLON.Material.PointFillMode:
  14892. indexToBind = null;
  14893. break;
  14894. case BABYLON.Material.WireFrameFillMode:
  14895. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14896. break;
  14897. default:
  14898. case BABYLON.Material.TriangleFillMode:
  14899. indexToBind = this._geometry.getIndexBuffer();
  14900. break;
  14901. }
  14902. // VBOs
  14903. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14904. };
  14905. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14906. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14907. return;
  14908. }
  14909. var engine = this.getScene().getEngine();
  14910. // Draw order
  14911. switch (fillMode) {
  14912. case BABYLON.Material.PointFillMode:
  14913. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14914. break;
  14915. case BABYLON.Material.WireFrameFillMode:
  14916. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14917. break;
  14918. default:
  14919. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14920. }
  14921. };
  14922. Mesh.prototype.registerBeforeRender = function (func) {
  14923. this._onBeforeRenderCallbacks.push(func);
  14924. };
  14925. Mesh.prototype.unregisterBeforeRender = function (func) {
  14926. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14927. if (index > -1) {
  14928. this._onBeforeRenderCallbacks.splice(index, 1);
  14929. }
  14930. };
  14931. Mesh.prototype.registerAfterRender = function (func) {
  14932. this._onAfterRenderCallbacks.push(func);
  14933. };
  14934. Mesh.prototype.unregisterAfterRender = function (func) {
  14935. var index = this._onAfterRenderCallbacks.indexOf(func);
  14936. if (index > -1) {
  14937. this._onAfterRenderCallbacks.splice(index, 1);
  14938. }
  14939. };
  14940. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14941. var scene = this.getScene();
  14942. this._batchCache.mustReturn = false;
  14943. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14944. this._batchCache.visibleInstances[subMeshId] = null;
  14945. if (this._visibleInstances) {
  14946. var currentRenderId = scene.getRenderId();
  14947. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14948. var selfRenderId = this._renderId;
  14949. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14950. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14951. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14952. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14953. }
  14954. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14955. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14956. this._batchCache.mustReturn = true;
  14957. return this._batchCache;
  14958. }
  14959. if (currentRenderId !== selfRenderId) {
  14960. this._batchCache.renderSelf[subMeshId] = false;
  14961. }
  14962. }
  14963. this._renderIdForInstances[subMeshId] = currentRenderId;
  14964. }
  14965. return this._batchCache;
  14966. };
  14967. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14968. var visibleInstances = batch.visibleInstances[subMesh._id];
  14969. var matricesCount = visibleInstances.length + 1;
  14970. var bufferSize = matricesCount * 16 * 4;
  14971. while (this._instancesBufferSize < bufferSize) {
  14972. this._instancesBufferSize *= 2;
  14973. }
  14974. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14975. if (this._worldMatricesInstancesBuffer) {
  14976. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14977. }
  14978. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14979. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14980. }
  14981. var offset = 0;
  14982. var instancesCount = 0;
  14983. var world = this.getWorldMatrix();
  14984. if (batch.renderSelf[subMesh._id]) {
  14985. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14986. offset += 16;
  14987. instancesCount++;
  14988. }
  14989. if (visibleInstances) {
  14990. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14991. var instance = visibleInstances[instanceIndex];
  14992. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14993. offset += 16;
  14994. instancesCount++;
  14995. }
  14996. }
  14997. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14998. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14999. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15000. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15001. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15002. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15003. this._draw(subMesh, fillMode, instancesCount);
  15004. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15005. };
  15006. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15007. var scene = this.getScene();
  15008. var engine = scene.getEngine();
  15009. if (hardwareInstancedRendering) {
  15010. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15011. }
  15012. else {
  15013. if (batch.renderSelf[subMesh._id]) {
  15014. // Draw
  15015. if (onBeforeDraw) {
  15016. onBeforeDraw(false, this.getWorldMatrix());
  15017. }
  15018. this._draw(subMesh, fillMode);
  15019. }
  15020. if (batch.visibleInstances[subMesh._id]) {
  15021. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15022. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15023. // World
  15024. var world = instance.getWorldMatrix();
  15025. if (onBeforeDraw) {
  15026. onBeforeDraw(true, world);
  15027. }
  15028. // Draw
  15029. this._draw(subMesh, fillMode);
  15030. }
  15031. }
  15032. }
  15033. };
  15034. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15035. var scene = this.getScene();
  15036. // Managing instances
  15037. var batch = this._getInstancesRenderList(subMesh._id);
  15038. if (batch.mustReturn) {
  15039. return;
  15040. }
  15041. // Checking geometry state
  15042. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15043. return;
  15044. }
  15045. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15046. this._onBeforeRenderCallbacks[callbackIndex](this);
  15047. }
  15048. var engine = scene.getEngine();
  15049. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15050. // Material
  15051. var effectiveMaterial = subMesh.getMaterial();
  15052. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15053. return;
  15054. }
  15055. // Outline - step 1
  15056. var savedDepthWrite = engine.getDepthWrite();
  15057. if (this.renderOutline) {
  15058. engine.setDepthWrite(false);
  15059. scene.getOutlineRenderer().render(subMesh, batch);
  15060. engine.setDepthWrite(savedDepthWrite);
  15061. }
  15062. effectiveMaterial._preBind();
  15063. var effect = effectiveMaterial.getEffect();
  15064. // Bind
  15065. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15066. this._bind(subMesh, effect, fillMode);
  15067. var world = this.getWorldMatrix();
  15068. effectiveMaterial.bind(world, this);
  15069. // Alpha mode
  15070. if (enableAlphaMode) {
  15071. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15072. }
  15073. // Draw
  15074. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15075. if (isInstance) {
  15076. effectiveMaterial.bindOnlyWorldMatrix(world);
  15077. }
  15078. });
  15079. // Unbind
  15080. effectiveMaterial.unbind();
  15081. // Outline - step 2
  15082. if (this.renderOutline && savedDepthWrite) {
  15083. engine.setDepthWrite(true);
  15084. engine.setColorWrite(false);
  15085. scene.getOutlineRenderer().render(subMesh, batch);
  15086. engine.setColorWrite(true);
  15087. }
  15088. // Overlay
  15089. if (this.renderOverlay) {
  15090. var currentMode = engine.getAlphaMode();
  15091. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15092. scene.getOutlineRenderer().render(subMesh, batch, true);
  15093. engine.setAlphaMode(currentMode);
  15094. }
  15095. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15096. this._onAfterRenderCallbacks[callbackIndex](this);
  15097. }
  15098. };
  15099. Mesh.prototype.getEmittedParticleSystems = function () {
  15100. var results = new Array();
  15101. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15102. var particleSystem = this.getScene().particleSystems[index];
  15103. if (particleSystem.emitter === this) {
  15104. results.push(particleSystem);
  15105. }
  15106. }
  15107. return results;
  15108. };
  15109. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15110. var results = new Array();
  15111. var descendants = this.getDescendants();
  15112. descendants.push(this);
  15113. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15114. var particleSystem = this.getScene().particleSystems[index];
  15115. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15116. results.push(particleSystem);
  15117. }
  15118. }
  15119. return results;
  15120. };
  15121. Mesh.prototype.getChildren = function () {
  15122. var results = [];
  15123. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15124. var mesh = this.getScene().meshes[index];
  15125. if (mesh.parent === this) {
  15126. results.push(mesh);
  15127. }
  15128. }
  15129. return results;
  15130. };
  15131. Mesh.prototype._checkDelayState = function () {
  15132. var _this = this;
  15133. var that = this;
  15134. var scene = this.getScene();
  15135. if (this._geometry) {
  15136. this._geometry.load(scene);
  15137. }
  15138. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15139. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15140. scene._addPendingData(that);
  15141. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15142. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15143. if (data instanceof ArrayBuffer) {
  15144. _this._delayLoadingFunction(data, _this);
  15145. }
  15146. else {
  15147. _this._delayLoadingFunction(JSON.parse(data), _this);
  15148. }
  15149. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15150. scene._removePendingData(_this);
  15151. }, function () { }, scene.database, getBinaryData);
  15152. }
  15153. };
  15154. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15155. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15156. return false;
  15157. }
  15158. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15159. return false;
  15160. }
  15161. this._checkDelayState();
  15162. return true;
  15163. };
  15164. Mesh.prototype.setMaterialByID = function (id) {
  15165. var materials = this.getScene().materials;
  15166. for (var index = 0; index < materials.length; index++) {
  15167. if (materials[index].id === id) {
  15168. this.material = materials[index];
  15169. return;
  15170. }
  15171. }
  15172. // Multi
  15173. var multiMaterials = this.getScene().multiMaterials;
  15174. for (index = 0; index < multiMaterials.length; index++) {
  15175. if (multiMaterials[index].id === id) {
  15176. this.material = multiMaterials[index];
  15177. return;
  15178. }
  15179. }
  15180. };
  15181. Mesh.prototype.getAnimatables = function () {
  15182. var results = [];
  15183. if (this.material) {
  15184. results.push(this.material);
  15185. }
  15186. if (this.skeleton) {
  15187. results.push(this.skeleton);
  15188. }
  15189. return results;
  15190. };
  15191. // Geometry
  15192. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15193. // Position
  15194. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15195. return;
  15196. }
  15197. this._resetPointsArrayCache();
  15198. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15199. var temp = [];
  15200. for (var index = 0; index < data.length; index += 3) {
  15201. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15202. }
  15203. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15204. // Normals
  15205. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15206. return;
  15207. }
  15208. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15209. temp = [];
  15210. for (index = 0; index < data.length; index += 3) {
  15211. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15212. }
  15213. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15214. // flip faces?
  15215. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15216. this.flipFaces();
  15217. }
  15218. };
  15219. // Will apply current transform to mesh and reset world matrix
  15220. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15221. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15222. this.scaling.copyFromFloats(1, 1, 1);
  15223. this.position.copyFromFloats(0, 0, 0);
  15224. this.rotation.copyFromFloats(0, 0, 0);
  15225. //only if quaternion is already set
  15226. if (this.rotationQuaternion) {
  15227. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15228. }
  15229. this._worldMatrix = BABYLON.Matrix.Identity();
  15230. };
  15231. // Cache
  15232. Mesh.prototype._resetPointsArrayCache = function () {
  15233. this._positions = null;
  15234. };
  15235. Mesh.prototype._generatePointsArray = function () {
  15236. if (this._positions)
  15237. return true;
  15238. this._positions = [];
  15239. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15240. if (!data) {
  15241. return false;
  15242. }
  15243. for (var index = 0; index < data.length; index += 3) {
  15244. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15245. }
  15246. return true;
  15247. };
  15248. // Clone
  15249. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15250. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15251. };
  15252. // Dispose
  15253. Mesh.prototype.dispose = function (doNotRecurse) {
  15254. if (this._geometry) {
  15255. this._geometry.releaseForMesh(this, true);
  15256. }
  15257. // Instances
  15258. if (this._worldMatricesInstancesBuffer) {
  15259. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15260. this._worldMatricesInstancesBuffer = null;
  15261. }
  15262. while (this.instances.length) {
  15263. this.instances[0].dispose();
  15264. }
  15265. _super.prototype.dispose.call(this, doNotRecurse);
  15266. };
  15267. // Geometric tools
  15268. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15269. var _this = this;
  15270. var scene = this.getScene();
  15271. var onload = function (img) {
  15272. // Getting height map data
  15273. var canvas = document.createElement("canvas");
  15274. var context = canvas.getContext("2d");
  15275. var heightMapWidth = img.width;
  15276. var heightMapHeight = img.height;
  15277. canvas.width = heightMapWidth;
  15278. canvas.height = heightMapHeight;
  15279. context.drawImage(img, 0, 0);
  15280. // Create VertexData from map data
  15281. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15282. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15283. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15284. //execute success callback, if set
  15285. if (onSuccess) {
  15286. onSuccess(_this);
  15287. }
  15288. };
  15289. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15290. };
  15291. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15292. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15293. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15294. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15295. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15296. return;
  15297. }
  15298. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15299. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15300. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15301. var position = BABYLON.Vector3.Zero();
  15302. var normal = BABYLON.Vector3.Zero();
  15303. var uv = BABYLON.Vector2.Zero();
  15304. for (var index = 0; index < positions.length; index += 3) {
  15305. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15306. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15307. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15308. // Compute height
  15309. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15310. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15311. var pos = (u + v * heightMapWidth) * 4;
  15312. var r = buffer[pos] / 255.0;
  15313. var g = buffer[pos + 1] / 255.0;
  15314. var b = buffer[pos + 2] / 255.0;
  15315. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15316. normal.normalize();
  15317. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15318. position = position.add(normal);
  15319. position.toArray(positions, index);
  15320. }
  15321. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15322. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15323. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15324. };
  15325. Mesh.prototype.convertToFlatShadedMesh = function () {
  15326. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15327. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15328. var kinds = this.getVerticesDataKinds();
  15329. var vbs = [];
  15330. var data = [];
  15331. var newdata = [];
  15332. var updatableNormals = false;
  15333. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15334. var kind = kinds[kindIndex];
  15335. var vertexBuffer = this.getVertexBuffer(kind);
  15336. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15337. updatableNormals = vertexBuffer.isUpdatable();
  15338. kinds.splice(kindIndex, 1);
  15339. kindIndex--;
  15340. continue;
  15341. }
  15342. vbs[kind] = vertexBuffer;
  15343. data[kind] = vbs[kind].getData();
  15344. newdata[kind] = [];
  15345. }
  15346. // Save previous submeshes
  15347. var previousSubmeshes = this.subMeshes.slice(0);
  15348. var indices = this.getIndices();
  15349. var totalIndices = this.getTotalIndices();
  15350. // Generating unique vertices per face
  15351. for (var index = 0; index < totalIndices; index++) {
  15352. var vertexIndex = indices[index];
  15353. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15354. kind = kinds[kindIndex];
  15355. var stride = vbs[kind].getStrideSize();
  15356. for (var offset = 0; offset < stride; offset++) {
  15357. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15358. }
  15359. }
  15360. }
  15361. // Updating faces & normal
  15362. var normals = [];
  15363. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15364. for (index = 0; index < totalIndices; index += 3) {
  15365. indices[index] = index;
  15366. indices[index + 1] = index + 1;
  15367. indices[index + 2] = index + 2;
  15368. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15369. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15370. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15371. var p1p2 = p1.subtract(p2);
  15372. var p3p2 = p3.subtract(p2);
  15373. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15374. // Store same normals for every vertex
  15375. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15376. normals.push(normal.x);
  15377. normals.push(normal.y);
  15378. normals.push(normal.z);
  15379. }
  15380. }
  15381. this.setIndices(indices);
  15382. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15383. // Updating vertex buffers
  15384. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15385. kind = kinds[kindIndex];
  15386. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15387. }
  15388. // Updating submeshes
  15389. this.releaseSubMeshes();
  15390. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15391. var previousOne = previousSubmeshes[submeshIndex];
  15392. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15393. }
  15394. this.synchronizeInstances();
  15395. };
  15396. // will inverse faces orientations, and invert normals too if specified
  15397. Mesh.prototype.flipFaces = function (flipNormals) {
  15398. if (flipNormals === void 0) { flipNormals = false; }
  15399. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15400. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15401. for (var i = 0; i < vertex_data.normals.length; i++) {
  15402. vertex_data.normals[i] *= -1;
  15403. }
  15404. }
  15405. var temp;
  15406. for (var i = 0; i < vertex_data.indices.length; i += 3) {
  15407. // reassign indices
  15408. temp = vertex_data.indices[i + 1];
  15409. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15410. vertex_data.indices[i + 2] = temp;
  15411. }
  15412. vertex_data.applyToMesh(this);
  15413. };
  15414. // Instances
  15415. Mesh.prototype.createInstance = function (name) {
  15416. return new BABYLON.InstancedMesh(name, this);
  15417. };
  15418. Mesh.prototype.synchronizeInstances = function () {
  15419. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15420. var instance = this.instances[instanceIndex];
  15421. instance._syncSubMeshes();
  15422. }
  15423. };
  15424. /**
  15425. * Simplify the mesh according to the given array of settings.
  15426. * Function will return immediately and will simplify async.
  15427. * @param settings a collection of simplification settings.
  15428. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15429. * @param type the type of simplification to run.
  15430. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15431. */
  15432. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15433. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15434. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15435. this.getScene().simplificationQueue.addTask({
  15436. settings: settings,
  15437. parallelProcessing: parallelProcessing,
  15438. mesh: this,
  15439. simplificationType: simplificationType,
  15440. successCallback: successCallback
  15441. });
  15442. };
  15443. /**
  15444. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15445. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15446. * This should be used together with the simplification to avoid disappearing triangles.
  15447. * @param successCallback an optional success callback to be called after the optimization finished.
  15448. */
  15449. Mesh.prototype.optimizeIndices = function (successCallback) {
  15450. var _this = this;
  15451. var indices = this.getIndices();
  15452. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15453. var vectorPositions = [];
  15454. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15455. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15456. }
  15457. var dupes = [];
  15458. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15459. var realPos = vectorPositions.length - 1 - iteration;
  15460. var testedPosition = vectorPositions[realPos];
  15461. for (var j = 0; j < realPos; ++j) {
  15462. var againstPosition = vectorPositions[j];
  15463. if (testedPosition.equals(againstPosition)) {
  15464. dupes[realPos] = j;
  15465. break;
  15466. }
  15467. }
  15468. }, function () {
  15469. for (var i = 0; i < indices.length; ++i) {
  15470. indices[i] = dupes[indices[i]] || indices[i];
  15471. }
  15472. //indices are now reordered
  15473. var originalSubMeshes = _this.subMeshes.slice(0);
  15474. _this.setIndices(indices);
  15475. _this.subMeshes = originalSubMeshes;
  15476. if (successCallback) {
  15477. successCallback(_this);
  15478. }
  15479. });
  15480. };
  15481. // Statics
  15482. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15483. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15484. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15485. if (ribbonInstance) {
  15486. // positionFunction : ribbon case
  15487. // only pathArray and sideOrientation parameters are taken into account for positions update
  15488. var positionFunction = function (positions) {
  15489. var minlg = pathArray[0].length;
  15490. var i = 0;
  15491. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15492. for (var si = 1; si <= ns; si++) {
  15493. for (var p = 0; p < pathArray.length; p++) {
  15494. var path = pathArray[p];
  15495. var l = path.length;
  15496. minlg = (minlg < l) ? minlg : l;
  15497. var j = 0;
  15498. while (j < minlg) {
  15499. positions[i] = path[j].x;
  15500. positions[i + 1] = path[j].y;
  15501. positions[i + 2] = path[j].z;
  15502. j++;
  15503. i += 3;
  15504. }
  15505. if (ribbonInstance._closePath) {
  15506. positions[i] = path[0].x;
  15507. positions[i + 1] = path[0].y;
  15508. positions[i + 2] = path[0].z;
  15509. i += 3;
  15510. }
  15511. }
  15512. }
  15513. };
  15514. var positions = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15515. positionFunction(positions);
  15516. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15517. if (!(ribbonInstance.areNormalsFrozen)) {
  15518. var indices = ribbonInstance.getIndices();
  15519. var normals = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15520. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15521. if (ribbonInstance._closePath) {
  15522. var indexFirst = 0;
  15523. var indexLast = 0;
  15524. for (var p = 0; p < pathArray.length; p++) {
  15525. indexFirst = ribbonInstance._idx[p] * 3;
  15526. if (p + 1 < pathArray.length) {
  15527. indexLast = (ribbonInstance._idx[p + 1] - 1) * 3;
  15528. }
  15529. else {
  15530. indexLast = normals.length - 3;
  15531. }
  15532. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15533. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15534. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15535. normals[indexLast] = normals[indexFirst];
  15536. normals[indexLast + 1] = normals[indexFirst + 1];
  15537. normals[indexLast + 2] = normals[indexFirst + 2];
  15538. }
  15539. }
  15540. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15541. }
  15542. return ribbonInstance;
  15543. }
  15544. else {
  15545. var ribbon = new Mesh(name, scene);
  15546. ribbon.sideOrientation = sideOrientation;
  15547. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15548. if (closePath) {
  15549. ribbon._idx = vertexData._idx;
  15550. }
  15551. ribbon._closePath = closePath;
  15552. vertexData.applyToMesh(ribbon, updatable);
  15553. return ribbon;
  15554. }
  15555. };
  15556. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15557. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15558. var disc = new Mesh(name, scene);
  15559. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15560. vertexData.applyToMesh(disc, updatable);
  15561. return disc;
  15562. };
  15563. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15564. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15565. var box = new Mesh(name, scene);
  15566. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15567. vertexData.applyToMesh(box, updatable);
  15568. return box;
  15569. };
  15570. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15571. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15572. var sphere = new Mesh(name, scene);
  15573. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15574. vertexData.applyToMesh(sphere, updatable);
  15575. return sphere;
  15576. };
  15577. // Cylinder and cone
  15578. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15579. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15580. // subdivisions is a new parameter, we need to support old signature
  15581. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15582. if (scene !== undefined) {
  15583. updatable = scene;
  15584. }
  15585. scene = subdivisions;
  15586. subdivisions = 1;
  15587. }
  15588. var cylinder = new Mesh(name, scene);
  15589. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation);
  15590. vertexData.applyToMesh(cylinder, updatable);
  15591. return cylinder;
  15592. };
  15593. // Torus (Code from SharpDX.org)
  15594. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15595. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15596. var torus = new Mesh(name, scene);
  15597. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15598. vertexData.applyToMesh(torus, updatable);
  15599. return torus;
  15600. };
  15601. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15602. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15603. var torusKnot = new Mesh(name, scene);
  15604. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15605. vertexData.applyToMesh(torusKnot, updatable);
  15606. return torusKnot;
  15607. };
  15608. // Lines
  15609. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15610. if (linesInstance === void 0) { linesInstance = null; }
  15611. if (linesInstance) {
  15612. var positionFunction = function (positions) {
  15613. var i = 0;
  15614. for (var p = 0; p < points.length; p++) {
  15615. positions[i] = points[p].x;
  15616. positions[i + 1] = points[p].y;
  15617. positions[i + 2] = points[p].z;
  15618. i += 3;
  15619. }
  15620. };
  15621. linesInstance.updateMeshPositions(positionFunction, false);
  15622. return linesInstance;
  15623. }
  15624. // lines creation
  15625. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15626. var vertexData = BABYLON.VertexData.CreateLines(points);
  15627. vertexData.applyToMesh(lines, updatable);
  15628. return lines;
  15629. };
  15630. // Dashed Lines
  15631. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15632. if (linesInstance === void 0) { linesInstance = null; }
  15633. if (linesInstance) {
  15634. var positionFunction = function (positions) {
  15635. var curvect = BABYLON.Vector3.Zero();
  15636. var nbSeg = positions.length / 6;
  15637. var lg = 0;
  15638. var nb = 0;
  15639. var shft = 0;
  15640. var dashshft = 0;
  15641. var curshft = 0;
  15642. var p = 0;
  15643. var i = 0;
  15644. var j = 0;
  15645. for (i = 0; i < points.length - 1; i++) {
  15646. points[i + 1].subtractToRef(points[i], curvect);
  15647. lg += curvect.length();
  15648. }
  15649. shft = lg / nbSeg;
  15650. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15651. for (i = 0; i < points.length - 1; i++) {
  15652. points[i + 1].subtractToRef(points[i], curvect);
  15653. nb = Math.floor(curvect.length() / shft);
  15654. curvect.normalize();
  15655. j = 0;
  15656. while (j < nb && p < positions.length) {
  15657. curshft = shft * j;
  15658. positions[p] = points[i].x + curshft * curvect.x;
  15659. positions[p + 1] = points[i].y + curshft * curvect.y;
  15660. positions[p + 2] = points[i].z + curshft * curvect.z;
  15661. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15662. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15663. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15664. p += 6;
  15665. j++;
  15666. }
  15667. }
  15668. while (p < positions.length) {
  15669. positions[p] = points[i].x;
  15670. positions[p + 1] = points[i].y;
  15671. positions[p + 2] = points[i].z;
  15672. p += 3;
  15673. }
  15674. };
  15675. linesInstance.updateMeshPositions(positionFunction, false);
  15676. return linesInstance;
  15677. }
  15678. // dashed lines creation
  15679. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15680. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15681. vertexData.applyToMesh(dashedLines, updatable);
  15682. dashedLines.dashSize = dashSize;
  15683. dashedLines.gapSize = gapSize;
  15684. return dashedLines;
  15685. };
  15686. // Extrusion
  15687. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15688. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15689. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15690. scale = scale || 1;
  15691. rotation = rotation || 0;
  15692. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15693. return extruded;
  15694. };
  15695. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15696. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15697. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15698. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15699. return extrudedCustom;
  15700. };
  15701. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15702. // extrusion geometry
  15703. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15704. var tangents = path3D.getTangents();
  15705. var normals = path3D.getNormals();
  15706. var binormals = path3D.getBinormals();
  15707. var distances = path3D.getDistances();
  15708. var angle = 0;
  15709. var returnScale = function (i, distance) { return scale; };
  15710. var returnRotation = function (i, distance) { return rotation; };
  15711. var rotate = custom ? rotateFunction : returnRotation;
  15712. var scl = custom ? scaleFunction : returnScale;
  15713. var index = 0;
  15714. for (var i = 0; i < curve.length; i++) {
  15715. var shapePath = new Array();
  15716. var angleStep = rotate(i, distances[i]);
  15717. var scaleRatio = scl(i, distances[i]);
  15718. for (var p = 0; p < shape.length; p++) {
  15719. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15720. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15721. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15722. shapePath.push(rotated);
  15723. }
  15724. shapePaths[index] = shapePath;
  15725. angle += angleStep;
  15726. index++;
  15727. }
  15728. // cap
  15729. var capPath = function (shapePath) {
  15730. var pointCap = Array();
  15731. var barycenter = BABYLON.Vector3.Zero();
  15732. var i;
  15733. for (i = 0; i < shapePath.length; i++) {
  15734. barycenter.addInPlace(shapePath[i]);
  15735. }
  15736. barycenter.scaleInPlace(1 / shapePath.length);
  15737. for (i = 0; i < shapePath.length; i++) {
  15738. pointCap.push(barycenter);
  15739. }
  15740. return pointCap;
  15741. };
  15742. switch (cap) {
  15743. case Mesh.NO_CAP:
  15744. break;
  15745. case Mesh.CAP_START:
  15746. shapePaths.unshift(capPath(shapePaths[0]));
  15747. break;
  15748. case Mesh.CAP_END:
  15749. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15750. break;
  15751. case Mesh.CAP_ALL:
  15752. shapePaths.unshift(capPath(shapePaths[0]));
  15753. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15754. break;
  15755. default:
  15756. break;
  15757. }
  15758. return shapePaths;
  15759. };
  15760. var path3D;
  15761. var pathArray;
  15762. if (instance) {
  15763. path3D = (instance.path3D).update(curve);
  15764. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15765. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15766. return instance;
  15767. }
  15768. // extruded shape creation
  15769. path3D = new BABYLON.Path3D(curve);
  15770. var newShapePaths = new Array();
  15771. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15772. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15773. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15774. extrudedGeneric.pathArray = pathArray;
  15775. extrudedGeneric.path3D = path3D;
  15776. extrudedGeneric.cap = cap;
  15777. return extrudedGeneric;
  15778. };
  15779. // Lathe
  15780. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15781. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15782. radius = radius || 1;
  15783. tessellation = tessellation || radius * 60;
  15784. var pi2 = Math.PI * 2;
  15785. var Y = BABYLON.Axis.Y;
  15786. var shapeLathe = new Array();
  15787. // first rotatable point
  15788. var i = 0;
  15789. while (shape[i].x === 0) {
  15790. i++;
  15791. }
  15792. var pt = shape[i];
  15793. for (i = 0; i < shape.length; i++) {
  15794. shapeLathe.push(shape[i].subtract(pt));
  15795. }
  15796. // circle path
  15797. var step = pi2 / tessellation;
  15798. var rotated;
  15799. var path = new Array();
  15800. ;
  15801. for (i = 0; i < tessellation; i++) {
  15802. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15803. path.push(rotated);
  15804. }
  15805. path.push(path[0]);
  15806. // extrusion
  15807. var scaleFunction = function () { return 1; };
  15808. var rotateFunction = function () { return 0; };
  15809. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15810. return lathe;
  15811. };
  15812. // Plane & ground
  15813. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15814. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15815. var plane = new Mesh(name, scene);
  15816. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15817. vertexData.applyToMesh(plane, updatable);
  15818. return plane;
  15819. };
  15820. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15821. var ground = new BABYLON.GroundMesh(name, scene);
  15822. ground._setReady(false);
  15823. ground._subdivisions = subdivisions;
  15824. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15825. vertexData.applyToMesh(ground, updatable);
  15826. ground._setReady(true);
  15827. return ground;
  15828. };
  15829. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15830. var tiledGround = new Mesh(name, scene);
  15831. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15832. vertexData.applyToMesh(tiledGround, updatable);
  15833. return tiledGround;
  15834. };
  15835. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15836. var ground = new BABYLON.GroundMesh(name, scene);
  15837. ground._subdivisions = subdivisions;
  15838. ground._setReady(false);
  15839. var onload = function (img) {
  15840. // Getting height map data
  15841. var canvas = document.createElement("canvas");
  15842. var context = canvas.getContext("2d");
  15843. var heightMapWidth = img.width;
  15844. var heightMapHeight = img.height;
  15845. canvas.width = heightMapWidth;
  15846. canvas.height = heightMapHeight;
  15847. context.drawImage(img, 0, 0);
  15848. // Create VertexData from map data
  15849. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15850. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15851. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15852. vertexData.applyToMesh(ground, updatable);
  15853. ground._setReady(true);
  15854. //execute ready callback, if set
  15855. if (onReady) {
  15856. onReady(ground);
  15857. }
  15858. };
  15859. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15860. return ground;
  15861. };
  15862. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15863. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15864. if (tubeInstance === void 0) { tubeInstance = null; }
  15865. // tube geometry
  15866. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15867. var tangents = path3D.getTangents();
  15868. var normals = path3D.getNormals();
  15869. var distances = path3D.getDistances();
  15870. var pi2 = Math.PI * 2;
  15871. var step = pi2 / tessellation;
  15872. var returnRadius = function (i, distance) { return radius; };
  15873. var radiusFunctionFinal = radiusFunction || returnRadius;
  15874. var circlePath;
  15875. var rad;
  15876. var normal;
  15877. var rotated;
  15878. var rotationMatrix;
  15879. var index = 0;
  15880. for (var i = 0; i < path.length; i++) {
  15881. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15882. circlePath = Array(); // current circle array
  15883. normal = normals[i]; // current normal
  15884. for (var t = 0; t < tessellation; t++) {
  15885. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15886. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15887. circlePath.push(rotated);
  15888. }
  15889. circlePaths[index] = circlePath;
  15890. index++;
  15891. }
  15892. // cap
  15893. var capPath = function (nbPoints, pathIndex) {
  15894. var pointCap = Array();
  15895. for (var i = 0; i < nbPoints; i++) {
  15896. pointCap.push(path[pathIndex]);
  15897. }
  15898. return pointCap;
  15899. };
  15900. switch (cap) {
  15901. case Mesh.NO_CAP:
  15902. break;
  15903. case Mesh.CAP_START:
  15904. circlePaths.unshift(capPath(tessellation + 1, 0));
  15905. break;
  15906. case Mesh.CAP_END:
  15907. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15908. break;
  15909. case Mesh.CAP_ALL:
  15910. circlePaths.unshift(capPath(tessellation + 1, 0));
  15911. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15912. break;
  15913. default:
  15914. break;
  15915. }
  15916. return circlePaths;
  15917. };
  15918. var path3D;
  15919. var pathArray;
  15920. if (tubeInstance) {
  15921. path3D = (tubeInstance.path3D).update(path);
  15922. pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15923. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15924. return tubeInstance;
  15925. }
  15926. // tube creation
  15927. path3D = new BABYLON.Path3D(path);
  15928. var newPathArray = new Array();
  15929. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15930. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15931. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15932. tube.pathArray = pathArray;
  15933. tube.path3D = path3D;
  15934. tube.tessellation = tessellation;
  15935. tube.cap = cap;
  15936. return tube;
  15937. };
  15938. // Decals
  15939. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15940. if (angle === void 0) { angle = 0; }
  15941. var indices = sourceMesh.getIndices();
  15942. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15943. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15944. // Getting correct rotation
  15945. if (!normal) {
  15946. var target = new BABYLON.Vector3(0, 0, 1);
  15947. var camera = sourceMesh.getScene().activeCamera;
  15948. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15949. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15950. }
  15951. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15952. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15953. var pitch = Math.atan2(normal.y, len);
  15954. // Matrix
  15955. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15956. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15957. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15958. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15959. var vertexData = new BABYLON.VertexData();
  15960. vertexData.indices = [];
  15961. vertexData.positions = [];
  15962. vertexData.normals = [];
  15963. vertexData.uvs = [];
  15964. var currentVertexDataIndex = 0;
  15965. var extractDecalVector3 = function (indexId) {
  15966. var vertexId = indices[indexId];
  15967. var result = new BABYLON.PositionNormalVertex();
  15968. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15969. // Send vector to decal local world
  15970. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15971. // Get normal
  15972. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15973. return result;
  15974. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15975. var clip = function (vertices, axis) {
  15976. if (vertices.length === 0) {
  15977. return vertices;
  15978. }
  15979. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15980. var clipVertices = function (v0, v1) {
  15981. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15982. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15983. };
  15984. var result = new Array();
  15985. for (var index = 0; index < vertices.length; index += 3) {
  15986. var v1Out;
  15987. var v2Out;
  15988. var v3Out;
  15989. var total = 0;
  15990. var nV1, nV2, nV3, nV4;
  15991. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15992. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15993. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15994. v1Out = d1 > 0;
  15995. v2Out = d2 > 0;
  15996. v3Out = d3 > 0;
  15997. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15998. switch (total) {
  15999. case 0:
  16000. result.push(vertices[index]);
  16001. result.push(vertices[index + 1]);
  16002. result.push(vertices[index + 2]);
  16003. break;
  16004. case 1:
  16005. if (v1Out) {
  16006. nV1 = vertices[index + 1];
  16007. nV2 = vertices[index + 2];
  16008. nV3 = clipVertices(vertices[index], nV1);
  16009. nV4 = clipVertices(vertices[index], nV2);
  16010. }
  16011. if (v2Out) {
  16012. nV1 = vertices[index];
  16013. nV2 = vertices[index + 2];
  16014. nV3 = clipVertices(vertices[index + 1], nV1);
  16015. nV4 = clipVertices(vertices[index + 1], nV2);
  16016. result.push(nV3);
  16017. result.push(nV2.clone());
  16018. result.push(nV1.clone());
  16019. result.push(nV2.clone());
  16020. result.push(nV3.clone());
  16021. result.push(nV4);
  16022. break;
  16023. }
  16024. if (v3Out) {
  16025. nV1 = vertices[index];
  16026. nV2 = vertices[index + 1];
  16027. nV3 = clipVertices(vertices[index + 2], nV1);
  16028. nV4 = clipVertices(vertices[index + 2], nV2);
  16029. }
  16030. result.push(nV1.clone());
  16031. result.push(nV2.clone());
  16032. result.push(nV3);
  16033. result.push(nV4);
  16034. result.push(nV3.clone());
  16035. result.push(nV2.clone());
  16036. break;
  16037. case 2:
  16038. if (!v1Out) {
  16039. nV1 = vertices[index].clone();
  16040. nV2 = clipVertices(nV1, vertices[index + 1]);
  16041. nV3 = clipVertices(nV1, vertices[index + 2]);
  16042. result.push(nV1);
  16043. result.push(nV2);
  16044. result.push(nV3);
  16045. }
  16046. if (!v2Out) {
  16047. nV1 = vertices[index + 1].clone();
  16048. nV2 = clipVertices(nV1, vertices[index + 2]);
  16049. nV3 = clipVertices(nV1, vertices[index]);
  16050. result.push(nV1);
  16051. result.push(nV2);
  16052. result.push(nV3);
  16053. }
  16054. if (!v3Out) {
  16055. nV1 = vertices[index + 2].clone();
  16056. nV2 = clipVertices(nV1, vertices[index]);
  16057. nV3 = clipVertices(nV1, vertices[index + 1]);
  16058. result.push(nV1);
  16059. result.push(nV2);
  16060. result.push(nV3);
  16061. }
  16062. break;
  16063. case 3:
  16064. break;
  16065. }
  16066. }
  16067. return result;
  16068. };
  16069. for (var index = 0; index < indices.length; index += 3) {
  16070. var faceVertices = new Array();
  16071. faceVertices.push(extractDecalVector3(index));
  16072. faceVertices.push(extractDecalVector3(index + 1));
  16073. faceVertices.push(extractDecalVector3(index + 2));
  16074. // Clip
  16075. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16076. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16077. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16078. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16079. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16080. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16081. if (faceVertices.length === 0) {
  16082. continue;
  16083. }
  16084. // Add UVs and get back to world
  16085. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16086. var vertex = faceVertices[vIndex];
  16087. vertexData.indices.push(currentVertexDataIndex);
  16088. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16089. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16090. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16091. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16092. currentVertexDataIndex++;
  16093. }
  16094. }
  16095. // Return mesh
  16096. var decal = new Mesh(name, sourceMesh.getScene());
  16097. vertexData.applyToMesh(decal);
  16098. decal.position = position.clone();
  16099. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16100. return decal;
  16101. };
  16102. // Skeletons
  16103. /**
  16104. * Update the vertex buffers by applying transformation from the bones
  16105. * @param {skeleton} skeleton to apply
  16106. */
  16107. Mesh.prototype.applySkeleton = function (skeleton) {
  16108. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16109. return this;
  16110. }
  16111. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16112. return this;
  16113. }
  16114. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16115. return this;
  16116. }
  16117. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16118. return this;
  16119. }
  16120. var source;
  16121. if (!this._sourcePositions) {
  16122. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16123. this._sourcePositions = new Float32Array(source);
  16124. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16125. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16126. }
  16127. }
  16128. if (!this._sourceNormals) {
  16129. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16130. this._sourceNormals = new Float32Array(source);
  16131. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16132. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16133. }
  16134. }
  16135. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16136. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16137. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16138. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16139. var skeletonMatrices = skeleton.getTransformMatrices();
  16140. var tempVector3 = BABYLON.Vector3.Zero();
  16141. var finalMatrix = new BABYLON.Matrix();
  16142. var tempMatrix = new BABYLON.Matrix();
  16143. for (var index = 0; index < positionsData.length; index += 3) {
  16144. var index4 = (index / 3) * 4;
  16145. var matricesWeight0 = matricesWeightsData[index4];
  16146. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16147. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16148. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16149. if (matricesWeight0 > 0) {
  16150. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16151. finalMatrix.addToSelf(tempMatrix);
  16152. }
  16153. if (matricesWeight1 > 0) {
  16154. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16155. finalMatrix.addToSelf(tempMatrix);
  16156. }
  16157. if (matricesWeight2 > 0) {
  16158. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16159. finalMatrix.addToSelf(tempMatrix);
  16160. }
  16161. if (matricesWeight3 > 0) {
  16162. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16163. finalMatrix.addToSelf(tempMatrix);
  16164. }
  16165. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16166. tempVector3.toArray(positionsData, index);
  16167. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16168. tempVector3.toArray(normalsData, index);
  16169. finalMatrix.reset();
  16170. }
  16171. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16172. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16173. return this;
  16174. };
  16175. // Tools
  16176. Mesh.MinMax = function (meshes) {
  16177. var minVector = null;
  16178. var maxVector = null;
  16179. for (var i in meshes) {
  16180. var mesh = meshes[i];
  16181. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16182. if (!minVector) {
  16183. minVector = boundingBox.minimumWorld;
  16184. maxVector = boundingBox.maximumWorld;
  16185. continue;
  16186. }
  16187. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16188. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16189. }
  16190. return {
  16191. min: minVector,
  16192. max: maxVector
  16193. };
  16194. };
  16195. Mesh.Center = function (meshesOrMinMaxVector) {
  16196. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16197. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16198. };
  16199. /**
  16200. * Merge the array of meshes into a single mesh for performance reasons.
  16201. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16202. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16203. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16204. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16205. */
  16206. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16207. if (disposeSource === void 0) { disposeSource = true; }
  16208. var index;
  16209. if (!allow32BitsIndices) {
  16210. var totalVertices = 0;
  16211. // Counting vertices
  16212. for (index = 0; index < meshes.length; index++) {
  16213. if (meshes[index]) {
  16214. totalVertices += meshes[index].getTotalVertices();
  16215. if (totalVertices > 65536) {
  16216. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16217. return null;
  16218. }
  16219. }
  16220. }
  16221. }
  16222. // Merge
  16223. var vertexData;
  16224. var otherVertexData;
  16225. var source;
  16226. for (index = 0; index < meshes.length; index++) {
  16227. if (meshes[index]) {
  16228. meshes[index].computeWorldMatrix(true);
  16229. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16230. otherVertexData.transform(meshes[index].getWorldMatrix());
  16231. if (vertexData) {
  16232. vertexData.merge(otherVertexData);
  16233. }
  16234. else {
  16235. vertexData = otherVertexData;
  16236. source = meshes[index];
  16237. }
  16238. }
  16239. }
  16240. if (!meshSubclass) {
  16241. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16242. }
  16243. vertexData.applyToMesh(meshSubclass);
  16244. // Setting properties
  16245. meshSubclass.material = source.material;
  16246. meshSubclass.checkCollisions = source.checkCollisions;
  16247. // Cleaning
  16248. if (disposeSource) {
  16249. for (index = 0; index < meshes.length; index++) {
  16250. if (meshes[index]) {
  16251. meshes[index].dispose();
  16252. }
  16253. }
  16254. }
  16255. return meshSubclass;
  16256. };
  16257. // Consts
  16258. Mesh._FRONTSIDE = 0;
  16259. Mesh._BACKSIDE = 1;
  16260. Mesh._DOUBLESIDE = 2;
  16261. Mesh._DEFAULTSIDE = 0;
  16262. Mesh._NO_CAP = 0;
  16263. Mesh._CAP_START = 1;
  16264. Mesh._CAP_END = 2;
  16265. Mesh._CAP_ALL = 3;
  16266. return Mesh;
  16267. })(BABYLON.AbstractMesh);
  16268. BABYLON.Mesh = Mesh;
  16269. })(BABYLON || (BABYLON = {}));
  16270. var BABYLON;
  16271. (function (BABYLON) {
  16272. var SubMesh = (function () {
  16273. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16274. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16275. this.materialIndex = materialIndex;
  16276. this.verticesStart = verticesStart;
  16277. this.verticesCount = verticesCount;
  16278. this.indexStart = indexStart;
  16279. this.indexCount = indexCount;
  16280. this._renderId = 0;
  16281. this._mesh = mesh;
  16282. this._renderingMesh = renderingMesh || mesh;
  16283. mesh.subMeshes.push(this);
  16284. this._trianglePlanes = [];
  16285. this._id = mesh.subMeshes.length - 1;
  16286. if (createBoundingBox) {
  16287. this.refreshBoundingInfo();
  16288. mesh.computeWorldMatrix(true);
  16289. }
  16290. }
  16291. SubMesh.prototype.getBoundingInfo = function () {
  16292. return this._boundingInfo;
  16293. };
  16294. SubMesh.prototype.getMesh = function () {
  16295. return this._mesh;
  16296. };
  16297. SubMesh.prototype.getRenderingMesh = function () {
  16298. return this._renderingMesh;
  16299. };
  16300. SubMesh.prototype.getMaterial = function () {
  16301. var rootMaterial = this._renderingMesh.material;
  16302. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16303. var multiMaterial = rootMaterial;
  16304. return multiMaterial.getSubMaterial(this.materialIndex);
  16305. }
  16306. if (!rootMaterial) {
  16307. return this._mesh.getScene().defaultMaterial;
  16308. }
  16309. return rootMaterial;
  16310. };
  16311. // Methods
  16312. SubMesh.prototype.refreshBoundingInfo = function () {
  16313. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16314. if (!data) {
  16315. this._boundingInfo = this._mesh._boundingInfo;
  16316. return;
  16317. }
  16318. var indices = this._renderingMesh.getIndices();
  16319. var extend;
  16320. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16321. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16322. }
  16323. else {
  16324. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16325. }
  16326. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16327. };
  16328. SubMesh.prototype._checkCollision = function (collider) {
  16329. return this._boundingInfo._checkCollision(collider);
  16330. };
  16331. SubMesh.prototype.updateBoundingInfo = function (world) {
  16332. if (!this._boundingInfo) {
  16333. this.refreshBoundingInfo();
  16334. }
  16335. this._boundingInfo._update(world);
  16336. };
  16337. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16338. return this._boundingInfo.isInFrustum(frustumPlanes);
  16339. };
  16340. SubMesh.prototype.render = function (enableAlphaMode) {
  16341. this._renderingMesh.render(this, enableAlphaMode);
  16342. };
  16343. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16344. if (!this._linesIndexBuffer) {
  16345. var linesIndices = [];
  16346. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16347. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16348. }
  16349. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16350. this.linesIndexCount = linesIndices.length;
  16351. }
  16352. return this._linesIndexBuffer;
  16353. };
  16354. SubMesh.prototype.canIntersects = function (ray) {
  16355. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16356. };
  16357. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16358. var intersectInfo = null;
  16359. // Triangles test
  16360. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16361. var p0 = positions[indices[index]];
  16362. var p1 = positions[indices[index + 1]];
  16363. var p2 = positions[indices[index + 2]];
  16364. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16365. if (currentIntersectInfo) {
  16366. if (currentIntersectInfo.distance < 0) {
  16367. continue;
  16368. }
  16369. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16370. intersectInfo = currentIntersectInfo;
  16371. intersectInfo.faceId = index / 3;
  16372. if (fastCheck) {
  16373. break;
  16374. }
  16375. }
  16376. }
  16377. }
  16378. return intersectInfo;
  16379. };
  16380. // Clone
  16381. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16382. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16383. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16384. return result;
  16385. };
  16386. // Dispose
  16387. SubMesh.prototype.dispose = function () {
  16388. if (this._linesIndexBuffer) {
  16389. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16390. this._linesIndexBuffer = null;
  16391. }
  16392. // Remove from mesh
  16393. var index = this._mesh.subMeshes.indexOf(this);
  16394. this._mesh.subMeshes.splice(index, 1);
  16395. };
  16396. // Statics
  16397. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16398. var minVertexIndex = Number.MAX_VALUE;
  16399. var maxVertexIndex = -Number.MAX_VALUE;
  16400. renderingMesh = renderingMesh || mesh;
  16401. var indices = renderingMesh.getIndices();
  16402. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16403. var vertexIndex = indices[index];
  16404. if (vertexIndex < minVertexIndex)
  16405. minVertexIndex = vertexIndex;
  16406. if (vertexIndex > maxVertexIndex)
  16407. maxVertexIndex = vertexIndex;
  16408. }
  16409. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16410. };
  16411. return SubMesh;
  16412. })();
  16413. BABYLON.SubMesh = SubMesh;
  16414. })(BABYLON || (BABYLON = {}));
  16415. var BABYLON;
  16416. (function (BABYLON) {
  16417. var BaseTexture = (function () {
  16418. function BaseTexture(scene) {
  16419. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16420. this.hasAlpha = false;
  16421. this.getAlphaFromRGB = false;
  16422. this.level = 1;
  16423. this.isCube = false;
  16424. this.isRenderTarget = false;
  16425. this.animations = new Array();
  16426. this.coordinatesIndex = 0;
  16427. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16428. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16429. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16430. this.anisotropicFilteringLevel = 4;
  16431. this._scene = scene;
  16432. this._scene.textures.push(this);
  16433. }
  16434. BaseTexture.prototype.getScene = function () {
  16435. return this._scene;
  16436. };
  16437. BaseTexture.prototype.getTextureMatrix = function () {
  16438. return null;
  16439. };
  16440. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16441. return null;
  16442. };
  16443. BaseTexture.prototype.getInternalTexture = function () {
  16444. return this._texture;
  16445. };
  16446. BaseTexture.prototype.isReady = function () {
  16447. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16448. return true;
  16449. }
  16450. if (this._texture) {
  16451. return this._texture.isReady;
  16452. }
  16453. return false;
  16454. };
  16455. BaseTexture.prototype.getSize = function () {
  16456. if (this._texture._width) {
  16457. return { width: this._texture._width, height: this._texture._height };
  16458. }
  16459. if (this._texture._size) {
  16460. return { width: this._texture._size, height: this._texture._size };
  16461. }
  16462. return { width: 0, height: 0 };
  16463. };
  16464. BaseTexture.prototype.getBaseSize = function () {
  16465. if (!this.isReady())
  16466. return { width: 0, height: 0 };
  16467. if (this._texture._size) {
  16468. return { width: this._texture._size, height: this._texture._size };
  16469. }
  16470. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16471. };
  16472. BaseTexture.prototype.scale = function (ratio) {
  16473. };
  16474. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16475. get: function () {
  16476. return false;
  16477. },
  16478. enumerable: true,
  16479. configurable: true
  16480. });
  16481. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16482. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16483. for (var index = 0; index < texturesCache.length; index++) {
  16484. var texturesCacheEntry = texturesCache[index];
  16485. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16486. texturesCache.splice(index, 1);
  16487. return;
  16488. }
  16489. }
  16490. };
  16491. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16492. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16493. for (var index = 0; index < texturesCache.length; index++) {
  16494. var texturesCacheEntry = texturesCache[index];
  16495. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16496. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16497. texturesCacheEntry.references++;
  16498. return texturesCacheEntry;
  16499. }
  16500. }
  16501. }
  16502. return null;
  16503. };
  16504. BaseTexture.prototype.delayLoad = function () {
  16505. };
  16506. BaseTexture.prototype.releaseInternalTexture = function () {
  16507. if (!this._texture) {
  16508. return;
  16509. }
  16510. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16511. this._texture.references--;
  16512. // Final reference ?
  16513. if (this._texture.references === 0) {
  16514. var index = texturesCache.indexOf(this._texture);
  16515. texturesCache.splice(index, 1);
  16516. this._scene.getEngine()._releaseTexture(this._texture);
  16517. delete this._texture;
  16518. }
  16519. };
  16520. BaseTexture.prototype.clone = function () {
  16521. return null;
  16522. };
  16523. BaseTexture.prototype.dispose = function () {
  16524. // Remove from scene
  16525. var index = this._scene.textures.indexOf(this);
  16526. if (index >= 0) {
  16527. this._scene.textures.splice(index, 1);
  16528. }
  16529. if (this._texture === undefined) {
  16530. return;
  16531. }
  16532. this.releaseInternalTexture();
  16533. // Callback
  16534. if (this.onDispose) {
  16535. this.onDispose();
  16536. }
  16537. };
  16538. return BaseTexture;
  16539. })();
  16540. BABYLON.BaseTexture = BaseTexture;
  16541. })(BABYLON || (BABYLON = {}));
  16542. var BABYLON;
  16543. (function (BABYLON) {
  16544. var Texture = (function (_super) {
  16545. __extends(Texture, _super);
  16546. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16547. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16548. if (onLoad === void 0) { onLoad = null; }
  16549. if (onError === void 0) { onError = null; }
  16550. if (buffer === void 0) { buffer = null; }
  16551. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16552. _super.call(this, scene);
  16553. this.uOffset = 0;
  16554. this.vOffset = 0;
  16555. this.uScale = 1.0;
  16556. this.vScale = 1.0;
  16557. this.uAng = 0;
  16558. this.vAng = 0;
  16559. this.wAng = 0;
  16560. this.name = url;
  16561. this.url = url;
  16562. this._noMipmap = noMipmap;
  16563. this._invertY = invertY;
  16564. this._samplingMode = samplingMode;
  16565. this._buffer = buffer;
  16566. this._deleteBuffer = deleteBuffer;
  16567. if (!url) {
  16568. return;
  16569. }
  16570. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16571. if (!this._texture) {
  16572. if (!scene.useDelayedTextureLoading) {
  16573. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16574. if (deleteBuffer) {
  16575. delete this._buffer;
  16576. }
  16577. }
  16578. else {
  16579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16580. }
  16581. }
  16582. else {
  16583. BABYLON.Tools.SetImmediate(function () {
  16584. if (onLoad) {
  16585. onLoad();
  16586. }
  16587. });
  16588. }
  16589. }
  16590. Texture.prototype.delayLoad = function () {
  16591. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16592. return;
  16593. }
  16594. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16595. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16596. if (!this._texture) {
  16597. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16598. if (this._deleteBuffer) {
  16599. delete this._buffer;
  16600. }
  16601. }
  16602. };
  16603. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16604. if (!this._texture) {
  16605. return;
  16606. }
  16607. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16608. };
  16609. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16610. x -= this.uOffset + 0.5;
  16611. y -= this.vOffset + 0.5;
  16612. z -= 0.5;
  16613. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16614. t.x *= this.uScale;
  16615. t.y *= this.vScale;
  16616. t.x += 0.5;
  16617. t.y += 0.5;
  16618. t.z += 0.5;
  16619. };
  16620. Texture.prototype.getTextureMatrix = function () {
  16621. if (this.uOffset === this._cachedUOffset &&
  16622. this.vOffset === this._cachedVOffset &&
  16623. this.uScale === this._cachedUScale &&
  16624. this.vScale === this._cachedVScale &&
  16625. this.uAng === this._cachedUAng &&
  16626. this.vAng === this._cachedVAng &&
  16627. this.wAng === this._cachedWAng) {
  16628. return this._cachedTextureMatrix;
  16629. }
  16630. this._cachedUOffset = this.uOffset;
  16631. this._cachedVOffset = this.vOffset;
  16632. this._cachedUScale = this.uScale;
  16633. this._cachedVScale = this.vScale;
  16634. this._cachedUAng = this.uAng;
  16635. this._cachedVAng = this.vAng;
  16636. this._cachedWAng = this.wAng;
  16637. if (!this._cachedTextureMatrix) {
  16638. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16639. this._rowGenerationMatrix = new BABYLON.Matrix();
  16640. this._t0 = BABYLON.Vector3.Zero();
  16641. this._t1 = BABYLON.Vector3.Zero();
  16642. this._t2 = BABYLON.Vector3.Zero();
  16643. }
  16644. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16645. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16646. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16647. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16648. this._t1.subtractInPlace(this._t0);
  16649. this._t2.subtractInPlace(this._t0);
  16650. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16651. this._cachedTextureMatrix.m[0] = this._t1.x;
  16652. this._cachedTextureMatrix.m[1] = this._t1.y;
  16653. this._cachedTextureMatrix.m[2] = this._t1.z;
  16654. this._cachedTextureMatrix.m[4] = this._t2.x;
  16655. this._cachedTextureMatrix.m[5] = this._t2.y;
  16656. this._cachedTextureMatrix.m[6] = this._t2.z;
  16657. this._cachedTextureMatrix.m[8] = this._t0.x;
  16658. this._cachedTextureMatrix.m[9] = this._t0.y;
  16659. this._cachedTextureMatrix.m[10] = this._t0.z;
  16660. return this._cachedTextureMatrix;
  16661. };
  16662. Texture.prototype.getReflectionTextureMatrix = function () {
  16663. if (this.uOffset === this._cachedUOffset &&
  16664. this.vOffset === this._cachedVOffset &&
  16665. this.uScale === this._cachedUScale &&
  16666. this.vScale === this._cachedVScale &&
  16667. this.coordinatesMode === this._cachedCoordinatesMode) {
  16668. return this._cachedTextureMatrix;
  16669. }
  16670. if (!this._cachedTextureMatrix) {
  16671. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16672. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16673. }
  16674. this._cachedCoordinatesMode = this.coordinatesMode;
  16675. switch (this.coordinatesMode) {
  16676. case Texture.SPHERICAL_MODE:
  16677. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16678. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16679. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16680. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16681. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16682. break;
  16683. case Texture.PLANAR_MODE:
  16684. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16685. this._cachedTextureMatrix[0] = this.uScale;
  16686. this._cachedTextureMatrix[5] = this.vScale;
  16687. this._cachedTextureMatrix[12] = this.uOffset;
  16688. this._cachedTextureMatrix[13] = this.vOffset;
  16689. break;
  16690. case Texture.PROJECTION_MODE:
  16691. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16692. this._projectionModeMatrix.m[0] = 0.5;
  16693. this._projectionModeMatrix.m[5] = -0.5;
  16694. this._projectionModeMatrix.m[10] = 0.0;
  16695. this._projectionModeMatrix.m[12] = 0.5;
  16696. this._projectionModeMatrix.m[13] = 0.5;
  16697. this._projectionModeMatrix.m[14] = 1.0;
  16698. this._projectionModeMatrix.m[15] = 1.0;
  16699. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16700. break;
  16701. default:
  16702. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16703. break;
  16704. }
  16705. return this._cachedTextureMatrix;
  16706. };
  16707. Texture.prototype.clone = function () {
  16708. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16709. // Base texture
  16710. newTexture.hasAlpha = this.hasAlpha;
  16711. newTexture.level = this.level;
  16712. newTexture.wrapU = this.wrapU;
  16713. newTexture.wrapV = this.wrapV;
  16714. newTexture.coordinatesIndex = this.coordinatesIndex;
  16715. newTexture.coordinatesMode = this.coordinatesMode;
  16716. // Texture
  16717. newTexture.uOffset = this.uOffset;
  16718. newTexture.vOffset = this.vOffset;
  16719. newTexture.uScale = this.uScale;
  16720. newTexture.vScale = this.vScale;
  16721. newTexture.uAng = this.uAng;
  16722. newTexture.vAng = this.vAng;
  16723. newTexture.wAng = this.wAng;
  16724. return newTexture;
  16725. };
  16726. // Statics
  16727. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16728. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16729. if (onLoad === void 0) { onLoad = null; }
  16730. if (onError === void 0) { onError = null; }
  16731. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16732. };
  16733. // Constants
  16734. Texture.NEAREST_SAMPLINGMODE = 1;
  16735. Texture.BILINEAR_SAMPLINGMODE = 2;
  16736. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16737. Texture.EXPLICIT_MODE = 0;
  16738. Texture.SPHERICAL_MODE = 1;
  16739. Texture.PLANAR_MODE = 2;
  16740. Texture.CUBIC_MODE = 3;
  16741. Texture.PROJECTION_MODE = 4;
  16742. Texture.SKYBOX_MODE = 5;
  16743. Texture.CLAMP_ADDRESSMODE = 0;
  16744. Texture.WRAP_ADDRESSMODE = 1;
  16745. Texture.MIRROR_ADDRESSMODE = 2;
  16746. return Texture;
  16747. })(BABYLON.BaseTexture);
  16748. BABYLON.Texture = Texture;
  16749. })(BABYLON || (BABYLON = {}));
  16750. var BABYLON;
  16751. (function (BABYLON) {
  16752. var CubeTexture = (function (_super) {
  16753. __extends(CubeTexture, _super);
  16754. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16755. _super.call(this, scene);
  16756. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16757. this.name = rootUrl;
  16758. this.url = rootUrl;
  16759. this._noMipmap = noMipmap;
  16760. this.hasAlpha = false;
  16761. this._texture = this._getFromCache(rootUrl, noMipmap);
  16762. if (!extensions) {
  16763. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16764. }
  16765. this._extensions = extensions;
  16766. if (!this._texture) {
  16767. if (!scene.useDelayedTextureLoading) {
  16768. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16769. }
  16770. else {
  16771. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16772. }
  16773. }
  16774. this.isCube = true;
  16775. this._textureMatrix = BABYLON.Matrix.Identity();
  16776. }
  16777. CubeTexture.prototype.clone = function () {
  16778. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16779. // Base texture
  16780. newTexture.level = this.level;
  16781. newTexture.wrapU = this.wrapU;
  16782. newTexture.wrapV = this.wrapV;
  16783. newTexture.coordinatesIndex = this.coordinatesIndex;
  16784. newTexture.coordinatesMode = this.coordinatesMode;
  16785. return newTexture;
  16786. };
  16787. // Methods
  16788. CubeTexture.prototype.delayLoad = function () {
  16789. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16790. return;
  16791. }
  16792. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16793. this._texture = this._getFromCache(this.url, this._noMipmap);
  16794. if (!this._texture) {
  16795. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16796. }
  16797. };
  16798. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16799. return this._textureMatrix;
  16800. };
  16801. return CubeTexture;
  16802. })(BABYLON.BaseTexture);
  16803. BABYLON.CubeTexture = CubeTexture;
  16804. })(BABYLON || (BABYLON = {}));
  16805. var BABYLON;
  16806. (function (BABYLON) {
  16807. var RenderTargetTexture = (function (_super) {
  16808. __extends(RenderTargetTexture, _super);
  16809. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16810. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16811. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16812. _super.call(this, null, scene, !generateMipMaps);
  16813. this.renderList = new Array();
  16814. this.renderParticles = true;
  16815. this.renderSprites = false;
  16816. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16817. this._currentRefreshId = -1;
  16818. this._refreshRate = 1;
  16819. this.name = name;
  16820. this.isRenderTarget = true;
  16821. this._size = size;
  16822. this._generateMipMaps = generateMipMaps;
  16823. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16824. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16825. // Rendering groups
  16826. this._renderingManager = new BABYLON.RenderingManager(scene);
  16827. }
  16828. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16829. this._currentRefreshId = -1;
  16830. };
  16831. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16832. get: function () {
  16833. return this._refreshRate;
  16834. },
  16835. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16836. set: function (value) {
  16837. this._refreshRate = value;
  16838. this.resetRefreshCounter();
  16839. },
  16840. enumerable: true,
  16841. configurable: true
  16842. });
  16843. RenderTargetTexture.prototype._shouldRender = function () {
  16844. if (this._currentRefreshId === -1) {
  16845. this._currentRefreshId = 1;
  16846. return true;
  16847. }
  16848. if (this.refreshRate === this._currentRefreshId) {
  16849. this._currentRefreshId = 1;
  16850. return true;
  16851. }
  16852. this._currentRefreshId++;
  16853. return false;
  16854. };
  16855. RenderTargetTexture.prototype.isReady = function () {
  16856. if (!this.getScene().renderTargetsEnabled) {
  16857. return false;
  16858. }
  16859. return _super.prototype.isReady.call(this);
  16860. };
  16861. RenderTargetTexture.prototype.getRenderSize = function () {
  16862. return this._size;
  16863. };
  16864. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16865. get: function () {
  16866. return true;
  16867. },
  16868. enumerable: true,
  16869. configurable: true
  16870. });
  16871. RenderTargetTexture.prototype.scale = function (ratio) {
  16872. var newSize = this._size * ratio;
  16873. this.resize(newSize, this._generateMipMaps);
  16874. };
  16875. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16876. this.releaseInternalTexture();
  16877. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16878. };
  16879. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16880. var scene = this.getScene();
  16881. var engine = scene.getEngine();
  16882. if (this._waitingRenderList) {
  16883. this.renderList = [];
  16884. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16885. var id = this._waitingRenderList[index];
  16886. this.renderList.push(scene.getMeshByID(id));
  16887. }
  16888. delete this._waitingRenderList;
  16889. }
  16890. if (this.renderList && this.renderList.length === 0) {
  16891. return;
  16892. }
  16893. // Bind
  16894. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16895. engine.bindFramebuffer(this._texture);
  16896. }
  16897. this._renderingManager.reset();
  16898. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16899. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16900. var mesh = currentRenderList[meshIndex];
  16901. if (mesh) {
  16902. if (!mesh.isReady()) {
  16903. // Reset _currentRefreshId
  16904. this.resetRefreshCounter();
  16905. continue;
  16906. }
  16907. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16908. mesh._activate(scene.getRenderId());
  16909. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16910. var subMesh = mesh.subMeshes[subIndex];
  16911. scene._activeIndices += subMesh.indexCount;
  16912. this._renderingManager.dispatch(subMesh);
  16913. }
  16914. }
  16915. }
  16916. }
  16917. if (this.onBeforeRender) {
  16918. this.onBeforeRender();
  16919. }
  16920. // Clear
  16921. if (this.onClear) {
  16922. this.onClear(engine);
  16923. }
  16924. else {
  16925. engine.clear(scene.clearColor, true, true);
  16926. }
  16927. if (!this._doNotChangeAspectRatio) {
  16928. scene.updateTransformMatrix(true);
  16929. }
  16930. // Render
  16931. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16932. if (useCameraPostProcess) {
  16933. scene.postProcessManager._finalizeFrame(false, this._texture);
  16934. }
  16935. if (!this._doNotChangeAspectRatio) {
  16936. scene.updateTransformMatrix(true);
  16937. }
  16938. if (this.onAfterRender) {
  16939. this.onAfterRender();
  16940. }
  16941. // Dump ?
  16942. if (dumpForDebug) {
  16943. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16944. }
  16945. // Unbind
  16946. engine.unBindFramebuffer(this._texture);
  16947. if (this.onAfterUnbind) {
  16948. this.onAfterUnbind();
  16949. }
  16950. };
  16951. RenderTargetTexture.prototype.clone = function () {
  16952. var textureSize = this.getSize();
  16953. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16954. // Base texture
  16955. newTexture.hasAlpha = this.hasAlpha;
  16956. newTexture.level = this.level;
  16957. // RenderTarget Texture
  16958. newTexture.coordinatesMode = this.coordinatesMode;
  16959. newTexture.renderList = this.renderList.slice(0);
  16960. return newTexture;
  16961. };
  16962. return RenderTargetTexture;
  16963. })(BABYLON.Texture);
  16964. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16965. })(BABYLON || (BABYLON = {}));
  16966. var BABYLON;
  16967. (function (BABYLON) {
  16968. var ProceduralTexture = (function (_super) {
  16969. __extends(ProceduralTexture, _super);
  16970. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16971. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16972. _super.call(this, null, scene, !generateMipMaps);
  16973. this._currentRefreshId = -1;
  16974. this._refreshRate = 1;
  16975. this._vertexDeclaration = [2];
  16976. this._vertexStrideSize = 2 * 4;
  16977. this._uniforms = new Array();
  16978. this._samplers = new Array();
  16979. this._textures = new Array();
  16980. this._floats = new Array();
  16981. this._floatsArrays = {};
  16982. this._colors3 = new Array();
  16983. this._colors4 = new Array();
  16984. this._vectors2 = new Array();
  16985. this._vectors3 = new Array();
  16986. this._matrices = new Array();
  16987. this._fallbackTextureUsed = false;
  16988. scene._proceduralTextures.push(this);
  16989. this.name = name;
  16990. this.isRenderTarget = true;
  16991. this._size = size;
  16992. this._generateMipMaps = generateMipMaps;
  16993. this.setFragment(fragment);
  16994. this._fallbackTexture = fallbackTexture;
  16995. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16996. // VBO
  16997. var vertices = [];
  16998. vertices.push(1, 1);
  16999. vertices.push(-1, 1);
  17000. vertices.push(-1, -1);
  17001. vertices.push(1, -1);
  17002. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17003. // Indices
  17004. var indices = [];
  17005. indices.push(0);
  17006. indices.push(1);
  17007. indices.push(2);
  17008. indices.push(0);
  17009. indices.push(2);
  17010. indices.push(3);
  17011. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17012. }
  17013. ProceduralTexture.prototype.reset = function () {
  17014. if (this._effect === undefined) {
  17015. return;
  17016. }
  17017. var engine = this.getScene().getEngine();
  17018. engine._releaseEffect(this._effect);
  17019. };
  17020. ProceduralTexture.prototype.isReady = function () {
  17021. var _this = this;
  17022. var engine = this.getScene().getEngine();
  17023. var shaders;
  17024. if (!this._fragment) {
  17025. return false;
  17026. }
  17027. if (this._fallbackTextureUsed) {
  17028. return true;
  17029. }
  17030. if (this._fragment.fragmentElement !== undefined) {
  17031. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17032. }
  17033. else {
  17034. shaders = { vertex: "procedural", fragment: this._fragment };
  17035. }
  17036. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17037. _this.releaseInternalTexture();
  17038. if (_this._fallbackTexture) {
  17039. _this._texture = _this._fallbackTexture._texture;
  17040. _this._texture.references++;
  17041. }
  17042. _this._fallbackTextureUsed = true;
  17043. });
  17044. return this._effect.isReady();
  17045. };
  17046. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17047. this._currentRefreshId = -1;
  17048. };
  17049. ProceduralTexture.prototype.setFragment = function (fragment) {
  17050. this._fragment = fragment;
  17051. };
  17052. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17053. get: function () {
  17054. return this._refreshRate;
  17055. },
  17056. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17057. set: function (value) {
  17058. this._refreshRate = value;
  17059. this.resetRefreshCounter();
  17060. },
  17061. enumerable: true,
  17062. configurable: true
  17063. });
  17064. ProceduralTexture.prototype._shouldRender = function () {
  17065. if (!this.isReady() || !this._texture) {
  17066. return false;
  17067. }
  17068. if (this._fallbackTextureUsed) {
  17069. return false;
  17070. }
  17071. if (this._currentRefreshId === -1) {
  17072. this._currentRefreshId = 1;
  17073. return true;
  17074. }
  17075. if (this.refreshRate === this._currentRefreshId) {
  17076. this._currentRefreshId = 1;
  17077. return true;
  17078. }
  17079. this._currentRefreshId++;
  17080. return false;
  17081. };
  17082. ProceduralTexture.prototype.getRenderSize = function () {
  17083. return this._size;
  17084. };
  17085. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17086. if (this._fallbackTextureUsed) {
  17087. return;
  17088. }
  17089. this.releaseInternalTexture();
  17090. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17091. };
  17092. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17093. if (this._uniforms.indexOf(uniformName) === -1) {
  17094. this._uniforms.push(uniformName);
  17095. }
  17096. };
  17097. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17098. if (this._samplers.indexOf(name) === -1) {
  17099. this._samplers.push(name);
  17100. }
  17101. this._textures[name] = texture;
  17102. return this;
  17103. };
  17104. ProceduralTexture.prototype.setFloat = function (name, value) {
  17105. this._checkUniform(name);
  17106. this._floats[name] = value;
  17107. return this;
  17108. };
  17109. ProceduralTexture.prototype.setFloats = function (name, value) {
  17110. this._checkUniform(name);
  17111. this._floatsArrays[name] = value;
  17112. return this;
  17113. };
  17114. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17115. this._checkUniform(name);
  17116. this._colors3[name] = value;
  17117. return this;
  17118. };
  17119. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17120. this._checkUniform(name);
  17121. this._colors4[name] = value;
  17122. return this;
  17123. };
  17124. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17125. this._checkUniform(name);
  17126. this._vectors2[name] = value;
  17127. return this;
  17128. };
  17129. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17130. this._checkUniform(name);
  17131. this._vectors3[name] = value;
  17132. return this;
  17133. };
  17134. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17135. this._checkUniform(name);
  17136. this._matrices[name] = value;
  17137. return this;
  17138. };
  17139. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17140. var scene = this.getScene();
  17141. var engine = scene.getEngine();
  17142. engine.bindFramebuffer(this._texture);
  17143. // Clear
  17144. engine.clear(scene.clearColor, true, true);
  17145. // Render
  17146. engine.enableEffect(this._effect);
  17147. engine.setState(false);
  17148. // Texture
  17149. for (var name in this._textures) {
  17150. this._effect.setTexture(name, this._textures[name]);
  17151. }
  17152. // Float
  17153. for (name in this._floats) {
  17154. this._effect.setFloat(name, this._floats[name]);
  17155. }
  17156. // Floats
  17157. for (name in this._floatsArrays) {
  17158. this._effect.setArray(name, this._floatsArrays[name]);
  17159. }
  17160. // Color3
  17161. for (name in this._colors3) {
  17162. this._effect.setColor3(name, this._colors3[name]);
  17163. }
  17164. // Color4
  17165. for (name in this._colors4) {
  17166. var color = this._colors4[name];
  17167. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17168. }
  17169. // Vector2
  17170. for (name in this._vectors2) {
  17171. this._effect.setVector2(name, this._vectors2[name]);
  17172. }
  17173. // Vector3
  17174. for (name in this._vectors3) {
  17175. this._effect.setVector3(name, this._vectors3[name]);
  17176. }
  17177. // Matrix
  17178. for (name in this._matrices) {
  17179. this._effect.setMatrix(name, this._matrices[name]);
  17180. }
  17181. // VBOs
  17182. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17183. // Draw order
  17184. engine.draw(true, 0, 6);
  17185. // Unbind
  17186. engine.unBindFramebuffer(this._texture);
  17187. };
  17188. ProceduralTexture.prototype.clone = function () {
  17189. var textureSize = this.getSize();
  17190. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17191. // Base texture
  17192. newTexture.hasAlpha = this.hasAlpha;
  17193. newTexture.level = this.level;
  17194. // RenderTarget Texture
  17195. newTexture.coordinatesMode = this.coordinatesMode;
  17196. return newTexture;
  17197. };
  17198. ProceduralTexture.prototype.dispose = function () {
  17199. var index = this.getScene()._proceduralTextures.indexOf(this);
  17200. if (index >= 0) {
  17201. this.getScene()._proceduralTextures.splice(index, 1);
  17202. }
  17203. _super.prototype.dispose.call(this);
  17204. };
  17205. return ProceduralTexture;
  17206. })(BABYLON.Texture);
  17207. BABYLON.ProceduralTexture = ProceduralTexture;
  17208. })(BABYLON || (BABYLON = {}));
  17209. var BABYLON;
  17210. (function (BABYLON) {
  17211. var MirrorTexture = (function (_super) {
  17212. __extends(MirrorTexture, _super);
  17213. function MirrorTexture(name, size, scene, generateMipMaps) {
  17214. var _this = this;
  17215. _super.call(this, name, size, scene, generateMipMaps, true);
  17216. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17217. this._transformMatrix = BABYLON.Matrix.Zero();
  17218. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17219. this.onBeforeRender = function () {
  17220. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17221. _this._savedViewMatrix = scene.getViewMatrix();
  17222. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17223. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17224. scene.clipPlane = _this.mirrorPlane;
  17225. scene.getEngine().cullBackFaces = false;
  17226. };
  17227. this.onAfterRender = function () {
  17228. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17229. scene.getEngine().cullBackFaces = true;
  17230. delete scene.clipPlane;
  17231. };
  17232. }
  17233. MirrorTexture.prototype.clone = function () {
  17234. var textureSize = this.getSize();
  17235. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17236. // Base texture
  17237. newTexture.hasAlpha = this.hasAlpha;
  17238. newTexture.level = this.level;
  17239. // Mirror Texture
  17240. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17241. newTexture.renderList = this.renderList.slice(0);
  17242. return newTexture;
  17243. };
  17244. return MirrorTexture;
  17245. })(BABYLON.RenderTargetTexture);
  17246. BABYLON.MirrorTexture = MirrorTexture;
  17247. })(BABYLON || (BABYLON = {}));
  17248. var BABYLON;
  17249. (function (BABYLON) {
  17250. var DynamicTexture = (function (_super) {
  17251. __extends(DynamicTexture, _super);
  17252. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17253. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17254. _super.call(this, null, scene, !generateMipMaps);
  17255. this.name = name;
  17256. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17257. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17258. this._generateMipMaps = generateMipMaps;
  17259. if (options.getContext) {
  17260. this._canvas = options;
  17261. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17262. }
  17263. else {
  17264. this._canvas = document.createElement("canvas");
  17265. if (options.width) {
  17266. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17267. }
  17268. else {
  17269. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17270. }
  17271. }
  17272. var textureSize = this.getSize();
  17273. this._canvas.width = textureSize.width;
  17274. this._canvas.height = textureSize.height;
  17275. this._context = this._canvas.getContext("2d");
  17276. }
  17277. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17278. get: function () {
  17279. return true;
  17280. },
  17281. enumerable: true,
  17282. configurable: true
  17283. });
  17284. DynamicTexture.prototype.scale = function (ratio) {
  17285. var textureSize = this.getSize();
  17286. textureSize.width *= ratio;
  17287. textureSize.height *= ratio;
  17288. this._canvas.width = textureSize.width;
  17289. this._canvas.height = textureSize.height;
  17290. this.releaseInternalTexture();
  17291. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17292. };
  17293. DynamicTexture.prototype.getContext = function () {
  17294. return this._context;
  17295. };
  17296. DynamicTexture.prototype.clear = function () {
  17297. var size = this.getSize();
  17298. this._context.fillRect(0, 0, size.width, size.height);
  17299. };
  17300. DynamicTexture.prototype.update = function (invertY) {
  17301. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17302. };
  17303. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17304. if (update === void 0) { update = true; }
  17305. var size = this.getSize();
  17306. if (clearColor) {
  17307. this._context.fillStyle = clearColor;
  17308. this._context.fillRect(0, 0, size.width, size.height);
  17309. }
  17310. this._context.font = font;
  17311. if (x === null) {
  17312. var textSize = this._context.measureText(text);
  17313. x = (size.width - textSize.width) / 2;
  17314. }
  17315. this._context.fillStyle = color;
  17316. this._context.fillText(text, x, y);
  17317. if (update) {
  17318. this.update(invertY);
  17319. }
  17320. };
  17321. DynamicTexture.prototype.clone = function () {
  17322. var textureSize = this.getSize();
  17323. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17324. // Base texture
  17325. newTexture.hasAlpha = this.hasAlpha;
  17326. newTexture.level = this.level;
  17327. // Dynamic Texture
  17328. newTexture.wrapU = this.wrapU;
  17329. newTexture.wrapV = this.wrapV;
  17330. return newTexture;
  17331. };
  17332. return DynamicTexture;
  17333. })(BABYLON.Texture);
  17334. BABYLON.DynamicTexture = DynamicTexture;
  17335. })(BABYLON || (BABYLON = {}));
  17336. var BABYLON;
  17337. (function (BABYLON) {
  17338. var VideoTexture = (function (_super) {
  17339. __extends(VideoTexture, _super);
  17340. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17341. var _this = this;
  17342. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17343. if (invertY === void 0) { invertY = false; }
  17344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17345. _super.call(this, null, scene, !generateMipMaps, invertY);
  17346. this._autoLaunch = true;
  17347. this.name = name;
  17348. this.video = document.createElement("video");
  17349. this.video.autoplay = false;
  17350. this.video.loop = true;
  17351. this.video.addEventListener("canplaythrough", function () {
  17352. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17353. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17354. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17355. }
  17356. else {
  17357. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17358. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17359. generateMipMaps = false;
  17360. }
  17361. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17362. _this._texture.isReady = true;
  17363. });
  17364. urls.forEach(function (url) {
  17365. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17366. var source = document.createElement("source");
  17367. source.src = url;
  17368. _this.video.appendChild(source);
  17369. });
  17370. this._lastUpdate = BABYLON.Tools.Now;
  17371. }
  17372. VideoTexture.prototype.update = function () {
  17373. if (this._autoLaunch) {
  17374. this._autoLaunch = false;
  17375. this.video.play();
  17376. }
  17377. var now = BABYLON.Tools.Now;
  17378. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17379. return false;
  17380. }
  17381. this._lastUpdate = now;
  17382. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17383. return true;
  17384. };
  17385. return VideoTexture;
  17386. })(BABYLON.Texture);
  17387. BABYLON.VideoTexture = VideoTexture;
  17388. })(BABYLON || (BABYLON = {}));
  17389. var BABYLON;
  17390. (function (BABYLON) {
  17391. var CustomProceduralTexture = (function (_super) {
  17392. __extends(CustomProceduralTexture, _super);
  17393. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17394. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17395. this._animate = true;
  17396. this._time = 0;
  17397. this._texturePath = texturePath;
  17398. //Try to load json
  17399. this.loadJson(texturePath);
  17400. this.refreshRate = 1;
  17401. }
  17402. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17403. var _this = this;
  17404. var that = this;
  17405. function noConfigFile() {
  17406. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17407. try {
  17408. that.setFragment(that._texturePath);
  17409. }
  17410. catch (ex) {
  17411. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17412. }
  17413. }
  17414. var configFileUrl = jsonUrl + "/config.json";
  17415. var xhr = new XMLHttpRequest();
  17416. xhr.open("GET", configFileUrl, true);
  17417. xhr.addEventListener("load", function () {
  17418. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17419. try {
  17420. _this._config = JSON.parse(xhr.response);
  17421. _this.updateShaderUniforms();
  17422. _this.updateTextures();
  17423. _this.setFragment(_this._texturePath + "/custom");
  17424. _this._animate = _this._config.animate;
  17425. _this.refreshRate = _this._config.refreshrate;
  17426. }
  17427. catch (ex) {
  17428. noConfigFile();
  17429. }
  17430. }
  17431. else {
  17432. noConfigFile();
  17433. }
  17434. }, false);
  17435. xhr.addEventListener("error", function () {
  17436. noConfigFile();
  17437. }, false);
  17438. try {
  17439. xhr.send();
  17440. }
  17441. catch (ex) {
  17442. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17443. }
  17444. };
  17445. CustomProceduralTexture.prototype.isReady = function () {
  17446. if (!_super.prototype.isReady.call(this)) {
  17447. return false;
  17448. }
  17449. for (var name in this._textures) {
  17450. var texture = this._textures[name];
  17451. if (!texture.isReady()) {
  17452. return false;
  17453. }
  17454. }
  17455. return true;
  17456. };
  17457. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17458. if (this._animate) {
  17459. this._time += this.getScene().getAnimationRatio() * 0.03;
  17460. this.updateShaderUniforms();
  17461. }
  17462. _super.prototype.render.call(this, useCameraPostProcess);
  17463. };
  17464. CustomProceduralTexture.prototype.updateTextures = function () {
  17465. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17466. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17467. }
  17468. };
  17469. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17470. if (this._config) {
  17471. for (var j = 0; j < this._config.uniforms.length; j++) {
  17472. var uniform = this._config.uniforms[j];
  17473. switch (uniform.type) {
  17474. case "float":
  17475. this.setFloat(uniform.name, uniform.value);
  17476. break;
  17477. case "color3":
  17478. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17479. break;
  17480. case "color4":
  17481. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17482. break;
  17483. case "vector2":
  17484. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17485. break;
  17486. case "vector3":
  17487. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17488. break;
  17489. }
  17490. }
  17491. }
  17492. this.setFloat("time", this._time);
  17493. };
  17494. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17495. get: function () {
  17496. return this._animate;
  17497. },
  17498. set: function (value) {
  17499. this._animate = value;
  17500. },
  17501. enumerable: true,
  17502. configurable: true
  17503. });
  17504. return CustomProceduralTexture;
  17505. })(BABYLON.ProceduralTexture);
  17506. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17507. })(BABYLON || (BABYLON = {}));
  17508. var BABYLON;
  17509. (function (BABYLON) {
  17510. var WoodProceduralTexture = (function (_super) {
  17511. __extends(WoodProceduralTexture, _super);
  17512. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17513. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17514. this._ampScale = 100.0;
  17515. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17516. this.updateShaderUniforms();
  17517. this.refreshRate = 0;
  17518. }
  17519. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17520. this.setFloat("ampScale", this._ampScale);
  17521. this.setColor3("woodColor", this._woodColor);
  17522. };
  17523. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17524. get: function () {
  17525. return this._ampScale;
  17526. },
  17527. set: function (value) {
  17528. this._ampScale = value;
  17529. this.updateShaderUniforms();
  17530. },
  17531. enumerable: true,
  17532. configurable: true
  17533. });
  17534. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17535. get: function () {
  17536. return this._woodColor;
  17537. },
  17538. set: function (value) {
  17539. this._woodColor = value;
  17540. this.updateShaderUniforms();
  17541. },
  17542. enumerable: true,
  17543. configurable: true
  17544. });
  17545. return WoodProceduralTexture;
  17546. })(BABYLON.ProceduralTexture);
  17547. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17548. var FireProceduralTexture = (function (_super) {
  17549. __extends(FireProceduralTexture, _super);
  17550. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17551. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17552. this._time = 0.0;
  17553. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17554. this._autoGenerateTime = true;
  17555. this._alphaThreshold = 0.5;
  17556. this._fireColors = FireProceduralTexture.RedFireColors;
  17557. this.updateShaderUniforms();
  17558. this.refreshRate = 1;
  17559. }
  17560. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17561. this.setFloat("time", this._time);
  17562. this.setVector2("speed", this._speed);
  17563. this.setColor3("c1", this._fireColors[0]);
  17564. this.setColor3("c2", this._fireColors[1]);
  17565. this.setColor3("c3", this._fireColors[2]);
  17566. this.setColor3("c4", this._fireColors[3]);
  17567. this.setColor3("c5", this._fireColors[4]);
  17568. this.setColor3("c6", this._fireColors[5]);
  17569. this.setFloat("alphaThreshold", this._alphaThreshold);
  17570. };
  17571. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17572. if (this._autoGenerateTime) {
  17573. this._time += this.getScene().getAnimationRatio() * 0.03;
  17574. this.updateShaderUniforms();
  17575. }
  17576. _super.prototype.render.call(this, useCameraPostProcess);
  17577. };
  17578. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17579. get: function () {
  17580. return [
  17581. new BABYLON.Color3(0.5, 0.0, 1.0),
  17582. new BABYLON.Color3(0.9, 0.0, 1.0),
  17583. new BABYLON.Color3(0.2, 0.0, 1.0),
  17584. new BABYLON.Color3(1.0, 0.9, 1.0),
  17585. new BABYLON.Color3(0.1, 0.1, 1.0),
  17586. new BABYLON.Color3(0.9, 0.9, 1.0)
  17587. ];
  17588. },
  17589. enumerable: true,
  17590. configurable: true
  17591. });
  17592. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17593. get: function () {
  17594. return [
  17595. new BABYLON.Color3(0.5, 1.0, 0.0),
  17596. new BABYLON.Color3(0.5, 1.0, 0.0),
  17597. new BABYLON.Color3(0.3, 0.4, 0.0),
  17598. new BABYLON.Color3(0.5, 1.0, 0.0),
  17599. new BABYLON.Color3(0.2, 0.0, 0.0),
  17600. new BABYLON.Color3(0.5, 1.0, 0.0)
  17601. ];
  17602. },
  17603. enumerable: true,
  17604. configurable: true
  17605. });
  17606. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17607. get: function () {
  17608. return [
  17609. new BABYLON.Color3(0.5, 0.0, 0.1),
  17610. new BABYLON.Color3(0.9, 0.0, 0.0),
  17611. new BABYLON.Color3(0.2, 0.0, 0.0),
  17612. new BABYLON.Color3(1.0, 0.9, 0.0),
  17613. new BABYLON.Color3(0.1, 0.1, 0.1),
  17614. new BABYLON.Color3(0.9, 0.9, 0.9)
  17615. ];
  17616. },
  17617. enumerable: true,
  17618. configurable: true
  17619. });
  17620. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17621. get: function () {
  17622. return [
  17623. new BABYLON.Color3(0.1, 0.0, 0.5),
  17624. new BABYLON.Color3(0.0, 0.0, 0.5),
  17625. new BABYLON.Color3(0.1, 0.0, 0.2),
  17626. new BABYLON.Color3(0.0, 0.0, 1.0),
  17627. new BABYLON.Color3(0.1, 0.2, 0.3),
  17628. new BABYLON.Color3(0.0, 0.2, 0.9)
  17629. ];
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17635. get: function () {
  17636. return this._fireColors;
  17637. },
  17638. set: function (value) {
  17639. this._fireColors = value;
  17640. this.updateShaderUniforms();
  17641. },
  17642. enumerable: true,
  17643. configurable: true
  17644. });
  17645. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17646. get: function () {
  17647. return this._time;
  17648. },
  17649. set: function (value) {
  17650. this._time = value;
  17651. this.updateShaderUniforms();
  17652. },
  17653. enumerable: true,
  17654. configurable: true
  17655. });
  17656. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17657. get: function () {
  17658. return this._speed;
  17659. },
  17660. set: function (value) {
  17661. this._speed = value;
  17662. this.updateShaderUniforms();
  17663. },
  17664. enumerable: true,
  17665. configurable: true
  17666. });
  17667. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17668. get: function () {
  17669. return this._alphaThreshold;
  17670. },
  17671. set: function (value) {
  17672. this._alphaThreshold = value;
  17673. this.updateShaderUniforms();
  17674. },
  17675. enumerable: true,
  17676. configurable: true
  17677. });
  17678. return FireProceduralTexture;
  17679. })(BABYLON.ProceduralTexture);
  17680. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17681. var CloudProceduralTexture = (function (_super) {
  17682. __extends(CloudProceduralTexture, _super);
  17683. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17684. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17685. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17686. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17687. this.updateShaderUniforms();
  17688. this.refreshRate = 0;
  17689. }
  17690. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17691. this.setColor4("skyColor", this._skyColor);
  17692. this.setColor4("cloudColor", this._cloudColor);
  17693. };
  17694. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17695. get: function () {
  17696. return this._skyColor;
  17697. },
  17698. set: function (value) {
  17699. this._skyColor = value;
  17700. this.updateShaderUniforms();
  17701. },
  17702. enumerable: true,
  17703. configurable: true
  17704. });
  17705. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17706. get: function () {
  17707. return this._cloudColor;
  17708. },
  17709. set: function (value) {
  17710. this._cloudColor = value;
  17711. this.updateShaderUniforms();
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. return CloudProceduralTexture;
  17717. })(BABYLON.ProceduralTexture);
  17718. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17719. var GrassProceduralTexture = (function (_super) {
  17720. __extends(GrassProceduralTexture, _super);
  17721. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17722. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17723. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17724. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17725. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17726. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17727. this._grassColors = [
  17728. new BABYLON.Color3(0.29, 0.38, 0.02),
  17729. new BABYLON.Color3(0.36, 0.49, 0.09),
  17730. new BABYLON.Color3(0.51, 0.6, 0.28)
  17731. ];
  17732. this.updateShaderUniforms();
  17733. this.refreshRate = 0;
  17734. }
  17735. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17736. this.setColor3("herb1Color", this._grassColors[0]);
  17737. this.setColor3("herb2Color", this._grassColors[1]);
  17738. this.setColor3("herb3Color", this._grassColors[2]);
  17739. this.setColor3("groundColor", this._groundColor);
  17740. };
  17741. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17742. get: function () {
  17743. return this._grassColors;
  17744. },
  17745. set: function (value) {
  17746. this._grassColors = value;
  17747. this.updateShaderUniforms();
  17748. },
  17749. enumerable: true,
  17750. configurable: true
  17751. });
  17752. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17753. get: function () {
  17754. return this._groundColor;
  17755. },
  17756. set: function (value) {
  17757. this.groundColor = value;
  17758. this.updateShaderUniforms();
  17759. },
  17760. enumerable: true,
  17761. configurable: true
  17762. });
  17763. return GrassProceduralTexture;
  17764. })(BABYLON.ProceduralTexture);
  17765. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17766. var RoadProceduralTexture = (function (_super) {
  17767. __extends(RoadProceduralTexture, _super);
  17768. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17769. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17770. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17771. this.updateShaderUniforms();
  17772. this.refreshRate = 0;
  17773. }
  17774. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17775. this.setColor3("roadColor", this._roadColor);
  17776. };
  17777. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17778. get: function () {
  17779. return this._roadColor;
  17780. },
  17781. set: function (value) {
  17782. this._roadColor = value;
  17783. this.updateShaderUniforms();
  17784. },
  17785. enumerable: true,
  17786. configurable: true
  17787. });
  17788. return RoadProceduralTexture;
  17789. })(BABYLON.ProceduralTexture);
  17790. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17791. var BrickProceduralTexture = (function (_super) {
  17792. __extends(BrickProceduralTexture, _super);
  17793. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17794. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17795. this._numberOfBricksHeight = 15;
  17796. this._numberOfBricksWidth = 5;
  17797. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17798. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17799. this.updateShaderUniforms();
  17800. this.refreshRate = 0;
  17801. }
  17802. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17803. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17804. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17805. this.setColor3("brickColor", this._brickColor);
  17806. this.setColor3("jointColor", this._jointColor);
  17807. };
  17808. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17809. get: function () {
  17810. return this._numberOfBricksHeight;
  17811. },
  17812. set: function (value) {
  17813. this._numberOfBricksHeight = value;
  17814. this.updateShaderUniforms();
  17815. },
  17816. enumerable: true,
  17817. configurable: true
  17818. });
  17819. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17820. get: function () {
  17821. return this._numberOfBricksWidth;
  17822. },
  17823. set: function (value) {
  17824. this._numberOfBricksHeight = value;
  17825. this.updateShaderUniforms();
  17826. },
  17827. enumerable: true,
  17828. configurable: true
  17829. });
  17830. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17831. get: function () {
  17832. return this._jointColor;
  17833. },
  17834. set: function (value) {
  17835. this._jointColor = value;
  17836. this.updateShaderUniforms();
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17842. get: function () {
  17843. return this._brickColor;
  17844. },
  17845. set: function (value) {
  17846. this._brickColor = value;
  17847. this.updateShaderUniforms();
  17848. },
  17849. enumerable: true,
  17850. configurable: true
  17851. });
  17852. return BrickProceduralTexture;
  17853. })(BABYLON.ProceduralTexture);
  17854. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17855. var MarbleProceduralTexture = (function (_super) {
  17856. __extends(MarbleProceduralTexture, _super);
  17857. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17858. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17859. this._numberOfTilesHeight = 3;
  17860. this._numberOfTilesWidth = 3;
  17861. this._amplitude = 9.0;
  17862. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17863. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17864. this.updateShaderUniforms();
  17865. this.refreshRate = 0;
  17866. }
  17867. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17868. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17869. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17870. this.setFloat("amplitude", this._amplitude);
  17871. this.setColor3("marbleColor", this._marbleColor);
  17872. this.setColor3("jointColor", this._jointColor);
  17873. };
  17874. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17875. get: function () {
  17876. return this._numberOfTilesHeight;
  17877. },
  17878. set: function (value) {
  17879. this._numberOfTilesHeight = value;
  17880. this.updateShaderUniforms();
  17881. },
  17882. enumerable: true,
  17883. configurable: true
  17884. });
  17885. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17886. get: function () {
  17887. return this._numberOfTilesWidth;
  17888. },
  17889. set: function (value) {
  17890. this._numberOfTilesWidth = value;
  17891. this.updateShaderUniforms();
  17892. },
  17893. enumerable: true,
  17894. configurable: true
  17895. });
  17896. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17897. get: function () {
  17898. return this._jointColor;
  17899. },
  17900. set: function (value) {
  17901. this._jointColor = value;
  17902. this.updateShaderUniforms();
  17903. },
  17904. enumerable: true,
  17905. configurable: true
  17906. });
  17907. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17908. get: function () {
  17909. return this._marbleColor;
  17910. },
  17911. set: function (value) {
  17912. this._marbleColor = value;
  17913. this.updateShaderUniforms();
  17914. },
  17915. enumerable: true,
  17916. configurable: true
  17917. });
  17918. return MarbleProceduralTexture;
  17919. })(BABYLON.ProceduralTexture);
  17920. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17921. })(BABYLON || (BABYLON = {}));
  17922. var BABYLON;
  17923. (function (BABYLON) {
  17924. var EffectFallbacks = (function () {
  17925. function EffectFallbacks() {
  17926. this._defines = {};
  17927. this._currentRank = 32;
  17928. this._maxRank = -1;
  17929. }
  17930. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17931. if (!this._defines[rank]) {
  17932. if (rank < this._currentRank) {
  17933. this._currentRank = rank;
  17934. }
  17935. if (rank > this._maxRank) {
  17936. this._maxRank = rank;
  17937. }
  17938. this._defines[rank] = new Array();
  17939. }
  17940. this._defines[rank].push(define);
  17941. };
  17942. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17943. get: function () {
  17944. return this._currentRank <= this._maxRank;
  17945. },
  17946. enumerable: true,
  17947. configurable: true
  17948. });
  17949. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17950. var currentFallbacks = this._defines[this._currentRank];
  17951. for (var index = 0; index < currentFallbacks.length; index++) {
  17952. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17953. }
  17954. this._currentRank++;
  17955. return currentDefines;
  17956. };
  17957. return EffectFallbacks;
  17958. })();
  17959. BABYLON.EffectFallbacks = EffectFallbacks;
  17960. var Effect = (function () {
  17961. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17962. var _this = this;
  17963. this._isReady = false;
  17964. this._compilationError = "";
  17965. this._valueCache = [];
  17966. this._engine = engine;
  17967. this.name = baseName;
  17968. this.defines = defines;
  17969. this._uniformsNames = uniformsNames.concat(samplers);
  17970. this._samplers = samplers;
  17971. this._attributesNames = attributesNames;
  17972. this.onError = onError;
  17973. this.onCompiled = onCompiled;
  17974. var vertexSource;
  17975. var fragmentSource;
  17976. if (baseName.vertexElement) {
  17977. vertexSource = document.getElementById(baseName.vertexElement);
  17978. if (!vertexSource) {
  17979. vertexSource = baseName.vertexElement;
  17980. }
  17981. }
  17982. else {
  17983. vertexSource = baseName.vertex || baseName;
  17984. }
  17985. if (baseName.fragmentElement) {
  17986. fragmentSource = document.getElementById(baseName.fragmentElement);
  17987. if (!fragmentSource) {
  17988. fragmentSource = baseName.fragmentElement;
  17989. }
  17990. }
  17991. else {
  17992. fragmentSource = baseName.fragment || baseName;
  17993. }
  17994. this._loadVertexShader(vertexSource, function (vertexCode) {
  17995. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17996. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17997. });
  17998. });
  17999. }
  18000. // Properties
  18001. Effect.prototype.isReady = function () {
  18002. return this._isReady;
  18003. };
  18004. Effect.prototype.getProgram = function () {
  18005. return this._program;
  18006. };
  18007. Effect.prototype.getAttributesNames = function () {
  18008. return this._attributesNames;
  18009. };
  18010. Effect.prototype.getAttributeLocation = function (index) {
  18011. return this._attributes[index];
  18012. };
  18013. Effect.prototype.getAttributeLocationByName = function (name) {
  18014. var index = this._attributesNames.indexOf(name);
  18015. return this._attributes[index];
  18016. };
  18017. Effect.prototype.getAttributesCount = function () {
  18018. return this._attributes.length;
  18019. };
  18020. Effect.prototype.getUniformIndex = function (uniformName) {
  18021. return this._uniformsNames.indexOf(uniformName);
  18022. };
  18023. Effect.prototype.getUniform = function (uniformName) {
  18024. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18025. };
  18026. Effect.prototype.getSamplers = function () {
  18027. return this._samplers;
  18028. };
  18029. Effect.prototype.getCompilationError = function () {
  18030. return this._compilationError;
  18031. };
  18032. // Methods
  18033. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18034. // DOM element ?
  18035. if (vertex instanceof HTMLElement) {
  18036. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18037. callback(vertexCode);
  18038. return;
  18039. }
  18040. // Is in local store ?
  18041. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18042. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18043. return;
  18044. }
  18045. var vertexShaderUrl;
  18046. if (vertex[0] === "." || vertex[0] === "/") {
  18047. vertexShaderUrl = vertex;
  18048. }
  18049. else {
  18050. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18051. }
  18052. // Vertex shader
  18053. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18054. };
  18055. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18056. // DOM element ?
  18057. if (fragment instanceof HTMLElement) {
  18058. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18059. callback(fragmentCode);
  18060. return;
  18061. }
  18062. // Is in local store ?
  18063. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18064. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18065. return;
  18066. }
  18067. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18068. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18069. return;
  18070. }
  18071. var fragmentShaderUrl;
  18072. if (fragment[0] === "." || fragment[0] === "/") {
  18073. fragmentShaderUrl = fragment;
  18074. }
  18075. else {
  18076. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18077. }
  18078. // Fragment shader
  18079. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18080. };
  18081. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18082. try {
  18083. var engine = this._engine;
  18084. if (!engine.getCaps().highPrecisionShaderSupported) {
  18085. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18086. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18087. }
  18088. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18089. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18090. this._attributes = engine.getAttributes(this._program, attributesNames);
  18091. for (var index = 0; index < this._samplers.length; index++) {
  18092. var sampler = this.getUniform(this._samplers[index]);
  18093. if (sampler == null) {
  18094. this._samplers.splice(index, 1);
  18095. index--;
  18096. }
  18097. }
  18098. engine.bindSamplers(this);
  18099. this._isReady = true;
  18100. if (this.onCompiled) {
  18101. this.onCompiled(this);
  18102. }
  18103. }
  18104. catch (e) {
  18105. // Is it a problem with precision?
  18106. if (e.message.indexOf("highp") !== -1) {
  18107. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18108. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18109. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18110. return;
  18111. }
  18112. // Let's go through fallbacks then
  18113. if (fallbacks && fallbacks.isMoreFallbacks) {
  18114. defines = fallbacks.reduce(defines);
  18115. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18116. }
  18117. else {
  18118. BABYLON.Tools.Error("Unable to compile effect: ");
  18119. if (this.name.vertexElement) {
  18120. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18121. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18122. }
  18123. else if (this.name.vertex) {
  18124. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18125. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18126. }
  18127. else {
  18128. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18129. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18130. }
  18131. BABYLON.Tools.Error("Defines: " + defines);
  18132. BABYLON.Tools.Error("Error: " + e.message);
  18133. this._compilationError = e.message;
  18134. if (this.onError) {
  18135. this.onError(this, this._compilationError);
  18136. }
  18137. }
  18138. }
  18139. };
  18140. Effect.prototype._bindTexture = function (channel, texture) {
  18141. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18142. };
  18143. Effect.prototype.setTexture = function (channel, texture) {
  18144. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18145. };
  18146. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18147. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18148. };
  18149. //public _cacheMatrix(uniformName, matrix) {
  18150. // if (!this._valueCache[uniformName]) {
  18151. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18152. // }
  18153. // for (var index = 0; index < 16; index++) {
  18154. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18155. // }
  18156. //};
  18157. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18158. if (!this._valueCache[uniformName]) {
  18159. this._valueCache[uniformName] = [x, y];
  18160. return;
  18161. }
  18162. this._valueCache[uniformName][0] = x;
  18163. this._valueCache[uniformName][1] = y;
  18164. };
  18165. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18166. if (!this._valueCache[uniformName]) {
  18167. this._valueCache[uniformName] = [x, y, z];
  18168. return;
  18169. }
  18170. this._valueCache[uniformName][0] = x;
  18171. this._valueCache[uniformName][1] = y;
  18172. this._valueCache[uniformName][2] = z;
  18173. };
  18174. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18175. if (!this._valueCache[uniformName]) {
  18176. this._valueCache[uniformName] = [x, y, z, w];
  18177. return;
  18178. }
  18179. this._valueCache[uniformName][0] = x;
  18180. this._valueCache[uniformName][1] = y;
  18181. this._valueCache[uniformName][2] = z;
  18182. this._valueCache[uniformName][3] = w;
  18183. };
  18184. Effect.prototype.setArray = function (uniformName, array) {
  18185. this._engine.setArray(this.getUniform(uniformName), array);
  18186. return this;
  18187. };
  18188. Effect.prototype.setArray2 = function (uniformName, array) {
  18189. this._engine.setArray2(this.getUniform(uniformName), array);
  18190. return this;
  18191. };
  18192. Effect.prototype.setArray3 = function (uniformName, array) {
  18193. this._engine.setArray3(this.getUniform(uniformName), array);
  18194. return this;
  18195. };
  18196. Effect.prototype.setArray4 = function (uniformName, array) {
  18197. this._engine.setArray4(this.getUniform(uniformName), array);
  18198. return this;
  18199. };
  18200. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18201. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18202. return this;
  18203. };
  18204. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18205. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18206. // return;
  18207. //this._cacheMatrix(uniformName, matrix);
  18208. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18209. return this;
  18210. };
  18211. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18212. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18213. return this;
  18214. };
  18215. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18216. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18217. return this;
  18218. };
  18219. Effect.prototype.setFloat = function (uniformName, value) {
  18220. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18221. return this;
  18222. this._valueCache[uniformName] = value;
  18223. this._engine.setFloat(this.getUniform(uniformName), value);
  18224. return this;
  18225. };
  18226. Effect.prototype.setBool = function (uniformName, bool) {
  18227. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18228. return this;
  18229. this._valueCache[uniformName] = bool;
  18230. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18231. return this;
  18232. };
  18233. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18234. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18235. return this;
  18236. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18237. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18238. return this;
  18239. };
  18240. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18241. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18242. return this;
  18243. this._cacheFloat2(uniformName, x, y);
  18244. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18245. return this;
  18246. };
  18247. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18248. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18249. return this;
  18250. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18251. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18252. return this;
  18253. };
  18254. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18255. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18256. return this;
  18257. this._cacheFloat3(uniformName, x, y, z);
  18258. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18259. return this;
  18260. };
  18261. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18262. 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)
  18263. return this;
  18264. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18265. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18266. return this;
  18267. };
  18268. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18269. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18270. return this;
  18271. this._cacheFloat4(uniformName, x, y, z, w);
  18272. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18273. return this;
  18274. };
  18275. Effect.prototype.setColor3 = function (uniformName, color3) {
  18276. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18277. return this;
  18278. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18279. this._engine.setColor3(this.getUniform(uniformName), color3);
  18280. return this;
  18281. };
  18282. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18283. 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)
  18284. return this;
  18285. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18286. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18287. return this;
  18288. };
  18289. // Statics
  18290. Effect.ShadersStore = {};
  18291. return Effect;
  18292. })();
  18293. BABYLON.Effect = Effect;
  18294. })(BABYLON || (BABYLON = {}));
  18295. var BABYLON;
  18296. (function (BABYLON) {
  18297. var Material = (function () {
  18298. function Material(name, scene, doNotAdd) {
  18299. this.name = name;
  18300. this.checkReadyOnEveryCall = true;
  18301. this.checkReadyOnlyOnce = false;
  18302. this.state = "";
  18303. this.alpha = 1.0;
  18304. this.backFaceCulling = true;
  18305. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18306. this.disableDepthWrite = false;
  18307. this._wasPreviouslyReady = false;
  18308. this._fillMode = Material.TriangleFillMode;
  18309. this.pointSize = 1.0;
  18310. this.zOffset = 0;
  18311. this.id = name;
  18312. this._scene = scene;
  18313. if (!doNotAdd) {
  18314. scene.materials.push(this);
  18315. }
  18316. }
  18317. Object.defineProperty(Material, "TriangleFillMode", {
  18318. get: function () {
  18319. return Material._TriangleFillMode;
  18320. },
  18321. enumerable: true,
  18322. configurable: true
  18323. });
  18324. Object.defineProperty(Material, "WireFrameFillMode", {
  18325. get: function () {
  18326. return Material._WireFrameFillMode;
  18327. },
  18328. enumerable: true,
  18329. configurable: true
  18330. });
  18331. Object.defineProperty(Material, "PointFillMode", {
  18332. get: function () {
  18333. return Material._PointFillMode;
  18334. },
  18335. enumerable: true,
  18336. configurable: true
  18337. });
  18338. Object.defineProperty(Material.prototype, "wireframe", {
  18339. get: function () {
  18340. return this._fillMode === Material.WireFrameFillMode;
  18341. },
  18342. set: function (value) {
  18343. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18344. },
  18345. enumerable: true,
  18346. configurable: true
  18347. });
  18348. Object.defineProperty(Material.prototype, "pointsCloud", {
  18349. get: function () {
  18350. return this._fillMode === Material.PointFillMode;
  18351. },
  18352. set: function (value) {
  18353. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18354. },
  18355. enumerable: true,
  18356. configurable: true
  18357. });
  18358. Object.defineProperty(Material.prototype, "fillMode", {
  18359. get: function () {
  18360. return this._fillMode;
  18361. },
  18362. set: function (value) {
  18363. this._fillMode = value;
  18364. },
  18365. enumerable: true,
  18366. configurable: true
  18367. });
  18368. Material.prototype.isReady = function (mesh, useInstances) {
  18369. return true;
  18370. };
  18371. Material.prototype.getEffect = function () {
  18372. return this._effect;
  18373. };
  18374. Material.prototype.getScene = function () {
  18375. return this._scene;
  18376. };
  18377. Material.prototype.needAlphaBlending = function () {
  18378. return (this.alpha < 1.0);
  18379. };
  18380. Material.prototype.needAlphaTesting = function () {
  18381. return false;
  18382. };
  18383. Material.prototype.getAlphaTestTexture = function () {
  18384. return null;
  18385. };
  18386. Material.prototype.trackCreation = function (onCompiled, onError) {
  18387. };
  18388. Material.prototype._preBind = function () {
  18389. var engine = this._scene.getEngine();
  18390. engine.enableEffect(this._effect);
  18391. engine.setState(this.backFaceCulling, this.zOffset);
  18392. };
  18393. Material.prototype.bind = function (world, mesh) {
  18394. this._scene._cachedMaterial = this;
  18395. if (this.onBind) {
  18396. this.onBind(this, mesh);
  18397. }
  18398. if (this.disableDepthWrite) {
  18399. var engine = this._scene.getEngine();
  18400. this._cachedDepthWriteState = engine.getDepthWrite();
  18401. engine.setDepthWrite(false);
  18402. }
  18403. };
  18404. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18405. };
  18406. Material.prototype.unbind = function () {
  18407. if (this.disableDepthWrite) {
  18408. var engine = this._scene.getEngine();
  18409. engine.setDepthWrite(this._cachedDepthWriteState);
  18410. }
  18411. };
  18412. Material.prototype.clone = function (name) {
  18413. return null;
  18414. };
  18415. Material.prototype.dispose = function (forceDisposeEffect) {
  18416. // Remove from scene
  18417. var index = this._scene.materials.indexOf(this);
  18418. this._scene.materials.splice(index, 1);
  18419. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18420. if (forceDisposeEffect && this._effect) {
  18421. this._scene.getEngine()._releaseEffect(this._effect);
  18422. this._effect = null;
  18423. }
  18424. // Callback
  18425. if (this.onDispose) {
  18426. this.onDispose();
  18427. }
  18428. };
  18429. Material._TriangleFillMode = 0;
  18430. Material._WireFrameFillMode = 1;
  18431. Material._PointFillMode = 2;
  18432. return Material;
  18433. })();
  18434. BABYLON.Material = Material;
  18435. })(BABYLON || (BABYLON = {}));
  18436. var BABYLON;
  18437. (function (BABYLON) {
  18438. var maxSimultaneousLights = 4;
  18439. var FresnelParameters = (function () {
  18440. function FresnelParameters() {
  18441. this.isEnabled = true;
  18442. this.leftColor = BABYLON.Color3.White();
  18443. this.rightColor = BABYLON.Color3.Black();
  18444. this.bias = 0;
  18445. this.power = 1;
  18446. }
  18447. return FresnelParameters;
  18448. })();
  18449. BABYLON.FresnelParameters = FresnelParameters;
  18450. var StandardMaterialDefines = (function () {
  18451. function StandardMaterialDefines() {
  18452. this.DIFFUSE = false;
  18453. this.AMBIENT = false;
  18454. this.OPACITY = false;
  18455. this.OPACITYRGB = false;
  18456. this.REFLECTION = false;
  18457. this.EMISSIVE = false;
  18458. this.SPECULAR = false;
  18459. this.BUMP = false;
  18460. this.SPECULAROVERALPHA = false;
  18461. this.CLIPPLANE = false;
  18462. this.ALPHATEST = false;
  18463. this.ALPHAFROMDIFFUSE = false;
  18464. this.POINTSIZE = false;
  18465. this.FOG = false;
  18466. this.LIGHT0 = false;
  18467. this.LIGHT1 = false;
  18468. this.LIGHT2 = false;
  18469. this.LIGHT3 = false;
  18470. this.SPOTLIGHT0 = false;
  18471. this.SPOTLIGHT1 = false;
  18472. this.SPOTLIGHT2 = false;
  18473. this.SPOTLIGHT3 = false;
  18474. this.HEMILIGHT0 = false;
  18475. this.HEMILIGHT1 = false;
  18476. this.HEMILIGHT2 = false;
  18477. this.HEMILIGHT3 = false;
  18478. this.POINTDIRLIGHT0 = false;
  18479. this.POINTDIRLIGHT1 = false;
  18480. this.POINTDIRLIGHT2 = false;
  18481. this.POINTDIRLIGHT3 = false;
  18482. this.SPECULARTERM = false;
  18483. this.SHADOW0 = false;
  18484. this.SHADOW1 = false;
  18485. this.SHADOW2 = false;
  18486. this.SHADOW3 = false;
  18487. this.SHADOWS = false;
  18488. this.SHADOWVSM0 = false;
  18489. this.SHADOWVSM1 = false;
  18490. this.SHADOWVSM2 = false;
  18491. this.SHADOWVSM3 = false;
  18492. this.SHADOWPCF0 = false;
  18493. this.SHADOWPCF1 = false;
  18494. this.SHADOWPCF2 = false;
  18495. this.SHADOWPCF3 = false;
  18496. this.DIFFUSEFRESNEL = false;
  18497. this.OPACITYFRESNEL = false;
  18498. this.REFLECTIONFRESNEL = false;
  18499. this.EMISSIVEFRESNEL = false;
  18500. this.FRESNEL = false;
  18501. this.NORMAL = false;
  18502. this.UV1 = false;
  18503. this.UV2 = false;
  18504. this.VERTEXCOLOR = false;
  18505. this.VERTEXALPHA = false;
  18506. this.BONES = false;
  18507. this.BONES4 = false;
  18508. this.BonesPerMesh = 0;
  18509. this.INSTANCES = false;
  18510. this.GLOSSINESS = false;
  18511. this._keys = Object.keys(this);
  18512. }
  18513. StandardMaterialDefines.prototype.isEqual = function (other) {
  18514. for (var index = 0; index < this._keys.length; index++) {
  18515. var prop = this._keys[index];
  18516. if (this[prop] !== other[prop]) {
  18517. return false;
  18518. }
  18519. }
  18520. return true;
  18521. };
  18522. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18523. for (var index = 0; index < this._keys.length; index++) {
  18524. var prop = this._keys[index];
  18525. other[prop] = this[prop];
  18526. }
  18527. };
  18528. StandardMaterialDefines.prototype.reset = function () {
  18529. for (var index = 0; index < this._keys.length; index++) {
  18530. var prop = this._keys[index];
  18531. if (prop === "BonesPerMesh") {
  18532. this[prop] = 0;
  18533. continue;
  18534. }
  18535. this[prop] = false;
  18536. }
  18537. };
  18538. StandardMaterialDefines.prototype.toString = function () {
  18539. var result = "";
  18540. for (var index = 0; index < this._keys.length; index++) {
  18541. var prop = this._keys[index];
  18542. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18543. result += "#define BonesPerMesh " + this[prop] + "\n";
  18544. continue;
  18545. }
  18546. if (this[prop]) {
  18547. result += "#define " + prop + "\n";
  18548. }
  18549. }
  18550. return result;
  18551. };
  18552. return StandardMaterialDefines;
  18553. })();
  18554. var StandardMaterial = (function (_super) {
  18555. __extends(StandardMaterial, _super);
  18556. function StandardMaterial(name, scene) {
  18557. var _this = this;
  18558. _super.call(this, name, scene);
  18559. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18560. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18561. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18562. this.specularPower = 64;
  18563. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18564. this.useAlphaFromDiffuseTexture = false;
  18565. this.useSpecularOverAlpha = true;
  18566. this.fogEnabled = true;
  18567. this.useGlossinessFromSpecularMapAlpha = false;
  18568. this._renderTargets = new BABYLON.SmartArray(16);
  18569. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18570. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18571. this._scaledDiffuse = new BABYLON.Color3();
  18572. this._scaledSpecular = new BABYLON.Color3();
  18573. this._defines = new StandardMaterialDefines();
  18574. this._cachedDefines = new StandardMaterialDefines();
  18575. this._cachedDefines.BonesPerMesh = -1;
  18576. this.getRenderTargetTextures = function () {
  18577. _this._renderTargets.reset();
  18578. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18579. _this._renderTargets.push(_this.reflectionTexture);
  18580. }
  18581. return _this._renderTargets;
  18582. };
  18583. }
  18584. StandardMaterial.prototype.needAlphaBlending = function () {
  18585. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18586. };
  18587. StandardMaterial.prototype.needAlphaTesting = function () {
  18588. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18589. };
  18590. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18591. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18592. };
  18593. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18594. return this.diffuseTexture;
  18595. };
  18596. // Methods
  18597. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18598. if (this.checkReadyOnlyOnce) {
  18599. if (this._wasPreviouslyReady) {
  18600. return true;
  18601. }
  18602. }
  18603. var scene = this.getScene();
  18604. if (!this.checkReadyOnEveryCall) {
  18605. if (this._renderId === scene.getRenderId()) {
  18606. return true;
  18607. }
  18608. }
  18609. var engine = scene.getEngine();
  18610. var needNormals = false;
  18611. var needUVs = false;
  18612. this._defines.reset();
  18613. // Textures
  18614. if (scene.texturesEnabled) {
  18615. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18616. if (!this.diffuseTexture.isReady()) {
  18617. return false;
  18618. }
  18619. else {
  18620. needUVs = true;
  18621. this._defines.DIFFUSE = true;
  18622. }
  18623. }
  18624. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18625. if (!this.ambientTexture.isReady()) {
  18626. return false;
  18627. }
  18628. else {
  18629. needUVs = true;
  18630. this._defines.AMBIENT = true;
  18631. }
  18632. }
  18633. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18634. if (!this.opacityTexture.isReady()) {
  18635. return false;
  18636. }
  18637. else {
  18638. needUVs = true;
  18639. this._defines.OPACITY = true;
  18640. if (this.opacityTexture.getAlphaFromRGB) {
  18641. this._defines.OPACITYRGB = true;
  18642. }
  18643. }
  18644. }
  18645. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18646. if (!this.reflectionTexture.isReady()) {
  18647. return false;
  18648. }
  18649. else {
  18650. needNormals = true;
  18651. needUVs = true;
  18652. this._defines.REFLECTION = true;
  18653. }
  18654. }
  18655. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18656. if (!this.emissiveTexture.isReady()) {
  18657. return false;
  18658. }
  18659. else {
  18660. needUVs = true;
  18661. this._defines.EMISSIVE = true;
  18662. }
  18663. }
  18664. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18665. if (!this.specularTexture.isReady()) {
  18666. return false;
  18667. }
  18668. else {
  18669. needUVs = true;
  18670. this._defines.SPECULAR = true;
  18671. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18672. }
  18673. }
  18674. }
  18675. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18676. if (!this.bumpTexture.isReady()) {
  18677. return false;
  18678. }
  18679. else {
  18680. needUVs = true;
  18681. this._defines.BUMP = true;
  18682. }
  18683. }
  18684. // Effect
  18685. if (scene.clipPlane) {
  18686. this._defines.CLIPPLANE = true;
  18687. }
  18688. if (engine.getAlphaTesting()) {
  18689. this._defines.ALPHATEST = true;
  18690. }
  18691. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18692. this._defines.ALPHAFROMDIFFUSE = true;
  18693. }
  18694. // Point size
  18695. if (this.pointsCloud || scene.forcePointsCloud) {
  18696. this._defines.POINTSIZE = true;
  18697. }
  18698. // Fog
  18699. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18700. this._defines.FOG = true;
  18701. }
  18702. var lightIndex = 0;
  18703. if (scene.lightsEnabled) {
  18704. for (var index = 0; index < scene.lights.length; index++) {
  18705. var light = scene.lights[index];
  18706. if (!light.isEnabled()) {
  18707. continue;
  18708. }
  18709. // Excluded check
  18710. if (light._excludedMeshesIds.length > 0) {
  18711. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18712. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18713. if (excludedMesh) {
  18714. light.excludedMeshes.push(excludedMesh);
  18715. }
  18716. }
  18717. light._excludedMeshesIds = [];
  18718. }
  18719. // Included check
  18720. if (light._includedOnlyMeshesIds.length > 0) {
  18721. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18722. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18723. if (includedOnlyMesh) {
  18724. light.includedOnlyMeshes.push(includedOnlyMesh);
  18725. }
  18726. }
  18727. light._includedOnlyMeshesIds = [];
  18728. }
  18729. if (!light.canAffectMesh(mesh)) {
  18730. continue;
  18731. }
  18732. needNormals = true;
  18733. this._defines["LIGHT" + lightIndex] = true;
  18734. var type;
  18735. if (light instanceof BABYLON.SpotLight) {
  18736. type = "SPOTLIGHT" + lightIndex;
  18737. }
  18738. else if (light instanceof BABYLON.HemisphericLight) {
  18739. type = "HEMILIGHT" + lightIndex;
  18740. }
  18741. else {
  18742. type = "POINTDIRLIGHT" + lightIndex;
  18743. }
  18744. this._defines[type] = true;
  18745. // Specular
  18746. if (!light.specular.equalsFloats(0, 0, 0)) {
  18747. this._defines.SPECULARTERM = true;
  18748. }
  18749. // Shadows
  18750. if (scene.shadowsEnabled) {
  18751. var shadowGenerator = light.getShadowGenerator();
  18752. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18753. this._defines["SHADOW" + lightIndex] = true;
  18754. this._defines.SHADOWS = true;
  18755. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18756. this._defines["SHADOWVSM" + lightIndex] = true;
  18757. }
  18758. if (shadowGenerator.usePoissonSampling) {
  18759. this._defines["SHADOWPCF" + lightIndex] = true;
  18760. }
  18761. }
  18762. }
  18763. lightIndex++;
  18764. if (lightIndex === maxSimultaneousLights)
  18765. break;
  18766. }
  18767. }
  18768. if (StandardMaterial.FresnelEnabled) {
  18769. // Fresnel
  18770. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18771. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18772. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18773. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18774. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18775. this._defines.DIFFUSEFRESNEL = true;
  18776. }
  18777. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18778. this._defines.OPACITYFRESNEL = true;
  18779. }
  18780. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18781. this._defines.REFLECTIONFRESNEL = true;
  18782. }
  18783. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18784. this._defines.EMISSIVEFRESNEL = true;
  18785. }
  18786. needNormals = true;
  18787. this._defines.FRESNEL = true;
  18788. }
  18789. }
  18790. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18791. this._defines.SPECULAROVERALPHA = true;
  18792. }
  18793. // Attribs
  18794. if (mesh) {
  18795. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18796. this._defines.NORMAL = true;
  18797. }
  18798. if (needUVs) {
  18799. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18800. this._defines.UV1 = true;
  18801. }
  18802. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18803. this._defines.UV2 = true;
  18804. }
  18805. }
  18806. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18807. this._defines.VERTEXCOLOR = true;
  18808. if (mesh.hasVertexAlpha) {
  18809. this._defines.VERTEXALPHA = true;
  18810. }
  18811. }
  18812. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18813. this._defines.BONES = true;
  18814. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18815. this._defines.BONES4 = true;
  18816. }
  18817. // Instances
  18818. if (useInstances) {
  18819. this._defines.INSTANCES = true;
  18820. }
  18821. }
  18822. // Get correct effect
  18823. if (!this._defines.isEqual(this._cachedDefines)) {
  18824. this._defines.cloneTo(this._cachedDefines);
  18825. scene.resetCachedMaterial();
  18826. // Fallbacks
  18827. var fallbacks = new BABYLON.EffectFallbacks();
  18828. if (this._defines.REFLECTION) {
  18829. fallbacks.addFallback(0, "REFLECTION");
  18830. }
  18831. if (this._defines.SPECULAR) {
  18832. fallbacks.addFallback(0, "SPECULAR");
  18833. }
  18834. if (this._defines.BUMP) {
  18835. fallbacks.addFallback(0, "BUMP");
  18836. }
  18837. if (this._defines.SPECULAROVERALPHA) {
  18838. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18839. }
  18840. if (this._defines.FOG) {
  18841. fallbacks.addFallback(1, "FOG");
  18842. }
  18843. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18844. if (!this._defines["LIGHT" + lightIndex]) {
  18845. continue;
  18846. }
  18847. if (lightIndex > 0) {
  18848. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18849. }
  18850. if (this._defines["SHADOW" + lightIndex]) {
  18851. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18852. }
  18853. if (this._defines["SHADOWPCF" + lightIndex]) {
  18854. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18855. }
  18856. if (this._defines["SHADOWVSM" + lightIndex]) {
  18857. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18858. }
  18859. }
  18860. if (this._defines.SPECULARTERM) {
  18861. fallbacks.addFallback(0, "SPECULARTERM");
  18862. }
  18863. if (this._defines.DIFFUSEFRESNEL) {
  18864. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18865. }
  18866. if (this._defines.OPACITYFRESNEL) {
  18867. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18868. }
  18869. if (this._defines.REFLECTIONFRESNEL) {
  18870. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18871. }
  18872. if (this._defines.EMISSIVEFRESNEL) {
  18873. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18874. }
  18875. if (this._defines.FRESNEL) {
  18876. fallbacks.addFallback(4, "FRESNEL");
  18877. }
  18878. if (this._defines.BONES4) {
  18879. fallbacks.addFallback(0, "BONES4");
  18880. }
  18881. //Attributes
  18882. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18883. if (this._defines.NORMAL) {
  18884. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18885. }
  18886. if (this._defines.UV1) {
  18887. attribs.push(BABYLON.VertexBuffer.UVKind);
  18888. }
  18889. if (this._defines.UV2) {
  18890. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18891. }
  18892. if (this._defines.VERTEXCOLOR) {
  18893. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18894. }
  18895. if (this._defines.BONES) {
  18896. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18897. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18898. }
  18899. if (this._defines.INSTANCES) {
  18900. attribs.push("world0");
  18901. attribs.push("world1");
  18902. attribs.push("world2");
  18903. attribs.push("world3");
  18904. }
  18905. // Legacy browser patch
  18906. var shaderName = "default";
  18907. if (!scene.getEngine().getCaps().standardDerivatives) {
  18908. shaderName = "legacydefault";
  18909. }
  18910. var join = this._defines.toString();
  18911. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18912. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18913. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18914. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18915. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18916. "vFogInfos", "vFogColor", "pointSize",
  18917. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18918. "mBones",
  18919. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18920. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18921. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18922. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18923. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18924. ], join, fallbacks, this.onCompiled, this.onError);
  18925. }
  18926. if (!this._effect.isReady()) {
  18927. return false;
  18928. }
  18929. this._renderId = scene.getRenderId();
  18930. this._wasPreviouslyReady = true;
  18931. return true;
  18932. };
  18933. StandardMaterial.prototype.unbind = function () {
  18934. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18935. this._effect.setTexture("reflection2DSampler", null);
  18936. }
  18937. _super.prototype.unbind.call(this);
  18938. };
  18939. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18940. this._effect.setMatrix("world", world);
  18941. };
  18942. StandardMaterial.prototype.bind = function (world, mesh) {
  18943. var scene = this.getScene();
  18944. // Matrices
  18945. this.bindOnlyWorldMatrix(world);
  18946. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18947. // Bones
  18948. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  18949. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18950. }
  18951. if (scene.getCachedMaterial() !== this) {
  18952. if (StandardMaterial.FresnelEnabled) {
  18953. // Fresnel
  18954. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18955. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18956. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18957. }
  18958. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18959. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18960. }
  18961. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18962. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18963. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18964. }
  18965. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18966. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18967. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18968. }
  18969. }
  18970. // Textures
  18971. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18972. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18973. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18974. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18975. }
  18976. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18977. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18978. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18979. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18980. }
  18981. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18982. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18983. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18984. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18985. }
  18986. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18987. if (this.reflectionTexture.isCube) {
  18988. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18989. }
  18990. else {
  18991. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18992. }
  18993. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18994. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18995. }
  18996. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18997. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18998. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18999. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19000. }
  19001. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19002. this._effect.setTexture("specularSampler", this.specularTexture);
  19003. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19004. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19005. }
  19006. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19007. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19008. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19009. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19010. }
  19011. // Clip plane
  19012. if (scene.clipPlane) {
  19013. var clipPlane = scene.clipPlane;
  19014. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19015. }
  19016. // Point size
  19017. if (this.pointsCloud) {
  19018. this._effect.setFloat("pointSize", this.pointSize);
  19019. }
  19020. // Colors
  19021. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19022. // Scaling down color according to emissive
  19023. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19024. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19025. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19026. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  19027. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19028. if (this._defines.SPECULARTERM) {
  19029. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19030. }
  19031. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19032. }
  19033. // Scaling down color according to emissive
  19034. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19035. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19036. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19037. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19038. if (scene.lightsEnabled) {
  19039. var lightIndex = 0;
  19040. for (var index = 0; index < scene.lights.length; index++) {
  19041. var light = scene.lights[index];
  19042. if (!light.isEnabled()) {
  19043. continue;
  19044. }
  19045. if (!light.canAffectMesh(mesh)) {
  19046. continue;
  19047. }
  19048. if (light instanceof BABYLON.PointLight) {
  19049. // Point Light
  19050. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19051. }
  19052. else if (light instanceof BABYLON.DirectionalLight) {
  19053. // Directional Light
  19054. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19055. }
  19056. else if (light instanceof BABYLON.SpotLight) {
  19057. // Spot Light
  19058. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19059. }
  19060. else if (light instanceof BABYLON.HemisphericLight) {
  19061. // Hemispheric Light
  19062. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19063. }
  19064. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19065. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19066. if (this._defines.SPECULARTERM) {
  19067. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19068. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19069. }
  19070. // Shadows
  19071. if (scene.shadowsEnabled) {
  19072. var shadowGenerator = light.getShadowGenerator();
  19073. if (mesh.receiveShadows && shadowGenerator) {
  19074. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19075. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19076. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19077. }
  19078. }
  19079. lightIndex++;
  19080. if (lightIndex === maxSimultaneousLights)
  19081. break;
  19082. }
  19083. }
  19084. // View
  19085. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19086. this._effect.setMatrix("view", scene.getViewMatrix());
  19087. }
  19088. // Fog
  19089. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19090. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19091. this._effect.setColor3("vFogColor", scene.fogColor);
  19092. }
  19093. _super.prototype.bind.call(this, world, mesh);
  19094. };
  19095. StandardMaterial.prototype.getAnimatables = function () {
  19096. var results = [];
  19097. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19098. results.push(this.diffuseTexture);
  19099. }
  19100. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19101. results.push(this.ambientTexture);
  19102. }
  19103. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19104. results.push(this.opacityTexture);
  19105. }
  19106. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19107. results.push(this.reflectionTexture);
  19108. }
  19109. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19110. results.push(this.emissiveTexture);
  19111. }
  19112. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19113. results.push(this.specularTexture);
  19114. }
  19115. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19116. results.push(this.bumpTexture);
  19117. }
  19118. return results;
  19119. };
  19120. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19121. if (this.diffuseTexture) {
  19122. this.diffuseTexture.dispose();
  19123. }
  19124. if (this.ambientTexture) {
  19125. this.ambientTexture.dispose();
  19126. }
  19127. if (this.opacityTexture) {
  19128. this.opacityTexture.dispose();
  19129. }
  19130. if (this.reflectionTexture) {
  19131. this.reflectionTexture.dispose();
  19132. }
  19133. if (this.emissiveTexture) {
  19134. this.emissiveTexture.dispose();
  19135. }
  19136. if (this.specularTexture) {
  19137. this.specularTexture.dispose();
  19138. }
  19139. if (this.bumpTexture) {
  19140. this.bumpTexture.dispose();
  19141. }
  19142. _super.prototype.dispose.call(this, forceDisposeEffect);
  19143. };
  19144. StandardMaterial.prototype.clone = function (name) {
  19145. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19146. // Base material
  19147. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19148. newStandardMaterial.alpha = this.alpha;
  19149. newStandardMaterial.fillMode = this.fillMode;
  19150. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  19151. // Standard material
  19152. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19153. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19154. }
  19155. if (this.ambientTexture && this.ambientTexture.clone) {
  19156. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19157. }
  19158. if (this.opacityTexture && this.opacityTexture.clone) {
  19159. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19160. }
  19161. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19162. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19163. }
  19164. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19165. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19166. }
  19167. if (this.specularTexture && this.specularTexture.clone) {
  19168. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19169. }
  19170. if (this.bumpTexture && this.bumpTexture.clone) {
  19171. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19172. }
  19173. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19174. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19175. newStandardMaterial.specularColor = this.specularColor.clone();
  19176. newStandardMaterial.specularPower = this.specularPower;
  19177. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19178. return newStandardMaterial;
  19179. };
  19180. // Statics
  19181. // Flags used to enable or disable a type of texture for all Standard Materials
  19182. StandardMaterial.DiffuseTextureEnabled = true;
  19183. StandardMaterial.AmbientTextureEnabled = true;
  19184. StandardMaterial.OpacityTextureEnabled = true;
  19185. StandardMaterial.ReflectionTextureEnabled = true;
  19186. StandardMaterial.EmissiveTextureEnabled = true;
  19187. StandardMaterial.SpecularTextureEnabled = true;
  19188. StandardMaterial.BumpTextureEnabled = true;
  19189. StandardMaterial.FresnelEnabled = true;
  19190. return StandardMaterial;
  19191. })(BABYLON.Material);
  19192. BABYLON.StandardMaterial = StandardMaterial;
  19193. })(BABYLON || (BABYLON = {}));
  19194. var BABYLON;
  19195. (function (BABYLON) {
  19196. var MultiMaterial = (function (_super) {
  19197. __extends(MultiMaterial, _super);
  19198. function MultiMaterial(name, scene) {
  19199. _super.call(this, name, scene, true);
  19200. this.subMaterials = new Array();
  19201. scene.multiMaterials.push(this);
  19202. }
  19203. // Properties
  19204. MultiMaterial.prototype.getSubMaterial = function (index) {
  19205. if (index < 0 || index >= this.subMaterials.length) {
  19206. return this.getScene().defaultMaterial;
  19207. }
  19208. return this.subMaterials[index];
  19209. };
  19210. // Methods
  19211. MultiMaterial.prototype.isReady = function (mesh) {
  19212. for (var index = 0; index < this.subMaterials.length; index++) {
  19213. var subMaterial = this.subMaterials[index];
  19214. if (subMaterial) {
  19215. if (!this.subMaterials[index].isReady(mesh)) {
  19216. return false;
  19217. }
  19218. }
  19219. }
  19220. return true;
  19221. };
  19222. MultiMaterial.prototype.clone = function (name) {
  19223. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19224. for (var index = 0; index < this.subMaterials.length; index++) {
  19225. var subMaterial = this.subMaterials[index];
  19226. newMultiMaterial.subMaterials.push(subMaterial);
  19227. }
  19228. return newMultiMaterial;
  19229. };
  19230. return MultiMaterial;
  19231. })(BABYLON.Material);
  19232. BABYLON.MultiMaterial = MultiMaterial;
  19233. })(BABYLON || (BABYLON = {}));
  19234. var BABYLON;
  19235. (function (BABYLON) {
  19236. var SceneLoader = (function () {
  19237. function SceneLoader() {
  19238. }
  19239. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19240. get: function () {
  19241. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19242. },
  19243. set: function (value) {
  19244. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19245. },
  19246. enumerable: true,
  19247. configurable: true
  19248. });
  19249. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19250. get: function () {
  19251. return SceneLoader._ShowLoadingScreen;
  19252. },
  19253. set: function (value) {
  19254. SceneLoader._ShowLoadingScreen = value;
  19255. },
  19256. enumerable: true,
  19257. configurable: true
  19258. });
  19259. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19260. var dotPosition = sceneFilename.lastIndexOf(".");
  19261. var queryStringPosition = sceneFilename.indexOf("?");
  19262. if (queryStringPosition === -1) {
  19263. queryStringPosition = sceneFilename.length;
  19264. }
  19265. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19266. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19267. var plugin = this._registeredPlugins[index];
  19268. if (plugin.extensions.indexOf(extension) !== -1) {
  19269. return plugin;
  19270. }
  19271. }
  19272. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19273. };
  19274. // Public functions
  19275. SceneLoader.RegisterPlugin = function (plugin) {
  19276. plugin.extensions = plugin.extensions.toLowerCase();
  19277. SceneLoader._registeredPlugins.push(plugin);
  19278. };
  19279. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19280. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19281. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19282. return;
  19283. }
  19284. var loadingToken = {};
  19285. scene._addPendingData(loadingToken);
  19286. var manifestChecked = function (success) {
  19287. scene.database = database;
  19288. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19289. var importMeshFromData = function (data) {
  19290. var meshes = [];
  19291. var particleSystems = [];
  19292. var skeletons = [];
  19293. try {
  19294. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19295. if (onerror) {
  19296. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19297. }
  19298. scene._removePendingData(loadingToken);
  19299. return;
  19300. }
  19301. }
  19302. catch (e) {
  19303. if (onerror) {
  19304. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19305. }
  19306. scene._removePendingData(loadingToken);
  19307. return;
  19308. }
  19309. if (onsuccess) {
  19310. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19311. onsuccess(meshes, particleSystems, skeletons);
  19312. scene._removePendingData(loadingToken);
  19313. }
  19314. };
  19315. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19316. // Direct load
  19317. importMeshFromData(sceneFilename.substr(5));
  19318. return;
  19319. }
  19320. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19321. importMeshFromData(data);
  19322. }, progressCallBack, database);
  19323. };
  19324. if (scene.getEngine().enableOfflineSupport) {
  19325. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19326. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19327. }
  19328. else {
  19329. manifestChecked(true);
  19330. }
  19331. };
  19332. /**
  19333. * Load a scene
  19334. * @param rootUrl a string that defines the root url for scene and resources
  19335. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19336. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19337. */
  19338. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19339. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19340. };
  19341. /**
  19342. * Append a scene
  19343. * @param rootUrl a string that defines the root url for scene and resources
  19344. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19345. * @param scene is the instance of BABYLON.Scene to append to
  19346. */
  19347. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19348. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19349. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19350. return;
  19351. }
  19352. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19353. var database;
  19354. var loadingToken = {};
  19355. scene._addPendingData(loadingToken);
  19356. if (SceneLoader.ShowLoadingScreen) {
  19357. scene.getEngine().displayLoadingUI();
  19358. }
  19359. var loadSceneFromData = function (data) {
  19360. scene.database = database;
  19361. if (!plugin.load(scene, data, rootUrl)) {
  19362. if (onerror) {
  19363. onerror(scene);
  19364. }
  19365. scene._removePendingData(loadingToken);
  19366. scene.getEngine().hideLoadingUI();
  19367. return;
  19368. }
  19369. if (onsuccess) {
  19370. onsuccess(scene);
  19371. }
  19372. scene._removePendingData(loadingToken);
  19373. if (SceneLoader.ShowLoadingScreen) {
  19374. scene.executeWhenReady(function () {
  19375. scene.getEngine().hideLoadingUI();
  19376. });
  19377. }
  19378. };
  19379. var manifestChecked = function (success) {
  19380. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19381. };
  19382. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19383. // Direct load
  19384. loadSceneFromData(sceneFilename.substr(5));
  19385. return;
  19386. }
  19387. if (rootUrl.indexOf("file:") === -1) {
  19388. if (scene.getEngine().enableOfflineSupport) {
  19389. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19390. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19391. }
  19392. else {
  19393. manifestChecked(true);
  19394. }
  19395. }
  19396. else {
  19397. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19398. }
  19399. };
  19400. // Flags
  19401. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19402. SceneLoader._ShowLoadingScreen = true;
  19403. // Members
  19404. SceneLoader._registeredPlugins = new Array();
  19405. return SceneLoader;
  19406. })();
  19407. BABYLON.SceneLoader = SceneLoader;
  19408. ;
  19409. })(BABYLON || (BABYLON = {}));
  19410. var BABYLON;
  19411. (function (BABYLON) {
  19412. var Internals;
  19413. (function (Internals) {
  19414. var checkColors4 = function (colors, count) {
  19415. // Check if color3 was used
  19416. if (colors.length === count * 3) {
  19417. var colors4 = [];
  19418. for (var index = 0; index < colors.length; index += 3) {
  19419. var newIndex = (index / 3) * 4;
  19420. colors4[newIndex] = colors[index];
  19421. colors4[newIndex + 1] = colors[index + 1];
  19422. colors4[newIndex + 2] = colors[index + 2];
  19423. colors4[newIndex + 3] = 1.0;
  19424. }
  19425. return colors4;
  19426. }
  19427. return colors;
  19428. };
  19429. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19430. var texture = null;
  19431. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19432. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19433. texture.name = parsedTexture.name;
  19434. texture.hasAlpha = parsedTexture.hasAlpha;
  19435. texture.level = parsedTexture.level;
  19436. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19437. }
  19438. return texture;
  19439. };
  19440. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19441. if (parsedTexture.isCube) {
  19442. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19443. }
  19444. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19445. return null;
  19446. }
  19447. var texture;
  19448. if (parsedTexture.mirrorPlane) {
  19449. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19450. texture._waitingRenderList = parsedTexture.renderList;
  19451. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19452. }
  19453. else if (parsedTexture.isRenderTarget) {
  19454. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19455. texture._waitingRenderList = parsedTexture.renderList;
  19456. }
  19457. else {
  19458. if (parsedTexture.base64String) {
  19459. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19460. }
  19461. else {
  19462. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19463. }
  19464. }
  19465. texture.name = parsedTexture.name;
  19466. texture.hasAlpha = parsedTexture.hasAlpha;
  19467. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19468. texture.level = parsedTexture.level;
  19469. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19470. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19471. texture.uOffset = parsedTexture.uOffset;
  19472. texture.vOffset = parsedTexture.vOffset;
  19473. texture.uScale = parsedTexture.uScale;
  19474. texture.vScale = parsedTexture.vScale;
  19475. texture.uAng = parsedTexture.uAng;
  19476. texture.vAng = parsedTexture.vAng;
  19477. texture.wAng = parsedTexture.wAng;
  19478. texture.wrapU = parsedTexture.wrapU;
  19479. texture.wrapV = parsedTexture.wrapV;
  19480. // Animations
  19481. if (parsedTexture.animations) {
  19482. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19483. var parsedAnimation = parsedTexture.animations[animationIndex];
  19484. texture.animations.push(parseAnimation(parsedAnimation));
  19485. }
  19486. }
  19487. return texture;
  19488. };
  19489. var parseSkeleton = function (parsedSkeleton, scene) {
  19490. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19491. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19492. var parsedBone = parsedSkeleton.bones[index];
  19493. var parentBone = null;
  19494. if (parsedBone.parentBoneIndex > -1) {
  19495. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19496. }
  19497. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19498. if (parsedBone.animation) {
  19499. bone.animations.push(parseAnimation(parsedBone.animation));
  19500. }
  19501. }
  19502. return skeleton;
  19503. };
  19504. var parseFresnelParameters = function (parsedFresnelParameters) {
  19505. var fresnelParameters = new BABYLON.FresnelParameters();
  19506. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19507. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19508. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19509. fresnelParameters.bias = parsedFresnelParameters.bias;
  19510. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19511. return fresnelParameters;
  19512. };
  19513. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19514. var material;
  19515. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19516. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19517. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19518. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19519. material.specularPower = parsedMaterial.specularPower;
  19520. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19521. material.alpha = parsedMaterial.alpha;
  19522. material.id = parsedMaterial.id;
  19523. if (parsedMaterial.disableDepthWrite) {
  19524. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19525. }
  19526. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19527. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19528. material.wireframe = parsedMaterial.wireframe;
  19529. if (parsedMaterial.diffuseTexture) {
  19530. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19531. }
  19532. if (parsedMaterial.diffuseFresnelParameters) {
  19533. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19534. }
  19535. if (parsedMaterial.ambientTexture) {
  19536. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19537. }
  19538. if (parsedMaterial.opacityTexture) {
  19539. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19540. }
  19541. if (parsedMaterial.opacityFresnelParameters) {
  19542. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19543. }
  19544. if (parsedMaterial.reflectionTexture) {
  19545. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19546. }
  19547. if (parsedMaterial.reflectionFresnelParameters) {
  19548. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19549. }
  19550. if (parsedMaterial.emissiveTexture) {
  19551. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19552. }
  19553. if (parsedMaterial.emissiveFresnelParameters) {
  19554. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19555. }
  19556. if (parsedMaterial.specularTexture) {
  19557. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19558. }
  19559. if (parsedMaterial.bumpTexture) {
  19560. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19561. }
  19562. if (parsedMaterial.checkReadyOnlyOnce) {
  19563. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19564. }
  19565. return material;
  19566. };
  19567. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19568. for (var index = 0; index < parsedData.materials.length; index++) {
  19569. var parsedMaterial = parsedData.materials[index];
  19570. if (parsedMaterial.id === id) {
  19571. return parseMaterial(parsedMaterial, scene, rootUrl);
  19572. }
  19573. }
  19574. return null;
  19575. };
  19576. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19577. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19578. multiMaterial.id = parsedMultiMaterial.id;
  19579. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19580. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19581. var subMatId = parsedMultiMaterial.materials[matIndex];
  19582. if (subMatId) {
  19583. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19584. }
  19585. else {
  19586. multiMaterial.subMaterials.push(null);
  19587. }
  19588. }
  19589. return multiMaterial;
  19590. };
  19591. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19592. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19593. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19594. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19595. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19596. var parsedFlare = parsedLensFlareSystem.flares[index];
  19597. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19598. }
  19599. return lensFlareSystem;
  19600. };
  19601. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19602. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19603. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19604. if (parsedParticleSystem.textureName) {
  19605. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19606. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19607. }
  19608. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19609. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19610. particleSystem.minSize = parsedParticleSystem.minSize;
  19611. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19612. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19613. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19614. particleSystem.emitter = emitter;
  19615. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19616. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19617. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19618. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19619. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19620. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19621. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19622. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19623. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19624. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19625. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19626. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19627. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19628. particleSystem.start();
  19629. return particleSystem;
  19630. };
  19631. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19632. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19633. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19634. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19635. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19636. shadowGenerator.getShadowMap().renderList.push(mesh);
  19637. }
  19638. if (parsedShadowGenerator.usePoissonSampling) {
  19639. shadowGenerator.usePoissonSampling = true;
  19640. }
  19641. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19642. shadowGenerator.useVarianceShadowMap = true;
  19643. }
  19644. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19645. shadowGenerator.useBlurVarianceShadowMap = true;
  19646. if (parsedShadowGenerator.blurScale) {
  19647. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19648. }
  19649. if (parsedShadowGenerator.blurBoxOffset) {
  19650. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19651. }
  19652. }
  19653. if (parsedShadowGenerator.bias !== undefined) {
  19654. shadowGenerator.bias = parsedShadowGenerator.bias;
  19655. }
  19656. return shadowGenerator;
  19657. };
  19658. var parseAnimation = function (parsedAnimation) {
  19659. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19660. var dataType = parsedAnimation.dataType;
  19661. var keys = [];
  19662. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19663. var key = parsedAnimation.keys[index];
  19664. var data;
  19665. switch (dataType) {
  19666. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19667. data = key.values[0];
  19668. break;
  19669. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19670. data = BABYLON.Quaternion.FromArray(key.values);
  19671. break;
  19672. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19673. data = BABYLON.Matrix.FromArray(key.values);
  19674. break;
  19675. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19676. default:
  19677. data = BABYLON.Vector3.FromArray(key.values);
  19678. break;
  19679. }
  19680. keys.push({
  19681. frame: key.frame,
  19682. value: data
  19683. });
  19684. }
  19685. animation.setKeys(keys);
  19686. return animation;
  19687. };
  19688. var parseLight = function (parsedLight, scene) {
  19689. var light;
  19690. switch (parsedLight.type) {
  19691. case 0:
  19692. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19693. break;
  19694. case 1:
  19695. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19696. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19697. break;
  19698. case 2:
  19699. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19700. break;
  19701. case 3:
  19702. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19703. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19704. break;
  19705. }
  19706. light.id = parsedLight.id;
  19707. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19708. if (parsedLight.intensity !== undefined) {
  19709. light.intensity = parsedLight.intensity;
  19710. }
  19711. if (parsedLight.range) {
  19712. light.range = parsedLight.range;
  19713. }
  19714. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19715. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19716. if (parsedLight.excludedMeshesIds) {
  19717. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19718. }
  19719. // Parent
  19720. if (parsedLight.parentId) {
  19721. light._waitingParentId = parsedLight.parentId;
  19722. }
  19723. if (parsedLight.includedOnlyMeshesIds) {
  19724. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19725. }
  19726. // Animations
  19727. if (parsedLight.animations) {
  19728. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19729. var parsedAnimation = parsedLight.animations[animationIndex];
  19730. light.animations.push(parseAnimation(parsedAnimation));
  19731. }
  19732. }
  19733. if (parsedLight.autoAnimate) {
  19734. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19735. }
  19736. };
  19737. var parseCamera = function (parsedCamera, scene) {
  19738. var camera;
  19739. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19740. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19741. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19742. var alpha = parsedCamera.alpha;
  19743. var beta = parsedCamera.beta;
  19744. var radius = parsedCamera.radius;
  19745. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19746. var interaxial_distance = parsedCamera.interaxial_distance;
  19747. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19748. }
  19749. else {
  19750. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19751. }
  19752. }
  19753. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19754. interaxial_distance = parsedCamera.interaxial_distance;
  19755. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19756. }
  19757. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19758. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19759. }
  19760. else if (parsedCamera.type === "FollowCamera") {
  19761. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19762. camera.heightOffset = parsedCamera.heightOffset;
  19763. camera.radius = parsedCamera.radius;
  19764. camera.rotationOffset = parsedCamera.rotationOffset;
  19765. if (lockedTargetMesh)
  19766. camera.target = lockedTargetMesh;
  19767. }
  19768. else if (parsedCamera.type === "GamepadCamera") {
  19769. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19770. }
  19771. else if (parsedCamera.type === "TouchCamera") {
  19772. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19773. }
  19774. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19775. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19776. }
  19777. else if (parsedCamera.type === "WebVRFreeCamera") {
  19778. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19779. }
  19780. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19781. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19782. }
  19783. else {
  19784. // Free Camera is the default value
  19785. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19786. }
  19787. // apply 3d rig, when found
  19788. if (parsedCamera.cameraRigMode) {
  19789. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19790. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19791. }
  19792. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19793. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19794. camera.lockedTarget = lockedTargetMesh;
  19795. }
  19796. camera.id = parsedCamera.id;
  19797. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19798. // Parent
  19799. if (parsedCamera.parentId) {
  19800. camera._waitingParentId = parsedCamera.parentId;
  19801. }
  19802. // Target
  19803. if (parsedCamera.target) {
  19804. if (camera.setTarget) {
  19805. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19806. }
  19807. else {
  19808. //For ArcRotate
  19809. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19810. }
  19811. }
  19812. else {
  19813. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19814. }
  19815. camera.fov = parsedCamera.fov;
  19816. camera.minZ = parsedCamera.minZ;
  19817. camera.maxZ = parsedCamera.maxZ;
  19818. camera.speed = parsedCamera.speed;
  19819. camera.inertia = parsedCamera.inertia;
  19820. camera.checkCollisions = parsedCamera.checkCollisions;
  19821. camera.applyGravity = parsedCamera.applyGravity;
  19822. if (parsedCamera.ellipsoid) {
  19823. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19824. }
  19825. // Animations
  19826. if (parsedCamera.animations) {
  19827. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19828. var parsedAnimation = parsedCamera.animations[animationIndex];
  19829. camera.animations.push(parseAnimation(parsedAnimation));
  19830. }
  19831. }
  19832. if (parsedCamera.autoAnimate) {
  19833. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19834. }
  19835. // Layer Mask
  19836. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19837. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19838. }
  19839. else {
  19840. camera.layerMask = 0x0FFFFFFF;
  19841. }
  19842. return camera;
  19843. };
  19844. var parseGeometry = function (parsedGeometry, scene) {
  19845. var id = parsedGeometry.id;
  19846. return scene.getGeometryByID(id);
  19847. };
  19848. var parseBox = function (parsedBox, scene) {
  19849. if (parseGeometry(parsedBox, scene)) {
  19850. return null; // null since geometry could be something else than a box...
  19851. }
  19852. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19853. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19854. scene.pushGeometry(box, true);
  19855. return box;
  19856. };
  19857. var parseSphere = function (parsedSphere, scene) {
  19858. if (parseGeometry(parsedSphere, scene)) {
  19859. return null; // null since geometry could be something else than a sphere...
  19860. }
  19861. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19862. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19863. scene.pushGeometry(sphere, true);
  19864. return sphere;
  19865. };
  19866. var parseCylinder = function (parsedCylinder, scene) {
  19867. if (parseGeometry(parsedCylinder, scene)) {
  19868. return null; // null since geometry could be something else than a cylinder...
  19869. }
  19870. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19871. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19872. scene.pushGeometry(cylinder, true);
  19873. return cylinder;
  19874. };
  19875. var parseTorus = function (parsedTorus, scene) {
  19876. if (parseGeometry(parsedTorus, scene)) {
  19877. return null; // null since geometry could be something else than a torus...
  19878. }
  19879. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19880. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19881. scene.pushGeometry(torus, true);
  19882. return torus;
  19883. };
  19884. var parseGround = function (parsedGround, scene) {
  19885. if (parseGeometry(parsedGround, scene)) {
  19886. return null; // null since geometry could be something else than a ground...
  19887. }
  19888. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19889. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19890. scene.pushGeometry(ground, true);
  19891. return ground;
  19892. };
  19893. var parsePlane = function (parsedPlane, scene) {
  19894. if (parseGeometry(parsedPlane, scene)) {
  19895. return null; // null since geometry could be something else than a plane...
  19896. }
  19897. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19898. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19899. scene.pushGeometry(plane, true);
  19900. return plane;
  19901. };
  19902. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19903. if (parseGeometry(parsedTorusKnot, scene)) {
  19904. return null; // null since geometry could be something else than a torusKnot...
  19905. }
  19906. 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);
  19907. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19908. scene.pushGeometry(torusKnot, true);
  19909. return torusKnot;
  19910. };
  19911. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19912. if (parseGeometry(parsedVertexData, scene)) {
  19913. return null; // null since geometry could be a primitive
  19914. }
  19915. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19916. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19917. if (parsedVertexData.delayLoadingFile) {
  19918. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19919. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19920. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19921. geometry._delayInfo = [];
  19922. if (parsedVertexData.hasUVs) {
  19923. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19924. }
  19925. if (parsedVertexData.hasUVs2) {
  19926. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19927. }
  19928. if (parsedVertexData.hasUVs3) {
  19929. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19930. }
  19931. if (parsedVertexData.hasUVs4) {
  19932. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19933. }
  19934. if (parsedVertexData.hasUVs5) {
  19935. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19936. }
  19937. if (parsedVertexData.hasUVs6) {
  19938. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19939. }
  19940. if (parsedVertexData.hasColors) {
  19941. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19942. }
  19943. if (parsedVertexData.hasMatricesIndices) {
  19944. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19945. }
  19946. if (parsedVertexData.hasMatricesWeights) {
  19947. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19948. }
  19949. geometry._delayLoadingFunction = importVertexData;
  19950. }
  19951. else {
  19952. importVertexData(parsedVertexData, geometry);
  19953. }
  19954. scene.pushGeometry(geometry, true);
  19955. return geometry;
  19956. };
  19957. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19958. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19959. mesh.id = parsedMesh.id;
  19960. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19961. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19962. if (parsedMesh.rotationQuaternion) {
  19963. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19964. }
  19965. else if (parsedMesh.rotation) {
  19966. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19967. }
  19968. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19969. if (parsedMesh.localMatrix) {
  19970. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19971. }
  19972. else if (parsedMesh.pivotMatrix) {
  19973. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19974. }
  19975. mesh.setEnabled(parsedMesh.isEnabled);
  19976. mesh.isVisible = parsedMesh.isVisible;
  19977. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19978. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19979. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19980. if (parsedMesh.applyFog !== undefined) {
  19981. mesh.applyFog = parsedMesh.applyFog;
  19982. }
  19983. if (parsedMesh.pickable !== undefined) {
  19984. mesh.isPickable = parsedMesh.pickable;
  19985. }
  19986. if (parsedMesh.alphaIndex !== undefined) {
  19987. mesh.alphaIndex = parsedMesh.alphaIndex;
  19988. }
  19989. mesh.receiveShadows = parsedMesh.receiveShadows;
  19990. mesh.billboardMode = parsedMesh.billboardMode;
  19991. if (parsedMesh.visibility !== undefined) {
  19992. mesh.visibility = parsedMesh.visibility;
  19993. }
  19994. mesh.checkCollisions = parsedMesh.checkCollisions;
  19995. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19996. // freezeWorldMatrix
  19997. if (parsedMesh.freezeWorldMatrix) {
  19998. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  19999. }
  20000. // Parent
  20001. if (parsedMesh.parentId) {
  20002. mesh._waitingParentId = parsedMesh.parentId;
  20003. }
  20004. // Actions
  20005. if (parsedMesh.actions !== undefined) {
  20006. mesh._waitingActions = parsedMesh.actions;
  20007. }
  20008. // Geometry
  20009. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20010. if (parsedMesh.delayLoadingFile) {
  20011. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20012. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20013. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20014. if (parsedMesh._binaryInfo) {
  20015. mesh._binaryInfo = parsedMesh._binaryInfo;
  20016. }
  20017. mesh._delayInfo = [];
  20018. if (parsedMesh.hasUVs) {
  20019. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20020. }
  20021. if (parsedMesh.hasUVs2) {
  20022. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20023. }
  20024. if (parsedMesh.hasUVs3) {
  20025. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20026. }
  20027. if (parsedMesh.hasUVs4) {
  20028. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20029. }
  20030. if (parsedMesh.hasUVs5) {
  20031. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20032. }
  20033. if (parsedMesh.hasUVs6) {
  20034. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20035. }
  20036. if (parsedMesh.hasColors) {
  20037. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20038. }
  20039. if (parsedMesh.hasMatricesIndices) {
  20040. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20041. }
  20042. if (parsedMesh.hasMatricesWeights) {
  20043. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20044. }
  20045. mesh._delayLoadingFunction = importGeometry;
  20046. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20047. mesh._checkDelayState();
  20048. }
  20049. }
  20050. else {
  20051. importGeometry(parsedMesh, mesh);
  20052. }
  20053. // Material
  20054. if (parsedMesh.materialId) {
  20055. mesh.setMaterialByID(parsedMesh.materialId);
  20056. }
  20057. else {
  20058. mesh.material = null;
  20059. }
  20060. // Skeleton
  20061. if (parsedMesh.skeletonId > -1) {
  20062. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20063. }
  20064. // Physics
  20065. if (parsedMesh.physicsImpostor) {
  20066. if (!scene.isPhysicsEnabled()) {
  20067. scene.enablePhysics();
  20068. }
  20069. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20070. }
  20071. // Animations
  20072. if (parsedMesh.animations) {
  20073. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20074. var parsedAnimation = parsedMesh.animations[animationIndex];
  20075. mesh.animations.push(parseAnimation(parsedAnimation));
  20076. }
  20077. }
  20078. if (parsedMesh.autoAnimate) {
  20079. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20080. }
  20081. // Layer Mask
  20082. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20083. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20084. }
  20085. else {
  20086. mesh.layerMask = 0x0FFFFFFF;
  20087. }
  20088. // Instances
  20089. if (parsedMesh.instances) {
  20090. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20091. var parsedInstance = parsedMesh.instances[index];
  20092. var instance = mesh.createInstance(parsedInstance.name);
  20093. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20094. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20095. if (parsedInstance.rotationQuaternion) {
  20096. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20097. }
  20098. else if (parsedInstance.rotation) {
  20099. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20100. }
  20101. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20102. instance.checkCollisions = mesh.checkCollisions;
  20103. if (parsedMesh.animations) {
  20104. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20105. parsedAnimation = parsedMesh.animations[animationIndex];
  20106. instance.animations.push(parseAnimation(parsedAnimation));
  20107. }
  20108. }
  20109. }
  20110. }
  20111. return mesh;
  20112. };
  20113. var parseActions = function (parsedActions, object, scene) {
  20114. var actionManager = new BABYLON.ActionManager(scene);
  20115. if (object === null)
  20116. scene.actionManager = actionManager;
  20117. else
  20118. object.actionManager = actionManager;
  20119. // instanciate a new object
  20120. var instanciate = function (name, params) {
  20121. var newInstance = Object.create(BABYLON[name].prototype);
  20122. newInstance.constructor.apply(newInstance, params);
  20123. return newInstance;
  20124. };
  20125. var parseParameter = function (name, value, target, propertyPath) {
  20126. if (propertyPath === null) {
  20127. // String, boolean or float
  20128. var floatValue = parseFloat(value);
  20129. if (value === "true" || value === "false")
  20130. return value === "true";
  20131. else
  20132. return isNaN(floatValue) ? value : floatValue;
  20133. }
  20134. var effectiveTarget = propertyPath.split(".");
  20135. var values = value.split(",");
  20136. // Get effective Target
  20137. for (var i = 0; i < effectiveTarget.length; i++) {
  20138. target = target[effectiveTarget[i]];
  20139. }
  20140. // Return appropriate value with its type
  20141. if (typeof (target) === "boolean")
  20142. return values[0] === "true";
  20143. if (typeof (target) === "string")
  20144. return values[0];
  20145. // Parameters with multiple values such as Vector3 etc.
  20146. var split = new Array();
  20147. for (var i = 0; i < values.length; i++)
  20148. split.push(parseFloat(values[i]));
  20149. if (target instanceof BABYLON.Vector3)
  20150. return BABYLON.Vector3.FromArray(split);
  20151. if (target instanceof BABYLON.Vector4)
  20152. return BABYLON.Vector4.FromArray(split);
  20153. if (target instanceof BABYLON.Color3)
  20154. return BABYLON.Color3.FromArray(split);
  20155. if (target instanceof BABYLON.Color4)
  20156. return BABYLON.Color4.FromArray(split);
  20157. return parseFloat(values[0]);
  20158. };
  20159. // traverse graph per trigger
  20160. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20161. if (combineArray === void 0) { combineArray = null; }
  20162. if (parsedAction.detached)
  20163. return;
  20164. var parameters = new Array();
  20165. var target = null;
  20166. var propertyPath = null;
  20167. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20168. // Parameters
  20169. if (parsedAction.type === 2)
  20170. parameters.push(actionManager);
  20171. else
  20172. parameters.push(trigger);
  20173. if (combine) {
  20174. var actions = new Array();
  20175. for (var j = 0; j < parsedAction.combine.length; j++) {
  20176. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20177. }
  20178. parameters.push(actions);
  20179. }
  20180. else {
  20181. for (var i = 0; i < parsedAction.properties.length; i++) {
  20182. var value = parsedAction.properties[i].value;
  20183. var name = parsedAction.properties[i].name;
  20184. var targetType = parsedAction.properties[i].targetType;
  20185. if (name === "target")
  20186. if (targetType !== null && targetType === "SceneProperties")
  20187. value = target = scene;
  20188. else
  20189. value = target = scene.getNodeByName(value);
  20190. else if (name === "parent")
  20191. value = scene.getNodeByName(value);
  20192. else if (name === "sound")
  20193. value = scene.getSoundByName(value);
  20194. else if (name !== "propertyPath") {
  20195. if (parsedAction.type === 2 && name === "operator")
  20196. value = BABYLON.ValueCondition[value];
  20197. else
  20198. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20199. }
  20200. else {
  20201. propertyPath = value;
  20202. }
  20203. parameters.push(value);
  20204. }
  20205. }
  20206. if (combineArray === null) {
  20207. parameters.push(condition);
  20208. }
  20209. else {
  20210. parameters.push(null);
  20211. }
  20212. // If interpolate value action
  20213. if (parsedAction.name === "InterpolateValueAction") {
  20214. var param = parameters[parameters.length - 2];
  20215. parameters[parameters.length - 1] = param;
  20216. parameters[parameters.length - 2] = condition;
  20217. }
  20218. // Action or condition(s) and not CombineAction
  20219. var newAction = instanciate(parsedAction.name, parameters);
  20220. if (combineArray === null) {
  20221. if (newAction instanceof BABYLON.Condition) {
  20222. condition = newAction;
  20223. newAction = action;
  20224. }
  20225. else {
  20226. condition = null;
  20227. if (action)
  20228. action.then(newAction);
  20229. else
  20230. actionManager.registerAction(newAction);
  20231. }
  20232. }
  20233. else {
  20234. combineArray.push(newAction);
  20235. }
  20236. for (var i = 0; i < parsedAction.children.length; i++)
  20237. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20238. };
  20239. // triggers
  20240. for (var i = 0; i < parsedActions.children.length; i++) {
  20241. var triggerParams;
  20242. var trigger = parsedActions.children[i];
  20243. if (trigger.properties.length > 0) {
  20244. var param = trigger.properties[0].value;
  20245. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20246. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20247. }
  20248. else
  20249. triggerParams = BABYLON.ActionManager[trigger.name];
  20250. for (var j = 0; j < trigger.children.length; j++) {
  20251. if (!trigger.detached)
  20252. traverse(trigger.children[j], triggerParams, null, null);
  20253. }
  20254. }
  20255. };
  20256. var parseSound = function (parsedSound, scene, rootUrl) {
  20257. var soundName = parsedSound.name;
  20258. var soundUrl = rootUrl + soundName;
  20259. var options = {
  20260. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20261. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20262. rolloffFactor: parsedSound.rolloffFactor,
  20263. refDistance: parsedSound.refDistance,
  20264. distanceModel: parsedSound.distanceModel,
  20265. playbackRate: parsedSound.playbackRate
  20266. };
  20267. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20268. scene._addPendingData(newSound);
  20269. if (parsedSound.position) {
  20270. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20271. newSound.setPosition(soundPosition);
  20272. }
  20273. if (parsedSound.isDirectional) {
  20274. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20275. if (parsedSound.localDirectionToMesh) {
  20276. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20277. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20278. }
  20279. }
  20280. if (parsedSound.connectedMeshId) {
  20281. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20282. if (connectedMesh) {
  20283. newSound.attachToMesh(connectedMesh);
  20284. }
  20285. }
  20286. };
  20287. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20288. names = (names instanceof Array) ? names : [names];
  20289. for (var i in names) {
  20290. if (mesh.name === names[i]) {
  20291. hierarchyIds.push(mesh.id);
  20292. return true;
  20293. }
  20294. }
  20295. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20296. hierarchyIds.push(mesh.id);
  20297. return true;
  20298. }
  20299. return false;
  20300. };
  20301. var importVertexData = function (parsedVertexData, geometry) {
  20302. var vertexData = new BABYLON.VertexData();
  20303. // positions
  20304. var positions = parsedVertexData.positions;
  20305. if (positions) {
  20306. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20307. }
  20308. // normals
  20309. var normals = parsedVertexData.normals;
  20310. if (normals) {
  20311. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20312. }
  20313. // uvs
  20314. var uvs = parsedVertexData.uvs;
  20315. if (uvs) {
  20316. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20317. }
  20318. // uv2s
  20319. var uv2s = parsedVertexData.uv2s;
  20320. if (uv2s) {
  20321. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20322. }
  20323. // uv3s
  20324. var uv3s = parsedVertexData.uv3s;
  20325. if (uv3s) {
  20326. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20327. }
  20328. // uv4s
  20329. var uv4s = parsedVertexData.uv4s;
  20330. if (uv4s) {
  20331. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20332. }
  20333. // uv5s
  20334. var uv5s = parsedVertexData.uv5s;
  20335. if (uv5s) {
  20336. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20337. }
  20338. // uv6s
  20339. var uv6s = parsedVertexData.uv6s;
  20340. if (uv6s) {
  20341. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20342. }
  20343. // colors
  20344. var colors = parsedVertexData.colors;
  20345. if (colors) {
  20346. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20347. }
  20348. // matricesIndices
  20349. var matricesIndices = parsedVertexData.matricesIndices;
  20350. if (matricesIndices) {
  20351. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20352. }
  20353. // matricesWeights
  20354. var matricesWeights = parsedVertexData.matricesWeights;
  20355. if (matricesWeights) {
  20356. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20357. }
  20358. // indices
  20359. var indices = parsedVertexData.indices;
  20360. if (indices) {
  20361. vertexData.indices = indices;
  20362. }
  20363. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20364. };
  20365. var importGeometry = function (parsedGeometry, mesh) {
  20366. var scene = mesh.getScene();
  20367. // Geometry
  20368. var geometryId = parsedGeometry.geometryId;
  20369. if (geometryId) {
  20370. var geometry = scene.getGeometryByID(geometryId);
  20371. if (geometry) {
  20372. geometry.applyToMesh(mesh);
  20373. }
  20374. }
  20375. else if (parsedGeometry instanceof ArrayBuffer) {
  20376. var binaryInfo = mesh._binaryInfo;
  20377. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20378. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20379. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20380. }
  20381. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20382. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20383. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20384. }
  20385. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20386. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20387. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20388. }
  20389. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20390. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20391. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20392. }
  20393. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20394. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20395. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20396. }
  20397. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20398. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20399. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20400. }
  20401. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20402. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20403. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20404. }
  20405. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20406. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20407. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20408. }
  20409. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20410. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20411. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20412. }
  20413. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20414. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20415. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20416. }
  20417. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20418. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20419. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20420. }
  20421. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20422. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20423. mesh.setIndices(indicesData);
  20424. }
  20425. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20426. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20427. mesh.subMeshes = [];
  20428. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20429. var materialIndex = subMeshesData[(i * 5) + 0];
  20430. var verticesStart = subMeshesData[(i * 5) + 1];
  20431. var verticesCount = subMeshesData[(i * 5) + 2];
  20432. var indexStart = subMeshesData[(i * 5) + 3];
  20433. var indexCount = subMeshesData[(i * 5) + 4];
  20434. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20435. }
  20436. }
  20437. }
  20438. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20439. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20440. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20441. if (parsedGeometry.uvs) {
  20442. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20443. }
  20444. if (parsedGeometry.uvs2) {
  20445. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20446. }
  20447. if (parsedGeometry.uvs3) {
  20448. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20449. }
  20450. if (parsedGeometry.uvs4) {
  20451. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20452. }
  20453. if (parsedGeometry.uvs5) {
  20454. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20455. }
  20456. if (parsedGeometry.uvs6) {
  20457. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20458. }
  20459. if (parsedGeometry.colors) {
  20460. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20461. }
  20462. if (parsedGeometry.matricesIndices) {
  20463. if (!parsedGeometry.matricesIndices._isExpanded) {
  20464. var floatIndices = [];
  20465. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20466. var matricesIndex = parsedGeometry.matricesIndices[i];
  20467. floatIndices.push(matricesIndex & 0x000000FF);
  20468. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20469. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20470. floatIndices.push(matricesIndex >> 24);
  20471. }
  20472. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20473. }
  20474. else {
  20475. delete parsedGeometry.matricesIndices._isExpanded;
  20476. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20477. }
  20478. }
  20479. if (parsedGeometry.matricesWeights) {
  20480. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20481. }
  20482. mesh.setIndices(parsedGeometry.indices);
  20483. }
  20484. // SubMeshes
  20485. if (parsedGeometry.subMeshes) {
  20486. mesh.subMeshes = [];
  20487. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20488. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20489. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20490. }
  20491. }
  20492. // Flat shading
  20493. if (mesh._shouldGenerateFlatShading) {
  20494. mesh.convertToFlatShadedMesh();
  20495. delete mesh._shouldGenerateFlatShading;
  20496. }
  20497. // Update
  20498. mesh.computeWorldMatrix(true);
  20499. // Octree
  20500. if (scene._selectionOctree) {
  20501. scene._selectionOctree.addMesh(mesh);
  20502. }
  20503. };
  20504. BABYLON.SceneLoader.RegisterPlugin({
  20505. extensions: ".babylon",
  20506. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20507. var parsedData = JSON.parse(data);
  20508. var loadedSkeletonsIds = [];
  20509. var loadedMaterialsIds = [];
  20510. var hierarchyIds = [];
  20511. for (var index = 0; index < parsedData.meshes.length; index++) {
  20512. var parsedMesh = parsedData.meshes[index];
  20513. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20514. if (meshesNames instanceof Array) {
  20515. // Remove found mesh name from list.
  20516. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20517. }
  20518. //Geometry?
  20519. if (parsedMesh.geometryId) {
  20520. //does the file contain geometries?
  20521. if (parsedData.geometries) {
  20522. //find the correct geometry and add it to the scene
  20523. var found = false;
  20524. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20525. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20526. return;
  20527. }
  20528. else {
  20529. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20530. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20531. switch (geometryType) {
  20532. case "boxes":
  20533. parseBox(parsedGeometryData, scene);
  20534. break;
  20535. case "spheres":
  20536. parseSphere(parsedGeometryData, scene);
  20537. break;
  20538. case "cylinders":
  20539. parseCylinder(parsedGeometryData, scene);
  20540. break;
  20541. case "toruses":
  20542. parseTorus(parsedGeometryData, scene);
  20543. break;
  20544. case "grounds":
  20545. parseGround(parsedGeometryData, scene);
  20546. break;
  20547. case "planes":
  20548. parsePlane(parsedGeometryData, scene);
  20549. break;
  20550. case "torusKnots":
  20551. parseTorusKnot(parsedGeometryData, scene);
  20552. break;
  20553. case "vertexData":
  20554. parseVertexData(parsedGeometryData, scene, rootUrl);
  20555. break;
  20556. }
  20557. found = true;
  20558. }
  20559. });
  20560. }
  20561. });
  20562. if (!found) {
  20563. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20564. }
  20565. }
  20566. }
  20567. // Material ?
  20568. if (parsedMesh.materialId) {
  20569. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20570. if (!materialFound && parsedData.multiMaterials) {
  20571. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20572. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20573. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20574. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20575. var subMatId = parsedMultiMaterial.materials[matIndex];
  20576. loadedMaterialsIds.push(subMatId);
  20577. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20578. }
  20579. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20580. parseMultiMaterial(parsedMultiMaterial, scene);
  20581. materialFound = true;
  20582. break;
  20583. }
  20584. }
  20585. }
  20586. if (!materialFound) {
  20587. loadedMaterialsIds.push(parsedMesh.materialId);
  20588. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20589. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20590. }
  20591. }
  20592. }
  20593. // Skeleton ?
  20594. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20595. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20596. if (!skeletonAlreadyLoaded) {
  20597. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20598. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20599. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20600. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20601. loadedSkeletonsIds.push(parsedSkeleton.id);
  20602. }
  20603. }
  20604. }
  20605. }
  20606. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20607. meshes.push(mesh);
  20608. }
  20609. }
  20610. // Connecting parents
  20611. for (index = 0; index < scene.meshes.length; index++) {
  20612. var currentMesh = scene.meshes[index];
  20613. if (currentMesh._waitingParentId) {
  20614. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20615. currentMesh._waitingParentId = undefined;
  20616. }
  20617. }
  20618. // freeze world matrix application
  20619. for (index = 0; index < scene.meshes.length; index++) {
  20620. var currentMesh = scene.meshes[index];
  20621. if (currentMesh._waitingFreezeWorldMatrix) {
  20622. currentMesh.freezeWorldMatrix();
  20623. currentMesh._waitingFreezeWorldMatrix = undefined;
  20624. }
  20625. }
  20626. // Particles
  20627. if (parsedData.particleSystems) {
  20628. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20629. var parsedParticleSystem = parsedData.particleSystems[index];
  20630. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20631. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20632. }
  20633. }
  20634. }
  20635. return true;
  20636. },
  20637. load: function (scene, data, rootUrl) {
  20638. var parsedData = JSON.parse(data);
  20639. // Scene
  20640. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20641. scene.autoClear = parsedData.autoClear;
  20642. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20643. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20644. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20645. // Fog
  20646. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20647. scene.fogMode = parsedData.fogMode;
  20648. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20649. scene.fogStart = parsedData.fogStart;
  20650. scene.fogEnd = parsedData.fogEnd;
  20651. scene.fogDensity = parsedData.fogDensity;
  20652. }
  20653. // Lights
  20654. for (var index = 0; index < parsedData.lights.length; index++) {
  20655. var parsedLight = parsedData.lights[index];
  20656. parseLight(parsedLight, scene);
  20657. }
  20658. // Materials
  20659. if (parsedData.materials) {
  20660. for (index = 0; index < parsedData.materials.length; index++) {
  20661. var parsedMaterial = parsedData.materials[index];
  20662. parseMaterial(parsedMaterial, scene, rootUrl);
  20663. }
  20664. }
  20665. if (parsedData.multiMaterials) {
  20666. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20667. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20668. parseMultiMaterial(parsedMultiMaterial, scene);
  20669. }
  20670. }
  20671. // Skeletons
  20672. if (parsedData.skeletons) {
  20673. for (index = 0; index < parsedData.skeletons.length; index++) {
  20674. var parsedSkeleton = parsedData.skeletons[index];
  20675. parseSkeleton(parsedSkeleton, scene);
  20676. }
  20677. }
  20678. // Geometries
  20679. var geometries = parsedData.geometries;
  20680. if (geometries) {
  20681. // Boxes
  20682. var boxes = geometries.boxes;
  20683. if (boxes) {
  20684. for (index = 0; index < boxes.length; index++) {
  20685. var parsedBox = boxes[index];
  20686. parseBox(parsedBox, scene);
  20687. }
  20688. }
  20689. // Spheres
  20690. var spheres = geometries.spheres;
  20691. if (spheres) {
  20692. for (index = 0; index < spheres.length; index++) {
  20693. var parsedSphere = spheres[index];
  20694. parseSphere(parsedSphere, scene);
  20695. }
  20696. }
  20697. // Cylinders
  20698. var cylinders = geometries.cylinders;
  20699. if (cylinders) {
  20700. for (index = 0; index < cylinders.length; index++) {
  20701. var parsedCylinder = cylinders[index];
  20702. parseCylinder(parsedCylinder, scene);
  20703. }
  20704. }
  20705. // Toruses
  20706. var toruses = geometries.toruses;
  20707. if (toruses) {
  20708. for (index = 0; index < toruses.length; index++) {
  20709. var parsedTorus = toruses[index];
  20710. parseTorus(parsedTorus, scene);
  20711. }
  20712. }
  20713. // Grounds
  20714. var grounds = geometries.grounds;
  20715. if (grounds) {
  20716. for (index = 0; index < grounds.length; index++) {
  20717. var parsedGround = grounds[index];
  20718. parseGround(parsedGround, scene);
  20719. }
  20720. }
  20721. // Planes
  20722. var planes = geometries.planes;
  20723. if (planes) {
  20724. for (index = 0; index < planes.length; index++) {
  20725. var parsedPlane = planes[index];
  20726. parsePlane(parsedPlane, scene);
  20727. }
  20728. }
  20729. // TorusKnots
  20730. var torusKnots = geometries.torusKnots;
  20731. if (torusKnots) {
  20732. for (index = 0; index < torusKnots.length; index++) {
  20733. var parsedTorusKnot = torusKnots[index];
  20734. parseTorusKnot(parsedTorusKnot, scene);
  20735. }
  20736. }
  20737. // VertexData
  20738. var vertexData = geometries.vertexData;
  20739. if (vertexData) {
  20740. for (index = 0; index < vertexData.length; index++) {
  20741. var parsedVertexData = vertexData[index];
  20742. parseVertexData(parsedVertexData, scene, rootUrl);
  20743. }
  20744. }
  20745. }
  20746. // Meshes
  20747. for (index = 0; index < parsedData.meshes.length; index++) {
  20748. var parsedMesh = parsedData.meshes[index];
  20749. parseMesh(parsedMesh, scene, rootUrl);
  20750. }
  20751. // Cameras
  20752. for (index = 0; index < parsedData.cameras.length; index++) {
  20753. var parsedCamera = parsedData.cameras[index];
  20754. parseCamera(parsedCamera, scene);
  20755. }
  20756. if (parsedData.activeCameraID) {
  20757. scene.setActiveCameraByID(parsedData.activeCameraID);
  20758. }
  20759. // Browsing all the graph to connect the dots
  20760. for (index = 0; index < scene.cameras.length; index++) {
  20761. var camera = scene.cameras[index];
  20762. if (camera._waitingParentId) {
  20763. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20764. camera._waitingParentId = undefined;
  20765. }
  20766. }
  20767. for (index = 0; index < scene.lights.length; index++) {
  20768. var light = scene.lights[index];
  20769. if (light._waitingParentId) {
  20770. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20771. light._waitingParentId = undefined;
  20772. }
  20773. }
  20774. // Sounds
  20775. if (parsedData.sounds) {
  20776. for (index = 0; index < parsedData.sounds.length; index++) {
  20777. var parsedSound = parsedData.sounds[index];
  20778. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20779. parseSound(parsedSound, scene, rootUrl);
  20780. }
  20781. else {
  20782. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20783. }
  20784. }
  20785. }
  20786. // Connect parents & children and parse actions
  20787. for (index = 0; index < scene.meshes.length; index++) {
  20788. var mesh = scene.meshes[index];
  20789. if (mesh._waitingParentId) {
  20790. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20791. mesh._waitingParentId = undefined;
  20792. }
  20793. if (mesh._waitingActions) {
  20794. parseActions(mesh._waitingActions, mesh, scene);
  20795. mesh._waitingActions = undefined;
  20796. }
  20797. }
  20798. // freeze world matrix application
  20799. for (index = 0; index < scene.meshes.length; index++) {
  20800. var currentMesh = scene.meshes[index];
  20801. if (currentMesh._waitingFreezeWorldMatrix) {
  20802. currentMesh.freezeWorldMatrix();
  20803. currentMesh._waitingFreezeWorldMatrix = undefined;
  20804. }
  20805. }
  20806. // Particles Systems
  20807. if (parsedData.particleSystems) {
  20808. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20809. var parsedParticleSystem = parsedData.particleSystems[index];
  20810. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20811. }
  20812. }
  20813. // Lens flares
  20814. if (parsedData.lensFlareSystems) {
  20815. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20816. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20817. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20818. }
  20819. }
  20820. // Shadows
  20821. if (parsedData.shadowGenerators) {
  20822. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20823. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20824. parseShadowGenerator(parsedShadowGenerator, scene);
  20825. }
  20826. }
  20827. // Actions (scene)
  20828. if (parsedData.actions) {
  20829. parseActions(parsedData.actions, null, scene);
  20830. }
  20831. // Finish
  20832. return true;
  20833. }
  20834. });
  20835. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20836. })(BABYLON || (BABYLON = {}));
  20837. var BABYLON;
  20838. (function (BABYLON) {
  20839. var SpriteManager = (function () {
  20840. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20842. this.name = name;
  20843. this.cellSize = cellSize;
  20844. this.sprites = new Array();
  20845. this.renderingGroupId = 0;
  20846. this.fogEnabled = true;
  20847. this._vertexDeclaration = [4, 4, 4, 4];
  20848. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20849. this._capacity = capacity;
  20850. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20851. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20852. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20853. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20854. this._scene = scene;
  20855. this._scene.spriteManagers.push(this);
  20856. // VBO
  20857. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20858. var indices = [];
  20859. var index = 0;
  20860. for (var count = 0; count < capacity; count++) {
  20861. indices.push(index);
  20862. indices.push(index + 1);
  20863. indices.push(index + 2);
  20864. indices.push(index);
  20865. indices.push(index + 2);
  20866. indices.push(index + 3);
  20867. index += 4;
  20868. }
  20869. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20870. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20871. // Effects
  20872. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20873. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20874. }
  20875. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20876. var arrayOffset = index * 16;
  20877. if (offsetX === 0)
  20878. offsetX = this._epsilon;
  20879. else if (offsetX === 1)
  20880. offsetX = 1 - this._epsilon;
  20881. if (offsetY === 0)
  20882. offsetY = this._epsilon;
  20883. else if (offsetY === 1)
  20884. offsetY = 1 - this._epsilon;
  20885. this._vertices[arrayOffset] = sprite.position.x;
  20886. this._vertices[arrayOffset + 1] = sprite.position.y;
  20887. this._vertices[arrayOffset + 2] = sprite.position.z;
  20888. this._vertices[arrayOffset + 3] = sprite.angle;
  20889. this._vertices[arrayOffset + 4] = sprite.width;
  20890. this._vertices[arrayOffset + 5] = sprite.height;
  20891. this._vertices[arrayOffset + 6] = offsetX;
  20892. this._vertices[arrayOffset + 7] = offsetY;
  20893. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20894. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20895. var offset = (sprite.cellIndex / rowSize) >> 0;
  20896. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20897. this._vertices[arrayOffset + 11] = offset;
  20898. // Color
  20899. this._vertices[arrayOffset + 12] = sprite.color.r;
  20900. this._vertices[arrayOffset + 13] = sprite.color.g;
  20901. this._vertices[arrayOffset + 14] = sprite.color.b;
  20902. this._vertices[arrayOffset + 15] = sprite.color.a;
  20903. };
  20904. SpriteManager.prototype.render = function () {
  20905. // Check
  20906. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20907. return;
  20908. var engine = this._scene.getEngine();
  20909. var baseSize = this._spriteTexture.getBaseSize();
  20910. // Sprites
  20911. var deltaTime = engine.getDeltaTime();
  20912. var max = Math.min(this._capacity, this.sprites.length);
  20913. var rowSize = baseSize.width / this.cellSize;
  20914. var offset = 0;
  20915. for (var index = 0; index < max; index++) {
  20916. var sprite = this.sprites[index];
  20917. if (!sprite) {
  20918. continue;
  20919. }
  20920. sprite._animate(deltaTime);
  20921. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20922. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20923. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20924. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20925. }
  20926. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20927. // Render
  20928. var effect = this._effectBase;
  20929. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20930. effect = this._effectFog;
  20931. }
  20932. engine.enableEffect(effect);
  20933. var viewMatrix = this._scene.getViewMatrix();
  20934. effect.setTexture("diffuseSampler", this._spriteTexture);
  20935. effect.setMatrix("view", viewMatrix);
  20936. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20937. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20938. // Fog
  20939. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20940. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20941. effect.setColor3("vFogColor", this._scene.fogColor);
  20942. }
  20943. // VBOs
  20944. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20945. // Draw order
  20946. engine.setDepthFunctionToLessOrEqual();
  20947. effect.setBool("alphaTest", true);
  20948. engine.setColorWrite(false);
  20949. engine.draw(true, 0, max * 6);
  20950. engine.setColorWrite(true);
  20951. effect.setBool("alphaTest", false);
  20952. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20953. engine.draw(true, 0, max * 6);
  20954. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20955. };
  20956. SpriteManager.prototype.dispose = function () {
  20957. if (this._vertexBuffer) {
  20958. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20959. this._vertexBuffer = null;
  20960. }
  20961. if (this._indexBuffer) {
  20962. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20963. this._indexBuffer = null;
  20964. }
  20965. if (this._spriteTexture) {
  20966. this._spriteTexture.dispose();
  20967. this._spriteTexture = null;
  20968. }
  20969. // Remove from scene
  20970. var index = this._scene.spriteManagers.indexOf(this);
  20971. this._scene.spriteManagers.splice(index, 1);
  20972. // Callback
  20973. if (this.onDispose) {
  20974. this.onDispose();
  20975. }
  20976. };
  20977. return SpriteManager;
  20978. })();
  20979. BABYLON.SpriteManager = SpriteManager;
  20980. })(BABYLON || (BABYLON = {}));
  20981. var BABYLON;
  20982. (function (BABYLON) {
  20983. var Sprite = (function () {
  20984. function Sprite(name, manager) {
  20985. this.name = name;
  20986. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20987. this.width = 1.0;
  20988. this.height = 1.0;
  20989. this.angle = 0;
  20990. this.cellIndex = 0;
  20991. this.invertU = 0;
  20992. this.invertV = 0;
  20993. this.animations = new Array();
  20994. this._animationStarted = false;
  20995. this._loopAnimation = false;
  20996. this._fromIndex = 0;
  20997. this._toIndex = 0;
  20998. this._delay = 0;
  20999. this._direction = 1;
  21000. this._frameCount = 0;
  21001. this._time = 0;
  21002. this._manager = manager;
  21003. this._manager.sprites.push(this);
  21004. this.position = BABYLON.Vector3.Zero();
  21005. }
  21006. Object.defineProperty(Sprite.prototype, "size", {
  21007. get: function () {
  21008. return this.width;
  21009. },
  21010. set: function (value) {
  21011. this.width = value;
  21012. this.height = value;
  21013. },
  21014. enumerable: true,
  21015. configurable: true
  21016. });
  21017. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21018. this._fromIndex = from;
  21019. this._toIndex = to;
  21020. this._loopAnimation = loop;
  21021. this._delay = delay;
  21022. this._animationStarted = true;
  21023. this._direction = from < to ? 1 : -1;
  21024. this.cellIndex = from;
  21025. this._time = 0;
  21026. };
  21027. Sprite.prototype.stopAnimation = function () {
  21028. this._animationStarted = false;
  21029. };
  21030. Sprite.prototype._animate = function (deltaTime) {
  21031. if (!this._animationStarted)
  21032. return;
  21033. this._time += deltaTime;
  21034. if (this._time > this._delay) {
  21035. this._time = this._time % this._delay;
  21036. this.cellIndex += this._direction;
  21037. if (this.cellIndex == this._toIndex) {
  21038. if (this._loopAnimation) {
  21039. this.cellIndex = this._fromIndex;
  21040. }
  21041. else {
  21042. this._animationStarted = false;
  21043. if (this.disposeWhenFinishedAnimating) {
  21044. this.dispose();
  21045. }
  21046. }
  21047. }
  21048. }
  21049. };
  21050. Sprite.prototype.dispose = function () {
  21051. for (var i = 0; i < this._manager.sprites.length; i++) {
  21052. if (this._manager.sprites[i] == this) {
  21053. this._manager.sprites.splice(i, 1);
  21054. }
  21055. }
  21056. };
  21057. return Sprite;
  21058. })();
  21059. BABYLON.Sprite = Sprite;
  21060. })(BABYLON || (BABYLON = {}));
  21061. var BABYLON;
  21062. (function (BABYLON) {
  21063. var Layer = (function () {
  21064. function Layer(name, imgUrl, scene, isBackground, color) {
  21065. this.name = name;
  21066. this._vertexDeclaration = [2];
  21067. this._vertexStrideSize = 2 * 4;
  21068. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21069. this.isBackground = isBackground === undefined ? true : isBackground;
  21070. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21071. this._scene = scene;
  21072. this._scene.layers.push(this);
  21073. // VBO
  21074. var vertices = [];
  21075. vertices.push(1, 1);
  21076. vertices.push(-1, 1);
  21077. vertices.push(-1, -1);
  21078. vertices.push(1, -1);
  21079. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21080. // Indices
  21081. var indices = [];
  21082. indices.push(0);
  21083. indices.push(1);
  21084. indices.push(2);
  21085. indices.push(0);
  21086. indices.push(2);
  21087. indices.push(3);
  21088. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21089. // Effects
  21090. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21091. }
  21092. Layer.prototype.render = function () {
  21093. // Check
  21094. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21095. return;
  21096. var engine = this._scene.getEngine();
  21097. // Render
  21098. engine.enableEffect(this._effect);
  21099. engine.setState(false);
  21100. // Texture
  21101. this._effect.setTexture("textureSampler", this.texture);
  21102. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21103. // Color
  21104. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21105. // VBOs
  21106. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21107. // Draw order
  21108. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21109. engine.draw(true, 0, 6);
  21110. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21111. };
  21112. Layer.prototype.dispose = function () {
  21113. if (this._vertexBuffer) {
  21114. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21115. this._vertexBuffer = null;
  21116. }
  21117. if (this._indexBuffer) {
  21118. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21119. this._indexBuffer = null;
  21120. }
  21121. if (this.texture) {
  21122. this.texture.dispose();
  21123. this.texture = null;
  21124. }
  21125. // Remove from scene
  21126. var index = this._scene.layers.indexOf(this);
  21127. this._scene.layers.splice(index, 1);
  21128. // Callback
  21129. if (this.onDispose) {
  21130. this.onDispose();
  21131. }
  21132. };
  21133. return Layer;
  21134. })();
  21135. BABYLON.Layer = Layer;
  21136. })(BABYLON || (BABYLON = {}));
  21137. var BABYLON;
  21138. (function (BABYLON) {
  21139. var Particle = (function () {
  21140. function Particle() {
  21141. this.position = BABYLON.Vector3.Zero();
  21142. this.direction = BABYLON.Vector3.Zero();
  21143. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21144. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21145. this.lifeTime = 1.0;
  21146. this.age = 0;
  21147. this.size = 0;
  21148. this.angle = 0;
  21149. this.angularSpeed = 0;
  21150. }
  21151. Particle.prototype.copyTo = function (other) {
  21152. other.position.copyFrom(this.position);
  21153. other.direction.copyFrom(this.direction);
  21154. other.color.copyFrom(this.color);
  21155. other.colorStep.copyFrom(this.colorStep);
  21156. other.lifeTime = this.lifeTime;
  21157. other.age = this.age;
  21158. other.size = this.size;
  21159. other.angle = this.angle;
  21160. other.angularSpeed = this.angularSpeed;
  21161. };
  21162. return Particle;
  21163. })();
  21164. BABYLON.Particle = Particle;
  21165. })(BABYLON || (BABYLON = {}));
  21166. var BABYLON;
  21167. (function (BABYLON) {
  21168. var randomNumber = function (min, max) {
  21169. if (min === max) {
  21170. return (min);
  21171. }
  21172. var random = Math.random();
  21173. return ((random * (max - min)) + min);
  21174. };
  21175. var ParticleSystem = (function () {
  21176. function ParticleSystem(name, capacity, scene, customEffect) {
  21177. var _this = this;
  21178. this.name = name;
  21179. this.renderingGroupId = 0;
  21180. this.emitter = null;
  21181. this.emitRate = 10;
  21182. this.manualEmitCount = -1;
  21183. this.updateSpeed = 0.01;
  21184. this.targetStopDuration = 0;
  21185. this.disposeOnStop = false;
  21186. this.minEmitPower = 1;
  21187. this.maxEmitPower = 1;
  21188. this.minLifeTime = 1;
  21189. this.maxLifeTime = 1;
  21190. this.minSize = 1;
  21191. this.maxSize = 1;
  21192. this.minAngularSpeed = 0;
  21193. this.maxAngularSpeed = 0;
  21194. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21195. this.forceDepthWrite = false;
  21196. this.gravity = BABYLON.Vector3.Zero();
  21197. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21198. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21199. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21200. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21201. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21202. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21203. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21204. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21205. this.particles = new Array();
  21206. this._vertexDeclaration = [3, 4, 4];
  21207. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21208. this._stockParticles = new Array();
  21209. this._newPartsExcess = 0;
  21210. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21211. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21212. this._scaledDirection = BABYLON.Vector3.Zero();
  21213. this._scaledGravity = BABYLON.Vector3.Zero();
  21214. this._currentRenderId = -1;
  21215. this._started = false;
  21216. this._stopped = false;
  21217. this._actualFrame = 0;
  21218. this.id = name;
  21219. this._capacity = capacity;
  21220. this._scene = scene;
  21221. this._customEffect = customEffect;
  21222. scene.particleSystems.push(this);
  21223. // VBO
  21224. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21225. var indices = [];
  21226. var index = 0;
  21227. for (var count = 0; count < capacity; count++) {
  21228. indices.push(index);
  21229. indices.push(index + 1);
  21230. indices.push(index + 2);
  21231. indices.push(index);
  21232. indices.push(index + 2);
  21233. indices.push(index + 3);
  21234. index += 4;
  21235. }
  21236. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21237. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21238. // Default behaviors
  21239. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21240. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21241. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21242. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21243. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21244. };
  21245. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21246. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21247. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21248. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21249. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21250. };
  21251. this.updateFunction = function (particles) {
  21252. for (var index = 0; index < particles.length; index++) {
  21253. var particle = particles[index];
  21254. particle.age += _this._scaledUpdateSpeed;
  21255. if (particle.age >= particle.lifeTime) {
  21256. _this.recycleParticle(particle);
  21257. index--;
  21258. continue;
  21259. }
  21260. else {
  21261. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21262. particle.color.addInPlace(_this._scaledColorStep);
  21263. if (particle.color.a < 0)
  21264. particle.color.a = 0;
  21265. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21266. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21267. particle.position.addInPlace(_this._scaledDirection);
  21268. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21269. particle.direction.addInPlace(_this._scaledGravity);
  21270. }
  21271. }
  21272. };
  21273. }
  21274. ParticleSystem.prototype.recycleParticle = function (particle) {
  21275. var lastParticle = this.particles.pop();
  21276. if (lastParticle !== particle) {
  21277. lastParticle.copyTo(particle);
  21278. this._stockParticles.push(lastParticle);
  21279. }
  21280. };
  21281. ParticleSystem.prototype.getCapacity = function () {
  21282. return this._capacity;
  21283. };
  21284. ParticleSystem.prototype.isAlive = function () {
  21285. return this._alive;
  21286. };
  21287. ParticleSystem.prototype.isStarted = function () {
  21288. return this._started;
  21289. };
  21290. ParticleSystem.prototype.start = function () {
  21291. this._started = true;
  21292. this._stopped = false;
  21293. this._actualFrame = 0;
  21294. };
  21295. ParticleSystem.prototype.stop = function () {
  21296. this._stopped = true;
  21297. };
  21298. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21299. var offset = index * 11;
  21300. this._vertices[offset] = particle.position.x;
  21301. this._vertices[offset + 1] = particle.position.y;
  21302. this._vertices[offset + 2] = particle.position.z;
  21303. this._vertices[offset + 3] = particle.color.r;
  21304. this._vertices[offset + 4] = particle.color.g;
  21305. this._vertices[offset + 5] = particle.color.b;
  21306. this._vertices[offset + 6] = particle.color.a;
  21307. this._vertices[offset + 7] = particle.angle;
  21308. this._vertices[offset + 8] = particle.size;
  21309. this._vertices[offset + 9] = offsetX;
  21310. this._vertices[offset + 10] = offsetY;
  21311. };
  21312. ParticleSystem.prototype._update = function (newParticles) {
  21313. // Update current
  21314. this._alive = this.particles.length > 0;
  21315. this.updateFunction(this.particles);
  21316. // Add new ones
  21317. var worldMatrix;
  21318. if (this.emitter.position) {
  21319. worldMatrix = this.emitter.getWorldMatrix();
  21320. }
  21321. else {
  21322. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21323. }
  21324. for (var index = 0; index < newParticles; index++) {
  21325. if (this.particles.length === this._capacity) {
  21326. break;
  21327. }
  21328. if (this._stockParticles.length !== 0) {
  21329. var particle = this._stockParticles.pop();
  21330. particle.age = 0;
  21331. }
  21332. else {
  21333. particle = new BABYLON.Particle();
  21334. }
  21335. this.particles.push(particle);
  21336. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21337. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21338. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21339. particle.size = randomNumber(this.minSize, this.maxSize);
  21340. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21341. this.startPositionFunction(worldMatrix, particle.position);
  21342. var step = randomNumber(0, 1.0);
  21343. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21344. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21345. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21346. }
  21347. };
  21348. ParticleSystem.prototype._getEffect = function () {
  21349. if (this._customEffect) {
  21350. return this._customEffect;
  21351. }
  21352. ;
  21353. var defines = [];
  21354. if (this._scene.clipPlane) {
  21355. defines.push("#define CLIPPLANE");
  21356. }
  21357. // Effect
  21358. var join = defines.join("\n");
  21359. if (this._cachedDefines !== join) {
  21360. this._cachedDefines = join;
  21361. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21362. }
  21363. return this._effect;
  21364. };
  21365. ParticleSystem.prototype.animate = function () {
  21366. if (!this._started)
  21367. return;
  21368. var effect = this._getEffect();
  21369. // Check
  21370. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21371. return;
  21372. if (this._currentRenderId === this._scene.getRenderId()) {
  21373. return;
  21374. }
  21375. this._currentRenderId = this._scene.getRenderId();
  21376. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21377. // determine the number of particles we need to create
  21378. var emitCout;
  21379. if (this.manualEmitCount > -1) {
  21380. emitCout = this.manualEmitCount;
  21381. this.manualEmitCount = 0;
  21382. }
  21383. else {
  21384. emitCout = this.emitRate;
  21385. }
  21386. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21387. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21388. if (this._newPartsExcess > 1.0) {
  21389. newParticles += this._newPartsExcess >> 0;
  21390. this._newPartsExcess -= this._newPartsExcess >> 0;
  21391. }
  21392. this._alive = false;
  21393. if (!this._stopped) {
  21394. this._actualFrame += this._scaledUpdateSpeed;
  21395. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21396. this.stop();
  21397. }
  21398. else {
  21399. newParticles = 0;
  21400. }
  21401. this._update(newParticles);
  21402. // Stopped?
  21403. if (this._stopped) {
  21404. if (!this._alive) {
  21405. this._started = false;
  21406. if (this.disposeOnStop) {
  21407. this._scene._toBeDisposed.push(this);
  21408. }
  21409. }
  21410. }
  21411. // Update VBO
  21412. var offset = 0;
  21413. for (var index = 0; index < this.particles.length; index++) {
  21414. var particle = this.particles[index];
  21415. this._appendParticleVertex(offset++, particle, 0, 0);
  21416. this._appendParticleVertex(offset++, particle, 1, 0);
  21417. this._appendParticleVertex(offset++, particle, 1, 1);
  21418. this._appendParticleVertex(offset++, particle, 0, 1);
  21419. }
  21420. var engine = this._scene.getEngine();
  21421. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21422. };
  21423. ParticleSystem.prototype.render = function () {
  21424. var effect = this._getEffect();
  21425. // Check
  21426. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21427. return 0;
  21428. var engine = this._scene.getEngine();
  21429. // Render
  21430. engine.enableEffect(effect);
  21431. engine.setState(false);
  21432. var viewMatrix = this._scene.getViewMatrix();
  21433. effect.setTexture("diffuseSampler", this.particleTexture);
  21434. effect.setMatrix("view", viewMatrix);
  21435. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21436. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21437. if (this._scene.clipPlane) {
  21438. var clipPlane = this._scene.clipPlane;
  21439. var invView = viewMatrix.clone();
  21440. invView.invert();
  21441. effect.setMatrix("invView", invView);
  21442. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21443. }
  21444. // VBOs
  21445. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21446. // Draw order
  21447. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21448. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21449. }
  21450. else {
  21451. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21452. }
  21453. if (this.forceDepthWrite) {
  21454. engine.setDepthWrite(true);
  21455. }
  21456. engine.draw(true, 0, this.particles.length * 6);
  21457. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21458. return this.particles.length;
  21459. };
  21460. ParticleSystem.prototype.dispose = function () {
  21461. if (this._vertexBuffer) {
  21462. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21463. this._vertexBuffer = null;
  21464. }
  21465. if (this._indexBuffer) {
  21466. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21467. this._indexBuffer = null;
  21468. }
  21469. if (this.particleTexture) {
  21470. this.particleTexture.dispose();
  21471. this.particleTexture = null;
  21472. }
  21473. // Remove from scene
  21474. var index = this._scene.particleSystems.indexOf(this);
  21475. this._scene.particleSystems.splice(index, 1);
  21476. // Callback
  21477. if (this.onDispose) {
  21478. this.onDispose();
  21479. }
  21480. };
  21481. // Clone
  21482. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21483. var result = new ParticleSystem(name, this._capacity, this._scene);
  21484. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21485. if (newEmitter === undefined) {
  21486. newEmitter = this.emitter;
  21487. }
  21488. result.emitter = newEmitter;
  21489. if (this.particleTexture) {
  21490. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21491. }
  21492. result.start();
  21493. return result;
  21494. };
  21495. // Statics
  21496. ParticleSystem.BLENDMODE_ONEONE = 0;
  21497. ParticleSystem.BLENDMODE_STANDARD = 1;
  21498. return ParticleSystem;
  21499. })();
  21500. BABYLON.ParticleSystem = ParticleSystem;
  21501. })(BABYLON || (BABYLON = {}));
  21502. var BABYLON;
  21503. (function (BABYLON) {
  21504. var Animation = (function () {
  21505. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21506. this.name = name;
  21507. this.targetProperty = targetProperty;
  21508. this.framePerSecond = framePerSecond;
  21509. this.dataType = dataType;
  21510. this.loopMode = loopMode;
  21511. this._offsetsCache = {};
  21512. this._highLimitsCache = {};
  21513. this._stopped = false;
  21514. this.targetPropertyPath = targetProperty.split(".");
  21515. this.dataType = dataType;
  21516. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21517. }
  21518. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21519. var dataType = undefined;
  21520. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21521. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21522. }
  21523. else if (from instanceof BABYLON.Quaternion) {
  21524. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21525. }
  21526. else if (from instanceof BABYLON.Vector3) {
  21527. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21528. }
  21529. else if (from instanceof BABYLON.Vector2) {
  21530. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21531. }
  21532. else if (from instanceof BABYLON.Color3) {
  21533. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21534. }
  21535. if (dataType == undefined) {
  21536. return null;
  21537. }
  21538. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21539. var keys = [];
  21540. keys.push({ frame: 0, value: from });
  21541. keys.push({ frame: totalFrame, value: to });
  21542. animation.setKeys(keys);
  21543. if (easingFunction !== undefined) {
  21544. animation.setEasingFunction(easingFunction);
  21545. }
  21546. mesh.animations.push(animation);
  21547. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  21548. };
  21549. // Methods
  21550. Animation.prototype.reset = function () {
  21551. this._offsetsCache = {};
  21552. this._highLimitsCache = {};
  21553. this.currentFrame = 0;
  21554. };
  21555. Animation.prototype.isStopped = function () {
  21556. return this._stopped;
  21557. };
  21558. Animation.prototype.getKeys = function () {
  21559. return this._keys;
  21560. };
  21561. Animation.prototype.getEasingFunction = function () {
  21562. return this._easingFunction;
  21563. };
  21564. Animation.prototype.setEasingFunction = function (easingFunction) {
  21565. this._easingFunction = easingFunction;
  21566. };
  21567. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21568. return startValue + (endValue - startValue) * gradient;
  21569. };
  21570. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21571. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21572. };
  21573. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21574. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21575. };
  21576. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21577. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21578. };
  21579. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21580. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21581. };
  21582. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21583. var startScale = new BABYLON.Vector3(0, 0, 0);
  21584. var startRotation = new BABYLON.Quaternion();
  21585. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21586. startValue.decompose(startScale, startRotation, startTranslation);
  21587. var endScale = new BABYLON.Vector3(0, 0, 0);
  21588. var endRotation = new BABYLON.Quaternion();
  21589. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21590. endValue.decompose(endScale, endRotation, endTranslation);
  21591. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21592. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21593. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21594. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21595. return result;
  21596. };
  21597. Animation.prototype.clone = function () {
  21598. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21599. clone.setKeys(this._keys);
  21600. return clone;
  21601. };
  21602. Animation.prototype.setKeys = function (values) {
  21603. this._keys = values.slice(0);
  21604. this._offsetsCache = {};
  21605. this._highLimitsCache = {};
  21606. };
  21607. Animation.prototype._getKeyValue = function (value) {
  21608. if (typeof value === "function") {
  21609. return value();
  21610. }
  21611. return value;
  21612. };
  21613. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21614. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21615. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21616. }
  21617. this.currentFrame = currentFrame;
  21618. // Try to get a hash to find the right key
  21619. 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));
  21620. if (this._keys[startKey].frame >= currentFrame) {
  21621. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21622. startKey--;
  21623. }
  21624. }
  21625. for (var key = startKey; key < this._keys.length; key++) {
  21626. if (this._keys[key + 1].frame >= currentFrame) {
  21627. var startValue = this._getKeyValue(this._keys[key].value);
  21628. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21629. // gradient : percent of currentFrame between the frame inf and the frame sup
  21630. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21631. // check for easingFunction and correction of gradient
  21632. if (this._easingFunction != null) {
  21633. gradient = this._easingFunction.ease(gradient);
  21634. }
  21635. switch (this.dataType) {
  21636. // Float
  21637. case Animation.ANIMATIONTYPE_FLOAT:
  21638. switch (loopMode) {
  21639. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21640. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21641. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21642. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21643. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21644. }
  21645. break;
  21646. // Quaternion
  21647. case Animation.ANIMATIONTYPE_QUATERNION:
  21648. var quaternion = null;
  21649. switch (loopMode) {
  21650. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21651. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21652. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21653. break;
  21654. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21655. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21656. break;
  21657. }
  21658. return quaternion;
  21659. // Vector3
  21660. case Animation.ANIMATIONTYPE_VECTOR3:
  21661. switch (loopMode) {
  21662. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21663. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21664. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21665. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21666. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21667. }
  21668. // Vector2
  21669. case Animation.ANIMATIONTYPE_VECTOR2:
  21670. switch (loopMode) {
  21671. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21672. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21673. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21674. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21675. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21676. }
  21677. // Color3
  21678. case Animation.ANIMATIONTYPE_COLOR3:
  21679. switch (loopMode) {
  21680. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21681. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21682. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21683. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21684. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21685. }
  21686. // Matrix
  21687. case Animation.ANIMATIONTYPE_MATRIX:
  21688. switch (loopMode) {
  21689. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21690. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21691. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21692. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21693. return startValue;
  21694. }
  21695. default:
  21696. break;
  21697. }
  21698. break;
  21699. }
  21700. }
  21701. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21702. };
  21703. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21704. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21705. this._stopped = true;
  21706. return false;
  21707. }
  21708. var returnValue = true;
  21709. // Adding a start key at frame 0 if missing
  21710. if (this._keys[0].frame !== 0) {
  21711. var newKey = { frame: 0, value: this._keys[0].value };
  21712. this._keys.splice(0, 0, newKey);
  21713. }
  21714. // Check limits
  21715. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21716. from = this._keys[0].frame;
  21717. }
  21718. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21719. to = this._keys[this._keys.length - 1].frame;
  21720. }
  21721. // Compute ratio
  21722. var range = to - from;
  21723. var offsetValue;
  21724. // ratio represents the frame delta between from and to
  21725. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21726. var highLimitValue = 0;
  21727. if (ratio > range && !loop) {
  21728. returnValue = false;
  21729. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21730. }
  21731. else {
  21732. // Get max value if required
  21733. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21734. var keyOffset = to.toString() + from.toString();
  21735. if (!this._offsetsCache[keyOffset]) {
  21736. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21737. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21738. switch (this.dataType) {
  21739. // Float
  21740. case Animation.ANIMATIONTYPE_FLOAT:
  21741. this._offsetsCache[keyOffset] = toValue - fromValue;
  21742. break;
  21743. // Quaternion
  21744. case Animation.ANIMATIONTYPE_QUATERNION:
  21745. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21746. break;
  21747. // Vector3
  21748. case Animation.ANIMATIONTYPE_VECTOR3:
  21749. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21750. // Vector2
  21751. case Animation.ANIMATIONTYPE_VECTOR2:
  21752. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21753. // Color3
  21754. case Animation.ANIMATIONTYPE_COLOR3:
  21755. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21756. default:
  21757. break;
  21758. }
  21759. this._highLimitsCache[keyOffset] = toValue;
  21760. }
  21761. highLimitValue = this._highLimitsCache[keyOffset];
  21762. offsetValue = this._offsetsCache[keyOffset];
  21763. }
  21764. }
  21765. if (offsetValue === undefined) {
  21766. switch (this.dataType) {
  21767. // Float
  21768. case Animation.ANIMATIONTYPE_FLOAT:
  21769. offsetValue = 0;
  21770. break;
  21771. // Quaternion
  21772. case Animation.ANIMATIONTYPE_QUATERNION:
  21773. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21774. break;
  21775. // Vector3
  21776. case Animation.ANIMATIONTYPE_VECTOR3:
  21777. offsetValue = BABYLON.Vector3.Zero();
  21778. break;
  21779. // Vector2
  21780. case Animation.ANIMATIONTYPE_VECTOR2:
  21781. offsetValue = BABYLON.Vector2.Zero();
  21782. break;
  21783. // Color3
  21784. case Animation.ANIMATIONTYPE_COLOR3:
  21785. offsetValue = BABYLON.Color3.Black();
  21786. }
  21787. }
  21788. // Compute value
  21789. var repeatCount = (ratio / range) >> 0;
  21790. var currentFrame = returnValue ? from + ratio % range : to;
  21791. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21792. // Set value
  21793. if (this.targetPropertyPath.length > 1) {
  21794. var property = this._target[this.targetPropertyPath[0]];
  21795. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21796. property = property[this.targetPropertyPath[index]];
  21797. }
  21798. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21799. }
  21800. else {
  21801. this._target[this.targetPropertyPath[0]] = currentValue;
  21802. }
  21803. if (this._target.markAsDirty) {
  21804. this._target.markAsDirty(this.targetProperty);
  21805. }
  21806. if (!returnValue) {
  21807. this._stopped = true;
  21808. }
  21809. return returnValue;
  21810. };
  21811. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21812. get: function () {
  21813. return Animation._ANIMATIONTYPE_FLOAT;
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21819. get: function () {
  21820. return Animation._ANIMATIONTYPE_VECTOR3;
  21821. },
  21822. enumerable: true,
  21823. configurable: true
  21824. });
  21825. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21826. get: function () {
  21827. return Animation._ANIMATIONTYPE_VECTOR2;
  21828. },
  21829. enumerable: true,
  21830. configurable: true
  21831. });
  21832. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21833. get: function () {
  21834. return Animation._ANIMATIONTYPE_QUATERNION;
  21835. },
  21836. enumerable: true,
  21837. configurable: true
  21838. });
  21839. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21840. get: function () {
  21841. return Animation._ANIMATIONTYPE_MATRIX;
  21842. },
  21843. enumerable: true,
  21844. configurable: true
  21845. });
  21846. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21847. get: function () {
  21848. return Animation._ANIMATIONTYPE_COLOR3;
  21849. },
  21850. enumerable: true,
  21851. configurable: true
  21852. });
  21853. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21854. get: function () {
  21855. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21856. },
  21857. enumerable: true,
  21858. configurable: true
  21859. });
  21860. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21861. get: function () {
  21862. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21863. },
  21864. enumerable: true,
  21865. configurable: true
  21866. });
  21867. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21868. get: function () {
  21869. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21870. },
  21871. enumerable: true,
  21872. configurable: true
  21873. });
  21874. // Statics
  21875. Animation._ANIMATIONTYPE_FLOAT = 0;
  21876. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21877. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21878. Animation._ANIMATIONTYPE_MATRIX = 3;
  21879. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21880. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21881. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21882. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21883. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21884. return Animation;
  21885. })();
  21886. BABYLON.Animation = Animation;
  21887. })(BABYLON || (BABYLON = {}));
  21888. var BABYLON;
  21889. (function (BABYLON) {
  21890. var Animatable = (function () {
  21891. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21892. if (fromFrame === void 0) { fromFrame = 0; }
  21893. if (toFrame === void 0) { toFrame = 100; }
  21894. if (loopAnimation === void 0) { loopAnimation = false; }
  21895. if (speedRatio === void 0) { speedRatio = 1.0; }
  21896. this.target = target;
  21897. this.fromFrame = fromFrame;
  21898. this.toFrame = toFrame;
  21899. this.loopAnimation = loopAnimation;
  21900. this.speedRatio = speedRatio;
  21901. this.onAnimationEnd = onAnimationEnd;
  21902. this._animations = new Array();
  21903. this._paused = false;
  21904. this.animationStarted = false;
  21905. if (animations) {
  21906. this.appendAnimations(target, animations);
  21907. }
  21908. this._scene = scene;
  21909. scene._activeAnimatables.push(this);
  21910. }
  21911. // Methods
  21912. Animatable.prototype.appendAnimations = function (target, animations) {
  21913. for (var index = 0; index < animations.length; index++) {
  21914. var animation = animations[index];
  21915. animation._target = target;
  21916. this._animations.push(animation);
  21917. }
  21918. };
  21919. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21920. var animations = this._animations;
  21921. for (var index = 0; index < animations.length; index++) {
  21922. if (animations[index].targetProperty === property) {
  21923. return animations[index];
  21924. }
  21925. }
  21926. return null;
  21927. };
  21928. Animatable.prototype.reset = function () {
  21929. var animations = this._animations;
  21930. for (var index = 0; index < animations.length; index++) {
  21931. animations[index].reset();
  21932. }
  21933. this._localDelayOffset = null;
  21934. this._pausedDelay = null;
  21935. };
  21936. Animatable.prototype.pause = function () {
  21937. if (this._paused) {
  21938. return;
  21939. }
  21940. this._paused = true;
  21941. };
  21942. Animatable.prototype.restart = function () {
  21943. this._paused = false;
  21944. };
  21945. Animatable.prototype.stop = function () {
  21946. var index = this._scene._activeAnimatables.indexOf(this);
  21947. if (index > -1) {
  21948. this._scene._activeAnimatables.splice(index, 1);
  21949. }
  21950. if (this.onAnimationEnd) {
  21951. this.onAnimationEnd();
  21952. }
  21953. };
  21954. Animatable.prototype._animate = function (delay) {
  21955. if (this._paused) {
  21956. if (!this._pausedDelay) {
  21957. this._pausedDelay = delay;
  21958. }
  21959. return true;
  21960. }
  21961. if (!this._localDelayOffset) {
  21962. this._localDelayOffset = delay;
  21963. }
  21964. else if (this._pausedDelay) {
  21965. this._localDelayOffset += delay - this._pausedDelay;
  21966. this._pausedDelay = null;
  21967. }
  21968. // Animating
  21969. var running = false;
  21970. var animations = this._animations;
  21971. for (var index = 0; index < animations.length; index++) {
  21972. var animation = animations[index];
  21973. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21974. running = running || isRunning;
  21975. }
  21976. if (!running) {
  21977. // Remove from active animatables
  21978. index = this._scene._activeAnimatables.indexOf(this);
  21979. this._scene._activeAnimatables.splice(index, 1);
  21980. }
  21981. if (!running && this.onAnimationEnd) {
  21982. this.onAnimationEnd();
  21983. }
  21984. return running;
  21985. };
  21986. return Animatable;
  21987. })();
  21988. BABYLON.Animatable = Animatable;
  21989. })(BABYLON || (BABYLON = {}));
  21990. var BABYLON;
  21991. (function (BABYLON) {
  21992. var EasingFunction = (function () {
  21993. function EasingFunction() {
  21994. // Properties
  21995. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21996. }
  21997. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21998. get: function () {
  21999. return EasingFunction._EASINGMODE_EASEIN;
  22000. },
  22001. enumerable: true,
  22002. configurable: true
  22003. });
  22004. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22005. get: function () {
  22006. return EasingFunction._EASINGMODE_EASEOUT;
  22007. },
  22008. enumerable: true,
  22009. configurable: true
  22010. });
  22011. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22012. get: function () {
  22013. return EasingFunction._EASINGMODE_EASEINOUT;
  22014. },
  22015. enumerable: true,
  22016. configurable: true
  22017. });
  22018. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22019. var n = Math.min(Math.max(easingMode, 0), 2);
  22020. this._easingMode = n;
  22021. };
  22022. EasingFunction.prototype.getEasingMode = function () {
  22023. return this._easingMode;
  22024. };
  22025. EasingFunction.prototype.easeInCore = function (gradient) {
  22026. throw new Error('You must implement this method');
  22027. };
  22028. EasingFunction.prototype.ease = function (gradient) {
  22029. switch (this._easingMode) {
  22030. case EasingFunction.EASINGMODE_EASEIN:
  22031. return this.easeInCore(gradient);
  22032. case EasingFunction.EASINGMODE_EASEOUT:
  22033. return (1 - this.easeInCore(1 - gradient));
  22034. }
  22035. if (gradient >= 0.5) {
  22036. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22037. }
  22038. return (this.easeInCore(gradient * 2) * 0.5);
  22039. };
  22040. //Statics
  22041. EasingFunction._EASINGMODE_EASEIN = 0;
  22042. EasingFunction._EASINGMODE_EASEOUT = 1;
  22043. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22044. return EasingFunction;
  22045. })();
  22046. BABYLON.EasingFunction = EasingFunction;
  22047. var CircleEase = (function (_super) {
  22048. __extends(CircleEase, _super);
  22049. function CircleEase() {
  22050. _super.apply(this, arguments);
  22051. }
  22052. CircleEase.prototype.easeInCore = function (gradient) {
  22053. gradient = Math.max(0, Math.min(1, gradient));
  22054. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22055. };
  22056. return CircleEase;
  22057. })(EasingFunction);
  22058. BABYLON.CircleEase = CircleEase;
  22059. var BackEase = (function (_super) {
  22060. __extends(BackEase, _super);
  22061. function BackEase(amplitude) {
  22062. if (amplitude === void 0) { amplitude = 1; }
  22063. _super.call(this);
  22064. this.amplitude = amplitude;
  22065. }
  22066. BackEase.prototype.easeInCore = function (gradient) {
  22067. var num = Math.max(0, this.amplitude);
  22068. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22069. };
  22070. return BackEase;
  22071. })(EasingFunction);
  22072. BABYLON.BackEase = BackEase;
  22073. var BounceEase = (function (_super) {
  22074. __extends(BounceEase, _super);
  22075. function BounceEase(bounces, bounciness) {
  22076. if (bounces === void 0) { bounces = 3; }
  22077. if (bounciness === void 0) { bounciness = 2; }
  22078. _super.call(this);
  22079. this.bounces = bounces;
  22080. this.bounciness = bounciness;
  22081. }
  22082. BounceEase.prototype.easeInCore = function (gradient) {
  22083. var y = Math.max(0.0, this.bounces);
  22084. var bounciness = this.bounciness;
  22085. if (bounciness <= 1.0) {
  22086. bounciness = 1.001;
  22087. }
  22088. var num9 = Math.pow(bounciness, y);
  22089. var num5 = 1.0 - bounciness;
  22090. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22091. var num15 = gradient * num4;
  22092. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22093. var num3 = Math.floor(num65);
  22094. var num13 = num3 + 1.0;
  22095. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22096. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22097. var num7 = (num8 + num12) * 0.5;
  22098. var num6 = gradient - num7;
  22099. var num2 = num7 - num8;
  22100. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22101. };
  22102. return BounceEase;
  22103. })(EasingFunction);
  22104. BABYLON.BounceEase = BounceEase;
  22105. var CubicEase = (function (_super) {
  22106. __extends(CubicEase, _super);
  22107. function CubicEase() {
  22108. _super.apply(this, arguments);
  22109. }
  22110. CubicEase.prototype.easeInCore = function (gradient) {
  22111. return (gradient * gradient * gradient);
  22112. };
  22113. return CubicEase;
  22114. })(EasingFunction);
  22115. BABYLON.CubicEase = CubicEase;
  22116. var ElasticEase = (function (_super) {
  22117. __extends(ElasticEase, _super);
  22118. function ElasticEase(oscillations, springiness) {
  22119. if (oscillations === void 0) { oscillations = 3; }
  22120. if (springiness === void 0) { springiness = 3; }
  22121. _super.call(this);
  22122. this.oscillations = oscillations;
  22123. this.springiness = springiness;
  22124. }
  22125. ElasticEase.prototype.easeInCore = function (gradient) {
  22126. var num2;
  22127. var num3 = Math.max(0.0, this.oscillations);
  22128. var num = Math.max(0.0, this.springiness);
  22129. if (num == 0) {
  22130. num2 = gradient;
  22131. }
  22132. else {
  22133. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22134. }
  22135. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22136. };
  22137. return ElasticEase;
  22138. })(EasingFunction);
  22139. BABYLON.ElasticEase = ElasticEase;
  22140. var ExponentialEase = (function (_super) {
  22141. __extends(ExponentialEase, _super);
  22142. function ExponentialEase(exponent) {
  22143. if (exponent === void 0) { exponent = 2; }
  22144. _super.call(this);
  22145. this.exponent = exponent;
  22146. }
  22147. ExponentialEase.prototype.easeInCore = function (gradient) {
  22148. if (this.exponent <= 0) {
  22149. return gradient;
  22150. }
  22151. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22152. };
  22153. return ExponentialEase;
  22154. })(EasingFunction);
  22155. BABYLON.ExponentialEase = ExponentialEase;
  22156. var PowerEase = (function (_super) {
  22157. __extends(PowerEase, _super);
  22158. function PowerEase(power) {
  22159. if (power === void 0) { power = 2; }
  22160. _super.call(this);
  22161. this.power = power;
  22162. }
  22163. PowerEase.prototype.easeInCore = function (gradient) {
  22164. var y = Math.max(0.0, this.power);
  22165. return Math.pow(gradient, y);
  22166. };
  22167. return PowerEase;
  22168. })(EasingFunction);
  22169. BABYLON.PowerEase = PowerEase;
  22170. var QuadraticEase = (function (_super) {
  22171. __extends(QuadraticEase, _super);
  22172. function QuadraticEase() {
  22173. _super.apply(this, arguments);
  22174. }
  22175. QuadraticEase.prototype.easeInCore = function (gradient) {
  22176. return (gradient * gradient);
  22177. };
  22178. return QuadraticEase;
  22179. })(EasingFunction);
  22180. BABYLON.QuadraticEase = QuadraticEase;
  22181. var QuarticEase = (function (_super) {
  22182. __extends(QuarticEase, _super);
  22183. function QuarticEase() {
  22184. _super.apply(this, arguments);
  22185. }
  22186. QuarticEase.prototype.easeInCore = function (gradient) {
  22187. return (gradient * gradient * gradient * gradient);
  22188. };
  22189. return QuarticEase;
  22190. })(EasingFunction);
  22191. BABYLON.QuarticEase = QuarticEase;
  22192. var QuinticEase = (function (_super) {
  22193. __extends(QuinticEase, _super);
  22194. function QuinticEase() {
  22195. _super.apply(this, arguments);
  22196. }
  22197. QuinticEase.prototype.easeInCore = function (gradient) {
  22198. return (gradient * gradient * gradient * gradient * gradient);
  22199. };
  22200. return QuinticEase;
  22201. })(EasingFunction);
  22202. BABYLON.QuinticEase = QuinticEase;
  22203. var SineEase = (function (_super) {
  22204. __extends(SineEase, _super);
  22205. function SineEase() {
  22206. _super.apply(this, arguments);
  22207. }
  22208. SineEase.prototype.easeInCore = function (gradient) {
  22209. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22210. };
  22211. return SineEase;
  22212. })(EasingFunction);
  22213. BABYLON.SineEase = SineEase;
  22214. var BezierCurveEase = (function (_super) {
  22215. __extends(BezierCurveEase, _super);
  22216. function BezierCurveEase(x1, y1, x2, y2) {
  22217. if (x1 === void 0) { x1 = 0; }
  22218. if (y1 === void 0) { y1 = 0; }
  22219. if (x2 === void 0) { x2 = 1; }
  22220. if (y2 === void 0) { y2 = 1; }
  22221. _super.call(this);
  22222. this.x1 = x1;
  22223. this.y1 = y1;
  22224. this.x2 = x2;
  22225. this.y2 = y2;
  22226. }
  22227. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22228. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22229. };
  22230. return BezierCurveEase;
  22231. })(EasingFunction);
  22232. BABYLON.BezierCurveEase = BezierCurveEase;
  22233. })(BABYLON || (BABYLON = {}));
  22234. var BABYLON;
  22235. (function (BABYLON) {
  22236. var Octree = (function () {
  22237. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22238. if (maxDepth === void 0) { maxDepth = 2; }
  22239. this.maxDepth = maxDepth;
  22240. this.dynamicContent = new Array();
  22241. this._maxBlockCapacity = maxBlockCapacity || 64;
  22242. this._selectionContent = new BABYLON.SmartArray(1024);
  22243. this._creationFunc = creationFunc;
  22244. }
  22245. // Methods
  22246. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22247. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22248. };
  22249. Octree.prototype.addMesh = function (entry) {
  22250. for (var index = 0; index < this.blocks.length; index++) {
  22251. var block = this.blocks[index];
  22252. block.addEntry(entry);
  22253. }
  22254. };
  22255. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22256. this._selectionContent.reset();
  22257. for (var index = 0; index < this.blocks.length; index++) {
  22258. var block = this.blocks[index];
  22259. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22260. }
  22261. if (allowDuplicate) {
  22262. this._selectionContent.concat(this.dynamicContent);
  22263. }
  22264. else {
  22265. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22266. }
  22267. return this._selectionContent;
  22268. };
  22269. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22270. this._selectionContent.reset();
  22271. for (var index = 0; index < this.blocks.length; index++) {
  22272. var block = this.blocks[index];
  22273. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22274. }
  22275. if (allowDuplicate) {
  22276. this._selectionContent.concat(this.dynamicContent);
  22277. }
  22278. else {
  22279. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22280. }
  22281. return this._selectionContent;
  22282. };
  22283. Octree.prototype.intersectsRay = function (ray) {
  22284. this._selectionContent.reset();
  22285. for (var index = 0; index < this.blocks.length; index++) {
  22286. var block = this.blocks[index];
  22287. block.intersectsRay(ray, this._selectionContent);
  22288. }
  22289. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22290. return this._selectionContent;
  22291. };
  22292. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22293. target.blocks = new Array();
  22294. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22295. // Segmenting space
  22296. for (var x = 0; x < 2; x++) {
  22297. for (var y = 0; y < 2; y++) {
  22298. for (var z = 0; z < 2; z++) {
  22299. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22300. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22301. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22302. block.addEntries(entries);
  22303. target.blocks.push(block);
  22304. }
  22305. }
  22306. }
  22307. };
  22308. Octree.CreationFuncForMeshes = function (entry, block) {
  22309. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22310. block.entries.push(entry);
  22311. }
  22312. };
  22313. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22314. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22315. block.entries.push(entry);
  22316. }
  22317. };
  22318. return Octree;
  22319. })();
  22320. BABYLON.Octree = Octree;
  22321. })(BABYLON || (BABYLON = {}));
  22322. var BABYLON;
  22323. (function (BABYLON) {
  22324. var OctreeBlock = (function () {
  22325. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22326. this.entries = new Array();
  22327. this._boundingVectors = new Array();
  22328. this._capacity = capacity;
  22329. this._depth = depth;
  22330. this._maxDepth = maxDepth;
  22331. this._creationFunc = creationFunc;
  22332. this._minPoint = minPoint;
  22333. this._maxPoint = maxPoint;
  22334. this._boundingVectors.push(minPoint.clone());
  22335. this._boundingVectors.push(maxPoint.clone());
  22336. this._boundingVectors.push(minPoint.clone());
  22337. this._boundingVectors[2].x = maxPoint.x;
  22338. this._boundingVectors.push(minPoint.clone());
  22339. this._boundingVectors[3].y = maxPoint.y;
  22340. this._boundingVectors.push(minPoint.clone());
  22341. this._boundingVectors[4].z = maxPoint.z;
  22342. this._boundingVectors.push(maxPoint.clone());
  22343. this._boundingVectors[5].z = minPoint.z;
  22344. this._boundingVectors.push(maxPoint.clone());
  22345. this._boundingVectors[6].x = minPoint.x;
  22346. this._boundingVectors.push(maxPoint.clone());
  22347. this._boundingVectors[7].y = minPoint.y;
  22348. }
  22349. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22350. // Property
  22351. get: function () {
  22352. return this._capacity;
  22353. },
  22354. enumerable: true,
  22355. configurable: true
  22356. });
  22357. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22358. get: function () {
  22359. return this._minPoint;
  22360. },
  22361. enumerable: true,
  22362. configurable: true
  22363. });
  22364. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22365. get: function () {
  22366. return this._maxPoint;
  22367. },
  22368. enumerable: true,
  22369. configurable: true
  22370. });
  22371. // Methods
  22372. OctreeBlock.prototype.addEntry = function (entry) {
  22373. if (this.blocks) {
  22374. for (var index = 0; index < this.blocks.length; index++) {
  22375. var block = this.blocks[index];
  22376. block.addEntry(entry);
  22377. }
  22378. return;
  22379. }
  22380. this._creationFunc(entry, this);
  22381. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22382. this.createInnerBlocks();
  22383. }
  22384. };
  22385. OctreeBlock.prototype.addEntries = function (entries) {
  22386. for (var index = 0; index < entries.length; index++) {
  22387. var mesh = entries[index];
  22388. this.addEntry(mesh);
  22389. }
  22390. };
  22391. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  22392. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  22393. if (this.blocks) {
  22394. for (var index = 0; index < this.blocks.length; index++) {
  22395. var block = this.blocks[index];
  22396. block.select(frustumPlanes, selection, allowDuplicate);
  22397. }
  22398. return;
  22399. }
  22400. if (allowDuplicate) {
  22401. selection.concat(this.entries);
  22402. }
  22403. else {
  22404. selection.concatWithNoDuplicate(this.entries);
  22405. }
  22406. }
  22407. };
  22408. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  22409. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  22410. if (this.blocks) {
  22411. for (var index = 0; index < this.blocks.length; index++) {
  22412. var block = this.blocks[index];
  22413. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  22414. }
  22415. return;
  22416. }
  22417. if (allowDuplicate) {
  22418. selection.concat(this.entries);
  22419. }
  22420. else {
  22421. selection.concatWithNoDuplicate(this.entries);
  22422. }
  22423. }
  22424. };
  22425. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  22426. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  22427. if (this.blocks) {
  22428. for (var index = 0; index < this.blocks.length; index++) {
  22429. var block = this.blocks[index];
  22430. block.intersectsRay(ray, selection);
  22431. }
  22432. return;
  22433. }
  22434. selection.concatWithNoDuplicate(this.entries);
  22435. }
  22436. };
  22437. OctreeBlock.prototype.createInnerBlocks = function () {
  22438. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  22439. };
  22440. return OctreeBlock;
  22441. })();
  22442. BABYLON.OctreeBlock = OctreeBlock;
  22443. })(BABYLON || (BABYLON = {}));
  22444. var BABYLON;
  22445. (function (BABYLON) {
  22446. var Bone = (function (_super) {
  22447. __extends(Bone, _super);
  22448. function Bone(name, skeleton, parentBone, matrix) {
  22449. _super.call(this, name, skeleton.getScene());
  22450. this.name = name;
  22451. this.children = new Array();
  22452. this.animations = new Array();
  22453. this._worldTransform = new BABYLON.Matrix();
  22454. this._absoluteTransform = new BABYLON.Matrix();
  22455. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22456. this._skeleton = skeleton;
  22457. this._matrix = matrix;
  22458. this._baseMatrix = matrix;
  22459. skeleton.bones.push(this);
  22460. if (parentBone) {
  22461. this._parent = parentBone;
  22462. parentBone.children.push(this);
  22463. }
  22464. else {
  22465. this._parent = null;
  22466. }
  22467. this._updateDifferenceMatrix();
  22468. }
  22469. // Members
  22470. Bone.prototype.getParent = function () {
  22471. return this._parent;
  22472. };
  22473. Bone.prototype.getLocalMatrix = function () {
  22474. return this._matrix;
  22475. };
  22476. Bone.prototype.getBaseMatrix = function () {
  22477. return this._baseMatrix;
  22478. };
  22479. Bone.prototype.getWorldMatrix = function () {
  22480. return this._worldTransform;
  22481. };
  22482. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22483. return this._invertedAbsoluteTransform;
  22484. };
  22485. Bone.prototype.getAbsoluteMatrix = function () {
  22486. var matrix = this._matrix.clone();
  22487. var parent = this._parent;
  22488. while (parent) {
  22489. matrix = matrix.multiply(parent.getLocalMatrix());
  22490. parent = parent.getParent();
  22491. }
  22492. return matrix;
  22493. };
  22494. // Methods
  22495. Bone.prototype.updateMatrix = function (matrix) {
  22496. this._matrix = matrix;
  22497. this._skeleton._markAsDirty();
  22498. this._updateDifferenceMatrix();
  22499. };
  22500. Bone.prototype._updateDifferenceMatrix = function () {
  22501. if (this._parent) {
  22502. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22503. }
  22504. else {
  22505. this._absoluteTransform.copyFrom(this._matrix);
  22506. }
  22507. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22508. for (var index = 0; index < this.children.length; index++) {
  22509. this.children[index]._updateDifferenceMatrix();
  22510. }
  22511. };
  22512. Bone.prototype.markAsDirty = function () {
  22513. this._currentRenderId++;
  22514. this._skeleton._markAsDirty();
  22515. };
  22516. return Bone;
  22517. })(BABYLON.Node);
  22518. BABYLON.Bone = Bone;
  22519. })(BABYLON || (BABYLON = {}));
  22520. var BABYLON;
  22521. (function (BABYLON) {
  22522. var Skeleton = (function () {
  22523. function Skeleton(name, id, scene) {
  22524. this.name = name;
  22525. this.id = id;
  22526. this.bones = new Array();
  22527. this._isDirty = true;
  22528. this._identity = BABYLON.Matrix.Identity();
  22529. this.bones = [];
  22530. this._scene = scene;
  22531. scene.skeletons.push(this);
  22532. this.prepare();
  22533. //make sure it will recalculate the matrix next time prepare is called.
  22534. this._isDirty = true;
  22535. }
  22536. // Members
  22537. Skeleton.prototype.getTransformMatrices = function () {
  22538. return this._transformMatrices;
  22539. };
  22540. Skeleton.prototype.getScene = function () {
  22541. return this._scene;
  22542. };
  22543. // Methods
  22544. Skeleton.prototype._markAsDirty = function () {
  22545. this._isDirty = true;
  22546. };
  22547. Skeleton.prototype.prepare = function () {
  22548. if (!this._isDirty) {
  22549. return;
  22550. }
  22551. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22552. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22553. }
  22554. for (var index = 0; index < this.bones.length; index++) {
  22555. var bone = this.bones[index];
  22556. var parentBone = bone.getParent();
  22557. if (parentBone) {
  22558. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22559. }
  22560. else {
  22561. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22562. }
  22563. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22564. }
  22565. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22566. this._isDirty = false;
  22567. this._scene._activeBones += this.bones.length;
  22568. };
  22569. Skeleton.prototype.getAnimatables = function () {
  22570. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22571. this._animatables = [];
  22572. for (var index = 0; index < this.bones.length; index++) {
  22573. this._animatables.push(this.bones[index]);
  22574. }
  22575. }
  22576. return this._animatables;
  22577. };
  22578. Skeleton.prototype.clone = function (name, id) {
  22579. var result = new Skeleton(name, id || name, this._scene);
  22580. for (var index = 0; index < this.bones.length; index++) {
  22581. var source = this.bones[index];
  22582. var parentBone = null;
  22583. if (source.getParent()) {
  22584. var parentIndex = this.bones.indexOf(source.getParent());
  22585. parentBone = result.bones[parentIndex];
  22586. }
  22587. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22588. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22589. }
  22590. return result;
  22591. };
  22592. return Skeleton;
  22593. })();
  22594. BABYLON.Skeleton = Skeleton;
  22595. })(BABYLON || (BABYLON = {}));
  22596. var BABYLON;
  22597. (function (BABYLON) {
  22598. var PostProcess = (function () {
  22599. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22600. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22601. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22602. this.name = name;
  22603. this.width = -1;
  22604. this.height = -1;
  22605. this._reusable = false;
  22606. this._textures = new BABYLON.SmartArray(2);
  22607. this._currentRenderTextureInd = 0;
  22608. if (camera != null) {
  22609. this._camera = camera;
  22610. this._scene = camera.getScene();
  22611. camera.attachPostProcess(this);
  22612. this._engine = this._scene.getEngine();
  22613. }
  22614. else {
  22615. this._engine = engine;
  22616. }
  22617. this._renderRatio = ratio;
  22618. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22619. this._reusable = reusable || false;
  22620. this._textureType = textureType;
  22621. samplers = samplers || [];
  22622. samplers.push("textureSampler");
  22623. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22624. }
  22625. PostProcess.prototype.isReusable = function () {
  22626. return this._reusable;
  22627. };
  22628. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22629. camera = camera || this._camera;
  22630. var scene = camera.getScene();
  22631. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22632. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22633. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22634. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  22635. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  22636. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22637. if (this._textures.length > 0) {
  22638. for (var i = 0; i < this._textures.length; i++) {
  22639. this._engine._releaseTexture(this._textures.data[i]);
  22640. }
  22641. this._textures.reset();
  22642. }
  22643. this.width = desiredWidth;
  22644. this.height = desiredHeight;
  22645. 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 }));
  22646. if (this._reusable) {
  22647. 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 }));
  22648. }
  22649. if (this.onSizeChanged) {
  22650. this.onSizeChanged();
  22651. }
  22652. }
  22653. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22654. if (this.onActivate) {
  22655. this.onActivate(camera);
  22656. }
  22657. // Clear
  22658. if (this.clearColor) {
  22659. this._engine.clear(this.clearColor, true, true);
  22660. }
  22661. else {
  22662. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22663. }
  22664. if (this._reusable) {
  22665. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22666. }
  22667. };
  22668. PostProcess.prototype.apply = function () {
  22669. // Check
  22670. if (!this._effect.isReady())
  22671. return null;
  22672. // States
  22673. this._engine.enableEffect(this._effect);
  22674. this._engine.setState(false);
  22675. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22676. this._engine.setDepthBuffer(false);
  22677. this._engine.setDepthWrite(false);
  22678. // Texture
  22679. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22680. // Parameters
  22681. if (this.onApply) {
  22682. this.onApply(this._effect);
  22683. }
  22684. return this._effect;
  22685. };
  22686. PostProcess.prototype.dispose = function (camera) {
  22687. camera = camera || this._camera;
  22688. if (this._textures.length > 0) {
  22689. for (var i = 0; i < this._textures.length; i++) {
  22690. this._engine._releaseTexture(this._textures.data[i]);
  22691. }
  22692. this._textures.reset();
  22693. }
  22694. if (!camera) {
  22695. return;
  22696. }
  22697. camera.detachPostProcess(this);
  22698. var index = camera._postProcesses.indexOf(this);
  22699. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22700. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22701. }
  22702. };
  22703. return PostProcess;
  22704. })();
  22705. BABYLON.PostProcess = PostProcess;
  22706. })(BABYLON || (BABYLON = {}));
  22707. var BABYLON;
  22708. (function (BABYLON) {
  22709. var PostProcessManager = (function () {
  22710. function PostProcessManager(scene) {
  22711. this._vertexDeclaration = [2];
  22712. this._vertexStrideSize = 2 * 4;
  22713. this._scene = scene;
  22714. }
  22715. PostProcessManager.prototype._prepareBuffers = function () {
  22716. if (this._vertexBuffer) {
  22717. return;
  22718. }
  22719. // VBO
  22720. var vertices = [];
  22721. vertices.push(1, 1);
  22722. vertices.push(-1, 1);
  22723. vertices.push(-1, -1);
  22724. vertices.push(1, -1);
  22725. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22726. // Indices
  22727. var indices = [];
  22728. indices.push(0);
  22729. indices.push(1);
  22730. indices.push(2);
  22731. indices.push(0);
  22732. indices.push(2);
  22733. indices.push(3);
  22734. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22735. };
  22736. // Methods
  22737. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22738. var postProcesses = this._scene.activeCamera._postProcesses;
  22739. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22740. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22741. return false;
  22742. }
  22743. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22744. return true;
  22745. };
  22746. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22747. var engine = this._scene.getEngine();
  22748. for (var index = 0; index < postProcesses.length; index++) {
  22749. if (index < postProcesses.length - 1) {
  22750. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22751. }
  22752. else {
  22753. if (targetTexture) {
  22754. engine.bindFramebuffer(targetTexture);
  22755. }
  22756. else {
  22757. engine.restoreDefaultFramebuffer();
  22758. }
  22759. }
  22760. var pp = postProcesses[index];
  22761. var effect = pp.apply();
  22762. if (effect) {
  22763. if (pp.onBeforeRender) {
  22764. pp.onBeforeRender(effect);
  22765. }
  22766. // VBOs
  22767. this._prepareBuffers();
  22768. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22769. // Draw order
  22770. engine.draw(true, 0, 6);
  22771. if (pp.onAfterRender) {
  22772. pp.onAfterRender(effect);
  22773. }
  22774. }
  22775. }
  22776. // Restore depth buffer
  22777. engine.setDepthBuffer(true);
  22778. engine.setDepthWrite(true);
  22779. };
  22780. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22781. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22782. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22783. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22784. return;
  22785. }
  22786. var engine = this._scene.getEngine();
  22787. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22788. if (index < postProcessesTakenIndices.length - 1) {
  22789. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22790. }
  22791. else {
  22792. if (targetTexture) {
  22793. engine.bindFramebuffer(targetTexture);
  22794. }
  22795. else {
  22796. engine.restoreDefaultFramebuffer();
  22797. }
  22798. }
  22799. if (doNotPresent) {
  22800. break;
  22801. }
  22802. var pp = postProcesses[postProcessesTakenIndices[index]];
  22803. var effect = pp.apply();
  22804. if (effect) {
  22805. if (pp.onBeforeRender) {
  22806. pp.onBeforeRender(effect);
  22807. }
  22808. // VBOs
  22809. this._prepareBuffers();
  22810. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22811. // Draw order
  22812. engine.draw(true, 0, 6);
  22813. if (pp.onAfterRender) {
  22814. pp.onAfterRender(effect);
  22815. }
  22816. }
  22817. }
  22818. // Restore depth buffer
  22819. engine.setDepthBuffer(true);
  22820. engine.setDepthWrite(true);
  22821. };
  22822. PostProcessManager.prototype.dispose = function () {
  22823. if (this._vertexBuffer) {
  22824. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22825. this._vertexBuffer = null;
  22826. }
  22827. if (this._indexBuffer) {
  22828. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22829. this._indexBuffer = null;
  22830. }
  22831. };
  22832. return PostProcessManager;
  22833. })();
  22834. BABYLON.PostProcessManager = PostProcessManager;
  22835. })(BABYLON || (BABYLON = {}));
  22836. var BABYLON;
  22837. (function (BABYLON) {
  22838. var PassPostProcess = (function (_super) {
  22839. __extends(PassPostProcess, _super);
  22840. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22841. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22842. }
  22843. return PassPostProcess;
  22844. })(BABYLON.PostProcess);
  22845. BABYLON.PassPostProcess = PassPostProcess;
  22846. })(BABYLON || (BABYLON = {}));
  22847. var BABYLON;
  22848. (function (BABYLON) {
  22849. var BlurPostProcess = (function (_super) {
  22850. __extends(BlurPostProcess, _super);
  22851. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22852. var _this = this;
  22853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22854. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22855. this.direction = direction;
  22856. this.blurWidth = blurWidth;
  22857. this.onApply = function (effect) {
  22858. effect.setFloat2("screenSize", _this.width, _this.height);
  22859. effect.setVector2("direction", _this.direction);
  22860. effect.setFloat("blurWidth", _this.blurWidth);
  22861. };
  22862. }
  22863. return BlurPostProcess;
  22864. })(BABYLON.PostProcess);
  22865. BABYLON.BlurPostProcess = BlurPostProcess;
  22866. })(BABYLON || (BABYLON = {}));
  22867. var BABYLON;
  22868. (function (BABYLON) {
  22869. var RefractionPostProcess = (function (_super) {
  22870. __extends(RefractionPostProcess, _super);
  22871. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22872. var _this = this;
  22873. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22874. this.color = color;
  22875. this.depth = depth;
  22876. this.colorLevel = colorLevel;
  22877. this.onActivate = function (cam) {
  22878. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22879. };
  22880. this.onApply = function (effect) {
  22881. effect.setColor3("baseColor", _this.color);
  22882. effect.setFloat("depth", _this.depth);
  22883. effect.setFloat("colorLevel", _this.colorLevel);
  22884. effect.setTexture("refractionSampler", _this._refRexture);
  22885. };
  22886. }
  22887. // Methods
  22888. RefractionPostProcess.prototype.dispose = function (camera) {
  22889. if (this._refRexture) {
  22890. this._refRexture.dispose();
  22891. }
  22892. _super.prototype.dispose.call(this, camera);
  22893. };
  22894. return RefractionPostProcess;
  22895. })(BABYLON.PostProcess);
  22896. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22897. })(BABYLON || (BABYLON = {}));
  22898. var BABYLON;
  22899. (function (BABYLON) {
  22900. var BlackAndWhitePostProcess = (function (_super) {
  22901. __extends(BlackAndWhitePostProcess, _super);
  22902. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22903. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22904. }
  22905. return BlackAndWhitePostProcess;
  22906. })(BABYLON.PostProcess);
  22907. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22908. })(BABYLON || (BABYLON = {}));
  22909. var BABYLON;
  22910. (function (BABYLON) {
  22911. var ConvolutionPostProcess = (function (_super) {
  22912. __extends(ConvolutionPostProcess, _super);
  22913. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22914. var _this = this;
  22915. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22916. this.kernel = kernel;
  22917. this.onApply = function (effect) {
  22918. effect.setFloat2("screenSize", _this.width, _this.height);
  22919. effect.setArray("kernel", _this.kernel);
  22920. };
  22921. }
  22922. // Statics
  22923. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22924. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22925. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22926. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22927. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22928. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22929. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22930. return ConvolutionPostProcess;
  22931. })(BABYLON.PostProcess);
  22932. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22933. })(BABYLON || (BABYLON = {}));
  22934. var BABYLON;
  22935. (function (BABYLON) {
  22936. var FilterPostProcess = (function (_super) {
  22937. __extends(FilterPostProcess, _super);
  22938. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22939. var _this = this;
  22940. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22941. this.kernelMatrix = kernelMatrix;
  22942. this.onApply = function (effect) {
  22943. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22944. };
  22945. }
  22946. return FilterPostProcess;
  22947. })(BABYLON.PostProcess);
  22948. BABYLON.FilterPostProcess = FilterPostProcess;
  22949. })(BABYLON || (BABYLON = {}));
  22950. var BABYLON;
  22951. (function (BABYLON) {
  22952. var FxaaPostProcess = (function (_super) {
  22953. __extends(FxaaPostProcess, _super);
  22954. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22955. var _this = this;
  22956. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22957. this.onSizeChanged = function () {
  22958. _this.texelWidth = 1.0 / _this.width;
  22959. _this.texelHeight = 1.0 / _this.height;
  22960. };
  22961. this.onApply = function (effect) {
  22962. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22963. };
  22964. }
  22965. return FxaaPostProcess;
  22966. })(BABYLON.PostProcess);
  22967. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22968. })(BABYLON || (BABYLON = {}));
  22969. var BABYLON;
  22970. (function (BABYLON) {
  22971. var StereoscopicInterlacePostProcess = (function (_super) {
  22972. __extends(StereoscopicInterlacePostProcess, _super);
  22973. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  22974. var _this = this;
  22975. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  22976. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22977. this.onSizeChanged = function () {
  22978. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22979. };
  22980. this.onApply = function (effect) {
  22981. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22982. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22983. };
  22984. }
  22985. return StereoscopicInterlacePostProcess;
  22986. })(BABYLON.PostProcess);
  22987. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  22988. })(BABYLON || (BABYLON = {}));
  22989. var BABYLON;
  22990. (function (BABYLON) {
  22991. var LensFlare = (function () {
  22992. function LensFlare(size, position, color, imgUrl, system) {
  22993. this.size = size;
  22994. this.position = position;
  22995. this.dispose = function () {
  22996. if (this.texture) {
  22997. this.texture.dispose();
  22998. }
  22999. // Remove from scene
  23000. var index = this._system.lensFlares.indexOf(this);
  23001. this._system.lensFlares.splice(index, 1);
  23002. };
  23003. this.color = color || new BABYLON.Color3(1, 1, 1);
  23004. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23005. this._system = system;
  23006. system.lensFlares.push(this);
  23007. }
  23008. return LensFlare;
  23009. })();
  23010. BABYLON.LensFlare = LensFlare;
  23011. })(BABYLON || (BABYLON = {}));
  23012. var BABYLON;
  23013. (function (BABYLON) {
  23014. var LensFlareSystem = (function () {
  23015. function LensFlareSystem(name, emitter, scene) {
  23016. this.name = name;
  23017. this.lensFlares = new Array();
  23018. this.borderLimit = 300;
  23019. this._vertexDeclaration = [2];
  23020. this._vertexStrideSize = 2 * 4;
  23021. this._isEnabled = true;
  23022. this._scene = scene;
  23023. this._emitter = emitter;
  23024. scene.lensFlareSystems.push(this);
  23025. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23026. // VBO
  23027. var vertices = [];
  23028. vertices.push(1, 1);
  23029. vertices.push(-1, 1);
  23030. vertices.push(-1, -1);
  23031. vertices.push(1, -1);
  23032. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23033. // Indices
  23034. var indices = [];
  23035. indices.push(0);
  23036. indices.push(1);
  23037. indices.push(2);
  23038. indices.push(0);
  23039. indices.push(2);
  23040. indices.push(3);
  23041. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23042. // Effects
  23043. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23044. }
  23045. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23046. get: function () {
  23047. return this._isEnabled;
  23048. },
  23049. set: function (value) {
  23050. this._isEnabled = value;
  23051. },
  23052. enumerable: true,
  23053. configurable: true
  23054. });
  23055. LensFlareSystem.prototype.getScene = function () {
  23056. return this._scene;
  23057. };
  23058. LensFlareSystem.prototype.getEmitter = function () {
  23059. return this._emitter;
  23060. };
  23061. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23062. this._emitter = newEmitter;
  23063. };
  23064. LensFlareSystem.prototype.getEmitterPosition = function () {
  23065. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23066. };
  23067. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23068. var position = this.getEmitterPosition();
  23069. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23070. this._positionX = position.x;
  23071. this._positionY = position.y;
  23072. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23073. if (position.z > 0) {
  23074. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23075. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23076. return true;
  23077. }
  23078. }
  23079. return false;
  23080. };
  23081. LensFlareSystem.prototype._isVisible = function () {
  23082. if (!this._isEnabled) {
  23083. return false;
  23084. }
  23085. var emitterPosition = this.getEmitterPosition();
  23086. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23087. var distance = direction.length();
  23088. direction.normalize();
  23089. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23090. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23091. return !pickInfo.hit || pickInfo.distance > distance;
  23092. };
  23093. LensFlareSystem.prototype.render = function () {
  23094. if (!this._effect.isReady())
  23095. return false;
  23096. var engine = this._scene.getEngine();
  23097. var viewport = this._scene.activeCamera.viewport;
  23098. var globalViewport = viewport.toGlobal(engine);
  23099. // Position
  23100. if (!this.computeEffectivePosition(globalViewport)) {
  23101. return false;
  23102. }
  23103. // Visibility
  23104. if (!this._isVisible()) {
  23105. return false;
  23106. }
  23107. // Intensity
  23108. var awayX;
  23109. var awayY;
  23110. if (this._positionX < this.borderLimit + globalViewport.x) {
  23111. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23112. }
  23113. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23114. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23115. }
  23116. else {
  23117. awayX = 0;
  23118. }
  23119. if (this._positionY < this.borderLimit + globalViewport.y) {
  23120. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23121. }
  23122. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23123. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23124. }
  23125. else {
  23126. awayY = 0;
  23127. }
  23128. var away = (awayX > awayY) ? awayX : awayY;
  23129. if (away > this.borderLimit) {
  23130. away = this.borderLimit;
  23131. }
  23132. var intensity = 1.0 - (away / this.borderLimit);
  23133. if (intensity < 0) {
  23134. return false;
  23135. }
  23136. if (intensity > 1.0) {
  23137. intensity = 1.0;
  23138. }
  23139. // Position
  23140. var centerX = globalViewport.x + globalViewport.width / 2;
  23141. var centerY = globalViewport.y + globalViewport.height / 2;
  23142. var distX = centerX - this._positionX;
  23143. var distY = centerY - this._positionY;
  23144. // Effects
  23145. engine.enableEffect(this._effect);
  23146. engine.setState(false);
  23147. engine.setDepthBuffer(false);
  23148. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23149. // VBOs
  23150. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23151. // Flares
  23152. for (var index = 0; index < this.lensFlares.length; index++) {
  23153. var flare = this.lensFlares[index];
  23154. var x = centerX - (distX * flare.position);
  23155. var y = centerY - (distY * flare.position);
  23156. var cw = flare.size;
  23157. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23158. var cx = 2 * (x / globalViewport.width) - 1.0;
  23159. var cy = 1.0 - 2 * (y / globalViewport.height);
  23160. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23161. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23162. // Texture
  23163. this._effect.setTexture("textureSampler", flare.texture);
  23164. // Color
  23165. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23166. // Draw order
  23167. engine.draw(true, 0, 6);
  23168. }
  23169. engine.setDepthBuffer(true);
  23170. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23171. return true;
  23172. };
  23173. LensFlareSystem.prototype.dispose = function () {
  23174. if (this._vertexBuffer) {
  23175. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23176. this._vertexBuffer = null;
  23177. }
  23178. if (this._indexBuffer) {
  23179. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23180. this._indexBuffer = null;
  23181. }
  23182. while (this.lensFlares.length) {
  23183. this.lensFlares[0].dispose();
  23184. }
  23185. // Remove from scene
  23186. var index = this._scene.lensFlareSystems.indexOf(this);
  23187. this._scene.lensFlareSystems.splice(index, 1);
  23188. };
  23189. return LensFlareSystem;
  23190. })();
  23191. BABYLON.LensFlareSystem = LensFlareSystem;
  23192. })(BABYLON || (BABYLON = {}));
  23193. var BABYLON;
  23194. (function (BABYLON) {
  23195. var CannonJSPlugin = (function () {
  23196. function CannonJSPlugin() {
  23197. this._registeredMeshes = [];
  23198. this._physicsMaterials = [];
  23199. this.updateBodyPosition = function (mesh) {
  23200. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23201. var registeredMesh = this._registeredMeshes[index];
  23202. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23203. var body = registeredMesh.body;
  23204. var center = mesh.getBoundingInfo().boundingBox.center;
  23205. body.position.set(center.x, center.z, center.y);
  23206. body.quaternion.x = mesh.rotationQuaternion.x;
  23207. body.quaternion.z = mesh.rotationQuaternion.y;
  23208. body.quaternion.y = mesh.rotationQuaternion.z;
  23209. body.quaternion.w = -mesh.rotationQuaternion.w;
  23210. return;
  23211. }
  23212. }
  23213. };
  23214. }
  23215. CannonJSPlugin.prototype.initialize = function (iterations) {
  23216. if (iterations === void 0) { iterations = 10; }
  23217. this._world = new CANNON.World();
  23218. this._world.broadphase = new CANNON.NaiveBroadphase();
  23219. this._world.solver.iterations = iterations;
  23220. };
  23221. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23222. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23223. };
  23224. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23225. this._world.step(delta);
  23226. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23227. var registeredMesh = this._registeredMeshes[index];
  23228. if (registeredMesh.isChild) {
  23229. continue;
  23230. }
  23231. // Body position
  23232. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23233. var deltaPos = registeredMesh.delta;
  23234. if (deltaPos) {
  23235. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23236. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23237. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23238. }
  23239. else {
  23240. registeredMesh.mesh.position.x = bodyX;
  23241. registeredMesh.mesh.position.y = bodyZ;
  23242. registeredMesh.mesh.position.z = bodyY;
  23243. }
  23244. if (!registeredMesh.mesh.rotationQuaternion) {
  23245. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23246. }
  23247. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23248. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23249. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23250. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23251. }
  23252. };
  23253. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23254. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23255. };
  23256. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23257. this.unregisterMesh(mesh);
  23258. mesh.computeWorldMatrix(true);
  23259. switch (impostor) {
  23260. case BABYLON.PhysicsEngine.SphereImpostor:
  23261. var bbox = mesh.getBoundingInfo().boundingBox;
  23262. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23263. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23264. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23265. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23266. case BABYLON.PhysicsEngine.BoxImpostor:
  23267. bbox = mesh.getBoundingInfo().boundingBox;
  23268. var min = bbox.minimumWorld;
  23269. var max = bbox.maximumWorld;
  23270. var box = max.subtract(min).scale(0.5);
  23271. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23272. case BABYLON.PhysicsEngine.PlaneImpostor:
  23273. return this._createPlane(mesh, options);
  23274. case BABYLON.PhysicsEngine.MeshImpostor:
  23275. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23276. var rawFaces = mesh.getIndices();
  23277. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23278. }
  23279. return null;
  23280. };
  23281. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23282. var shape = new CANNON.Sphere(radius);
  23283. if (!options) {
  23284. return shape;
  23285. }
  23286. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23287. };
  23288. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23289. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23290. if (!options) {
  23291. return shape;
  23292. }
  23293. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23294. };
  23295. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23296. var shape = new CANNON.Plane();
  23297. if (!options) {
  23298. return shape;
  23299. }
  23300. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23301. };
  23302. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23303. var verts = [], faces = [];
  23304. mesh.computeWorldMatrix(true);
  23305. // Get vertices
  23306. for (var i = 0; i < rawVerts.length; i += 3) {
  23307. var transformed = BABYLON.Vector3.Zero();
  23308. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23309. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23310. }
  23311. // Get faces
  23312. for (var j = 0; j < rawFaces.length; j += 3) {
  23313. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23314. }
  23315. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23316. if (!options) {
  23317. return shape;
  23318. }
  23319. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23320. };
  23321. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23322. var index;
  23323. var mat;
  23324. for (index = 0; index < this._physicsMaterials.length; index++) {
  23325. mat = this._physicsMaterials[index];
  23326. if (mat.friction === friction && mat.restitution === restitution) {
  23327. return mat;
  23328. }
  23329. }
  23330. var currentMat = new CANNON.Material();
  23331. currentMat.friction = friction;
  23332. currentMat.restitution = restitution;
  23333. this._physicsMaterials.push(currentMat);
  23334. for (index = 0; index < this._physicsMaterials.length; index++) {
  23335. mat = this._physicsMaterials[index];
  23336. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23337. contactMaterial.contactEquationStiffness = 1e10;
  23338. contactMaterial.contactEquationRegularizationTime = 10;
  23339. this._world.addContactMaterial(contactMaterial);
  23340. }
  23341. return currentMat;
  23342. };
  23343. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23344. var initialRotation = null;
  23345. if (mesh.rotationQuaternion) {
  23346. initialRotation = mesh.rotationQuaternion.clone();
  23347. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23348. }
  23349. // The delta between the mesh position and the mesh bounding box center
  23350. var bbox = mesh.getBoundingInfo().boundingBox;
  23351. var deltaPosition = mesh.position.subtract(bbox.center);
  23352. var material = this._addMaterial(friction, restitution);
  23353. var body = new CANNON.RigidBody(mass, shape, material);
  23354. if (initialRotation) {
  23355. body.quaternion.x = initialRotation.x;
  23356. body.quaternion.z = initialRotation.y;
  23357. body.quaternion.y = initialRotation.z;
  23358. body.quaternion.w = -initialRotation.w;
  23359. }
  23360. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23361. this._world.add(body);
  23362. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23363. return body;
  23364. };
  23365. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23366. var compoundShape = new CANNON.Compound();
  23367. for (var index = 0; index < parts.length; index++) {
  23368. var mesh = parts[index].mesh;
  23369. var shape = this.registerMesh(mesh, parts[index].impostor);
  23370. if (index == 0) {
  23371. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23372. }
  23373. else {
  23374. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23375. }
  23376. }
  23377. var initialMesh = parts[0].mesh;
  23378. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23379. body.parts = parts;
  23380. return body;
  23381. };
  23382. CannonJSPlugin.prototype._unbindBody = function (body) {
  23383. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23384. var registeredMesh = this._registeredMeshes[index];
  23385. if (registeredMesh.body === body) {
  23386. registeredMesh.body = null;
  23387. registeredMesh.delta = 0;
  23388. }
  23389. }
  23390. };
  23391. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23392. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23393. var registeredMesh = this._registeredMeshes[index];
  23394. if (registeredMesh.mesh === mesh) {
  23395. // Remove body
  23396. if (registeredMesh.body) {
  23397. this._world.remove(registeredMesh.body);
  23398. this._unbindBody(registeredMesh.body);
  23399. }
  23400. this._registeredMeshes.splice(index, 1);
  23401. return;
  23402. }
  23403. }
  23404. };
  23405. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23406. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23407. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23408. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23409. var registeredMesh = this._registeredMeshes[index];
  23410. if (registeredMesh.mesh === mesh) {
  23411. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23412. return;
  23413. }
  23414. }
  23415. };
  23416. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23417. var body1 = null, body2 = null;
  23418. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23419. var registeredMesh = this._registeredMeshes[index];
  23420. if (registeredMesh.mesh === mesh1) {
  23421. body1 = registeredMesh.body;
  23422. }
  23423. else if (registeredMesh.mesh === mesh2) {
  23424. body2 = registeredMesh.body;
  23425. }
  23426. }
  23427. if (!body1 || !body2) {
  23428. return false;
  23429. }
  23430. 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));
  23431. this._world.addConstraint(constraint);
  23432. return true;
  23433. };
  23434. CannonJSPlugin.prototype.dispose = function () {
  23435. while (this._registeredMeshes.length) {
  23436. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23437. }
  23438. };
  23439. CannonJSPlugin.prototype.isSupported = function () {
  23440. return window.CANNON !== undefined;
  23441. };
  23442. return CannonJSPlugin;
  23443. })();
  23444. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23445. })(BABYLON || (BABYLON = {}));
  23446. var BABYLON;
  23447. (function (BABYLON) {
  23448. var OimoJSPlugin = (function () {
  23449. function OimoJSPlugin() {
  23450. this._registeredMeshes = [];
  23451. /**
  23452. * Update the body position according to the mesh position
  23453. * @param mesh
  23454. */
  23455. this.updateBodyPosition = function (mesh) {
  23456. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23457. var registeredMesh = this._registeredMeshes[index];
  23458. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23459. var body = registeredMesh.body.body;
  23460. mesh.computeWorldMatrix(true);
  23461. var center = mesh.getBoundingInfo().boundingBox.center;
  23462. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  23463. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  23464. body.sleeping = false;
  23465. return;
  23466. }
  23467. // Case where the parent has been updated
  23468. if (registeredMesh.mesh.parent === mesh) {
  23469. mesh.computeWorldMatrix(true);
  23470. registeredMesh.mesh.computeWorldMatrix(true);
  23471. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  23472. var absoluteRotation = mesh.rotation;
  23473. body = registeredMesh.body.body;
  23474. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  23475. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  23476. body.sleeping = false;
  23477. return;
  23478. }
  23479. }
  23480. };
  23481. }
  23482. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  23483. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23484. };
  23485. OimoJSPlugin.prototype.initialize = function (iterations) {
  23486. this._world = new OIMO.World();
  23487. this._world.clear();
  23488. };
  23489. OimoJSPlugin.prototype.setGravity = function (gravity) {
  23490. this._world.gravity = gravity;
  23491. };
  23492. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23493. var body = null;
  23494. this.unregisterMesh(mesh);
  23495. mesh.computeWorldMatrix(true);
  23496. var initialRotation = null;
  23497. if (mesh.rotationQuaternion) {
  23498. initialRotation = mesh.rotationQuaternion.clone();
  23499. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23500. mesh.computeWorldMatrix(true);
  23501. }
  23502. var bbox = mesh.getBoundingInfo().boundingBox;
  23503. // The delta between the mesh position and the mesh bounding box center
  23504. var deltaPosition = mesh.position.subtract(bbox.center);
  23505. // Transform delta position with the rotation
  23506. if (initialRotation) {
  23507. var m = new BABYLON.Matrix();
  23508. initialRotation.toRotationMatrix(m);
  23509. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  23510. }
  23511. // register mesh
  23512. switch (impostor) {
  23513. case BABYLON.PhysicsEngine.SphereImpostor:
  23514. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23515. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23516. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23517. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23518. body = new OIMO.Body({
  23519. type: 'sphere',
  23520. size: [size],
  23521. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23522. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23523. move: options.mass != 0,
  23524. config: [options.mass, options.friction, options.restitution],
  23525. world: this._world
  23526. });
  23527. break;
  23528. case BABYLON.PhysicsEngine.PlaneImpostor:
  23529. //Oimo "fakes" a cylinder as a box, so why don't we!
  23530. case BABYLON.PhysicsEngine.CylinderImpostor:
  23531. case BABYLON.PhysicsEngine.BoxImpostor:
  23532. var min = bbox.minimumWorld;
  23533. var max = bbox.maximumWorld;
  23534. var box = max.subtract(min);
  23535. var sizeX = this._checkWithEpsilon(box.x);
  23536. var sizeY = this._checkWithEpsilon(box.y);
  23537. var sizeZ = this._checkWithEpsilon(box.z);
  23538. body = new OIMO.Body({
  23539. type: 'box',
  23540. size: [sizeX, sizeY, sizeZ],
  23541. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23542. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23543. move: options.mass != 0,
  23544. config: [options.mass, options.friction, options.restitution],
  23545. world: this._world
  23546. });
  23547. break;
  23548. }
  23549. //If quaternion was set as the rotation of the object
  23550. if (initialRotation) {
  23551. //We have to access the rigid body's properties to set the quaternion.
  23552. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  23553. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  23554. //update the internal rotation matrix
  23555. body.body.syncShapes();
  23556. }
  23557. this._registeredMeshes.push({
  23558. mesh: mesh,
  23559. body: body,
  23560. delta: deltaPosition
  23561. });
  23562. return body;
  23563. };
  23564. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23565. var types = [], sizes = [], positions = [], rotations = [];
  23566. var initialMesh = parts[0].mesh;
  23567. for (var index = 0; index < parts.length; index++) {
  23568. var part = parts[index];
  23569. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  23570. types.push(bodyParameters.type);
  23571. sizes.push.apply(sizes, bodyParameters.size);
  23572. positions.push.apply(positions, bodyParameters.pos);
  23573. rotations.push.apply(rotations, bodyParameters.rot);
  23574. }
  23575. var body = new OIMO.Body({
  23576. type: types,
  23577. size: sizes,
  23578. pos: positions,
  23579. rot: rotations,
  23580. move: options.mass != 0,
  23581. config: [options.mass, options.friction, options.restitution],
  23582. world: this._world
  23583. });
  23584. this._registeredMeshes.push({
  23585. mesh: initialMesh,
  23586. body: body
  23587. });
  23588. return body;
  23589. };
  23590. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  23591. var bodyParameters = null;
  23592. var mesh = part.mesh;
  23593. // We need the bounding box/sphere info to compute the physics body
  23594. mesh.computeWorldMatrix();
  23595. switch (part.impostor) {
  23596. case BABYLON.PhysicsEngine.SphereImpostor:
  23597. var bbox = mesh.getBoundingInfo().boundingBox;
  23598. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23599. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23600. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23601. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23602. bodyParameters = {
  23603. type: 'sphere',
  23604. /* bug with oimo : sphere needs 3 sizes in this case */
  23605. size: [size, -1, -1],
  23606. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  23607. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23608. };
  23609. break;
  23610. case BABYLON.PhysicsEngine.PlaneImpostor:
  23611. case BABYLON.PhysicsEngine.BoxImpostor:
  23612. bbox = mesh.getBoundingInfo().boundingBox;
  23613. var min = bbox.minimumWorld;
  23614. var max = bbox.maximumWorld;
  23615. var box = max.subtract(min);
  23616. var sizeX = this._checkWithEpsilon(box.x);
  23617. var sizeY = this._checkWithEpsilon(box.y);
  23618. var sizeZ = this._checkWithEpsilon(box.z);
  23619. var relativePosition = mesh.position;
  23620. bodyParameters = {
  23621. type: 'box',
  23622. size: [sizeX, sizeY, sizeZ],
  23623. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  23624. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23625. };
  23626. break;
  23627. }
  23628. return bodyParameters;
  23629. };
  23630. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  23631. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23632. var registeredMesh = this._registeredMeshes[index];
  23633. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23634. if (registeredMesh.body) {
  23635. this._world.removeRigidBody(registeredMesh.body.body);
  23636. this._unbindBody(registeredMesh.body);
  23637. }
  23638. this._registeredMeshes.splice(index, 1);
  23639. return;
  23640. }
  23641. }
  23642. };
  23643. OimoJSPlugin.prototype._unbindBody = function (body) {
  23644. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23645. var registeredMesh = this._registeredMeshes[index];
  23646. if (registeredMesh.body === body) {
  23647. registeredMesh.body = null;
  23648. }
  23649. }
  23650. };
  23651. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23652. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23653. var registeredMesh = this._registeredMeshes[index];
  23654. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23655. // Get object mass to have a behaviour similar to cannon.js
  23656. var mass = registeredMesh.body.body.massInfo.mass;
  23657. // The force is scaled with the mass of object
  23658. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  23659. return;
  23660. }
  23661. }
  23662. };
  23663. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23664. var body1 = null, body2 = null;
  23665. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23666. var registeredMesh = this._registeredMeshes[index];
  23667. if (registeredMesh.mesh === mesh1) {
  23668. body1 = registeredMesh.body.body;
  23669. }
  23670. else if (registeredMesh.mesh === mesh2) {
  23671. body2 = registeredMesh.body.body;
  23672. }
  23673. }
  23674. if (!body1 || !body2) {
  23675. return false;
  23676. }
  23677. if (!options) {
  23678. options = {};
  23679. }
  23680. new OIMO.Link({
  23681. type: options.type,
  23682. body1: body1,
  23683. body2: body2,
  23684. min: options.min,
  23685. max: options.max,
  23686. axe1: options.axe1,
  23687. axe2: options.axe2,
  23688. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23689. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23690. collision: options.collision,
  23691. spring: options.spring,
  23692. world: this._world
  23693. });
  23694. return true;
  23695. };
  23696. OimoJSPlugin.prototype.dispose = function () {
  23697. this._world.clear();
  23698. while (this._registeredMeshes.length) {
  23699. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23700. }
  23701. };
  23702. OimoJSPlugin.prototype.isSupported = function () {
  23703. return OIMO !== undefined;
  23704. };
  23705. OimoJSPlugin.prototype._getLastShape = function (body) {
  23706. var lastShape = body.shapes;
  23707. while (lastShape.next) {
  23708. lastShape = lastShape.next;
  23709. }
  23710. return lastShape;
  23711. };
  23712. OimoJSPlugin.prototype.runOneStep = function (time) {
  23713. this._world.step();
  23714. // Update the position of all registered meshes
  23715. var i = this._registeredMeshes.length;
  23716. var m;
  23717. while (i--) {
  23718. var body = this._registeredMeshes[i].body.body;
  23719. var mesh = this._registeredMeshes[i].mesh;
  23720. var delta = this._registeredMeshes[i].delta;
  23721. if (!body.sleeping) {
  23722. if (body.shapes.next) {
  23723. var parentShape = this._getLastShape(body);
  23724. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23725. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23726. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23727. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23728. if (!mesh.rotationQuaternion) {
  23729. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23730. }
  23731. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23732. mesh.computeWorldMatrix();
  23733. }
  23734. else {
  23735. m = body.getMatrix();
  23736. mtx = BABYLON.Matrix.FromArray(m);
  23737. // Body position
  23738. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23739. if (!delta) {
  23740. mesh.position.x = bodyX;
  23741. mesh.position.y = bodyY;
  23742. mesh.position.z = bodyZ;
  23743. }
  23744. else {
  23745. mesh.position.x = bodyX + delta.x;
  23746. mesh.position.y = bodyY + delta.y;
  23747. mesh.position.z = bodyZ + delta.z;
  23748. }
  23749. if (!mesh.rotationQuaternion) {
  23750. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23751. }
  23752. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23753. mesh.computeWorldMatrix();
  23754. }
  23755. }
  23756. }
  23757. };
  23758. return OimoJSPlugin;
  23759. })();
  23760. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23761. })(BABYLON || (BABYLON = {}));
  23762. var BABYLON;
  23763. (function (BABYLON) {
  23764. var PhysicsEngine = (function () {
  23765. function PhysicsEngine(plugin) {
  23766. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23767. }
  23768. PhysicsEngine.prototype._initialize = function (gravity) {
  23769. this._currentPlugin.initialize();
  23770. this._setGravity(gravity);
  23771. };
  23772. PhysicsEngine.prototype._runOneStep = function (delta) {
  23773. if (delta > 0.1) {
  23774. delta = 0.1;
  23775. }
  23776. else if (delta <= 0) {
  23777. delta = 1.0 / 60.0;
  23778. }
  23779. this._currentPlugin.runOneStep(delta);
  23780. };
  23781. PhysicsEngine.prototype._setGravity = function (gravity) {
  23782. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23783. this._currentPlugin.setGravity(this.gravity);
  23784. };
  23785. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23786. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23787. };
  23788. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23789. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23790. };
  23791. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23792. this._currentPlugin.unregisterMesh(mesh);
  23793. };
  23794. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23795. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23796. };
  23797. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23798. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23799. };
  23800. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23801. this._currentPlugin.updateBodyPosition(mesh);
  23802. };
  23803. PhysicsEngine.prototype.dispose = function () {
  23804. this._currentPlugin.dispose();
  23805. };
  23806. PhysicsEngine.prototype.isSupported = function () {
  23807. return this._currentPlugin.isSupported();
  23808. };
  23809. // Statics
  23810. PhysicsEngine.NoImpostor = 0;
  23811. PhysicsEngine.SphereImpostor = 1;
  23812. PhysicsEngine.BoxImpostor = 2;
  23813. PhysicsEngine.PlaneImpostor = 3;
  23814. PhysicsEngine.MeshImpostor = 4;
  23815. PhysicsEngine.CapsuleImpostor = 5;
  23816. PhysicsEngine.ConeImpostor = 6;
  23817. PhysicsEngine.CylinderImpostor = 7;
  23818. PhysicsEngine.ConvexHullImpostor = 8;
  23819. PhysicsEngine.Epsilon = 0.001;
  23820. return PhysicsEngine;
  23821. })();
  23822. BABYLON.PhysicsEngine = PhysicsEngine;
  23823. })(BABYLON || (BABYLON = {}));
  23824. var BABYLON;
  23825. (function (BABYLON) {
  23826. var serializeLight = function (light) {
  23827. var serializationObject = {};
  23828. serializationObject.name = light.name;
  23829. serializationObject.id = light.id;
  23830. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23831. if (light instanceof BABYLON.PointLight) {
  23832. serializationObject.type = 0;
  23833. serializationObject.position = light.position.asArray();
  23834. }
  23835. else if (light instanceof BABYLON.DirectionalLight) {
  23836. serializationObject.type = 1;
  23837. var directionalLight = light;
  23838. serializationObject.position = directionalLight.position.asArray();
  23839. serializationObject.direction = directionalLight.direction.asArray();
  23840. }
  23841. else if (light instanceof BABYLON.SpotLight) {
  23842. serializationObject.type = 2;
  23843. var spotLight = light;
  23844. serializationObject.position = spotLight.position.asArray();
  23845. serializationObject.direction = spotLight.position.asArray();
  23846. serializationObject.angle = spotLight.angle;
  23847. serializationObject.exponent = spotLight.exponent;
  23848. }
  23849. else if (light instanceof BABYLON.HemisphericLight) {
  23850. serializationObject.type = 3;
  23851. var hemisphericLight = light;
  23852. serializationObject.direction = hemisphericLight.direction.asArray();
  23853. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23854. }
  23855. if (light.intensity) {
  23856. serializationObject.intensity = light.intensity;
  23857. }
  23858. serializationObject.range = light.range;
  23859. serializationObject.diffuse = light.diffuse.asArray();
  23860. serializationObject.specular = light.specular.asArray();
  23861. return serializationObject;
  23862. };
  23863. var serializeFresnelParameter = function (fresnelParameter) {
  23864. var serializationObject = {};
  23865. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23866. serializationObject.leftColor = fresnelParameter.leftColor;
  23867. serializationObject.rightColor = fresnelParameter.rightColor;
  23868. serializationObject.bias = fresnelParameter.bias;
  23869. serializationObject.power = fresnelParameter.power;
  23870. return serializationObject;
  23871. };
  23872. var appendAnimations = function (source, destination) {
  23873. if (source.animations) {
  23874. destination.animations = [];
  23875. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23876. var animation = source.animations[animationIndex];
  23877. destination.animations.push(serializeAnimation(animation));
  23878. }
  23879. }
  23880. };
  23881. var serializeCamera = function (camera) {
  23882. var serializationObject = {};
  23883. serializationObject.name = camera.name;
  23884. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23885. serializationObject.id = camera.id;
  23886. serializationObject.position = camera.position.asArray();
  23887. // Parent
  23888. if (camera.parent) {
  23889. serializationObject.parentId = camera.parent.id;
  23890. }
  23891. serializationObject.fov = camera.fov;
  23892. serializationObject.minZ = camera.minZ;
  23893. serializationObject.maxZ = camera.maxZ;
  23894. serializationObject.inertia = camera.inertia;
  23895. //setting the type
  23896. if (camera instanceof BABYLON.FreeCamera) {
  23897. serializationObject.type = "FreeCamera";
  23898. }
  23899. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23900. serializationObject.type = "ArcRotateCamera";
  23901. }
  23902. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23903. serializationObject.type = "AnaglyphArcRotateCamera";
  23904. }
  23905. else if (camera instanceof BABYLON.GamepadCamera) {
  23906. serializationObject.type = "GamepadCamera";
  23907. }
  23908. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23909. serializationObject.type = "AnaglyphFreeCamera";
  23910. }
  23911. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23912. serializationObject.type = "DeviceOrientationCamera";
  23913. }
  23914. else if (camera instanceof BABYLON.FollowCamera) {
  23915. serializationObject.type = "FollowCamera";
  23916. }
  23917. else if (camera instanceof BABYLON.TouchCamera) {
  23918. serializationObject.type = "TouchCamera";
  23919. }
  23920. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23921. serializationObject.type = "VirtualJoysticksCamera";
  23922. }
  23923. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23924. serializationObject.type = "WebVRFreeCamera";
  23925. }
  23926. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23927. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23928. }
  23929. //special properties of specific cameras
  23930. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23931. var arcCamera = camera;
  23932. serializationObject.alpha = arcCamera.alpha;
  23933. serializationObject.beta = arcCamera.beta;
  23934. serializationObject.radius = arcCamera.radius;
  23935. if (arcCamera.target && arcCamera.target.id) {
  23936. serializationObject.lockedTargetId = arcCamera.target.id;
  23937. }
  23938. }
  23939. else if (camera instanceof BABYLON.FollowCamera) {
  23940. var followCam = camera;
  23941. serializationObject.radius = followCam.radius;
  23942. serializationObject.heightOffset = followCam.heightOffset;
  23943. serializationObject.rotationOffset = followCam.rotationOffset;
  23944. }
  23945. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23946. //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.
  23947. if (camera['_interaxialDistance'] !== undefined) {
  23948. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  23949. }
  23950. }
  23951. //general properties that not all cameras have. The [] is due to typescript's type safety
  23952. if (camera['speed'] !== undefined) {
  23953. serializationObject.speed = camera['speed'];
  23954. }
  23955. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23956. serializationObject.target = camera['target'].asArray();
  23957. }
  23958. // Target
  23959. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23960. serializationObject.rotation = camera['rotation'].asArray();
  23961. }
  23962. // Locked target
  23963. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23964. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23965. }
  23966. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23967. serializationObject.applyGravity = camera['applyGravity'] || false;
  23968. if (camera['ellipsoid']) {
  23969. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23970. }
  23971. // Animations
  23972. appendAnimations(camera, serializationObject);
  23973. // Layer mask
  23974. serializationObject.layerMask = camera.layerMask;
  23975. return serializationObject;
  23976. };
  23977. var serializeAnimation = function (animation) {
  23978. var serializationObject = {};
  23979. serializationObject.name = animation.name;
  23980. serializationObject.property = animation.targetProperty;
  23981. serializationObject.framePerSecond = animation.framePerSecond;
  23982. serializationObject.dataType = animation.dataType;
  23983. serializationObject.loopBehavior = animation.loopMode;
  23984. var dataType = animation.dataType;
  23985. serializationObject.keys = [];
  23986. var keys = animation.getKeys();
  23987. for (var index = 0; index < keys.length; index++) {
  23988. var animationKey = keys[index];
  23989. var key = {};
  23990. key.frame = animationKey.frame;
  23991. switch (dataType) {
  23992. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23993. key.values = [animationKey.value];
  23994. break;
  23995. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23996. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23997. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23998. key.values = animationKey.value.asArray();
  23999. break;
  24000. }
  24001. serializationObject.keys.push(key);
  24002. }
  24003. return serializationObject;
  24004. };
  24005. var serializeMultiMaterial = function (material) {
  24006. var serializationObject = {};
  24007. serializationObject.name = material.name;
  24008. serializationObject.id = material.id;
  24009. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24010. serializationObject.materials = [];
  24011. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24012. var subMat = material.subMaterials[matIndex];
  24013. if (subMat) {
  24014. serializationObject.materials.push(subMat.id);
  24015. }
  24016. else {
  24017. serializationObject.materials.push(null);
  24018. }
  24019. }
  24020. return serializationObject;
  24021. };
  24022. var serializeMaterial = function (material) {
  24023. var serializationObject = {};
  24024. serializationObject.name = material.name;
  24025. serializationObject.ambient = material.ambientColor.asArray();
  24026. serializationObject.diffuse = material.diffuseColor.asArray();
  24027. serializationObject.specular = material.specularColor.asArray();
  24028. serializationObject.specularPower = material.specularPower;
  24029. serializationObject.emissive = material.emissiveColor.asArray();
  24030. serializationObject.alpha = material.alpha;
  24031. serializationObject.id = material.id;
  24032. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24033. serializationObject.backFaceCulling = material.backFaceCulling;
  24034. if (material.diffuseTexture) {
  24035. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24036. }
  24037. if (material.diffuseFresnelParameters) {
  24038. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24039. }
  24040. if (material.ambientTexture) {
  24041. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24042. }
  24043. if (material.opacityTexture) {
  24044. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24045. }
  24046. if (material.opacityFresnelParameters) {
  24047. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24048. }
  24049. if (material.reflectionTexture) {
  24050. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24051. }
  24052. if (material.reflectionFresnelParameters) {
  24053. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24054. }
  24055. if (material.emissiveTexture) {
  24056. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24057. }
  24058. if (material.emissiveFresnelParameters) {
  24059. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24060. }
  24061. if (material.specularTexture) {
  24062. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24063. }
  24064. if (material.bumpTexture) {
  24065. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24066. }
  24067. return serializationObject;
  24068. };
  24069. var serializeTexture = function (texture) {
  24070. var serializationObject = {};
  24071. if (!texture.name) {
  24072. return null;
  24073. }
  24074. if (texture instanceof BABYLON.CubeTexture) {
  24075. serializationObject.name = texture.name;
  24076. serializationObject.hasAlpha = texture.hasAlpha;
  24077. serializationObject.isCube = true;
  24078. serializationObject.level = texture.level;
  24079. serializationObject.coordinatesMode = texture.coordinatesMode;
  24080. return serializationObject;
  24081. }
  24082. if (texture instanceof BABYLON.MirrorTexture) {
  24083. var mirrorTexture = texture;
  24084. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24085. serializationObject.renderList = [];
  24086. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  24087. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24088. }
  24089. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24090. }
  24091. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24092. var renderTargetTexture = texture;
  24093. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24094. serializationObject.renderList = [];
  24095. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24096. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24097. }
  24098. }
  24099. var regularTexture = texture;
  24100. serializationObject.name = texture.name;
  24101. serializationObject.hasAlpha = texture.hasAlpha;
  24102. serializationObject.level = texture.level;
  24103. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24104. serializationObject.coordinatesMode = texture.coordinatesMode;
  24105. serializationObject.uOffset = regularTexture.uOffset;
  24106. serializationObject.vOffset = regularTexture.vOffset;
  24107. serializationObject.uScale = regularTexture.uScale;
  24108. serializationObject.vScale = regularTexture.vScale;
  24109. serializationObject.uAng = regularTexture.uAng;
  24110. serializationObject.vAng = regularTexture.vAng;
  24111. serializationObject.wAng = regularTexture.wAng;
  24112. serializationObject.wrapU = texture.wrapU;
  24113. serializationObject.wrapV = texture.wrapV;
  24114. // Animations
  24115. appendAnimations(texture, serializationObject);
  24116. return serializationObject;
  24117. };
  24118. var serializeSkeleton = function (skeleton) {
  24119. var serializationObject = {};
  24120. serializationObject.name = skeleton.name;
  24121. serializationObject.id = skeleton.id;
  24122. serializationObject.bones = [];
  24123. for (var index = 0; index < skeleton.bones.length; index++) {
  24124. var bone = skeleton.bones[index];
  24125. var serializedBone = {
  24126. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24127. name: bone.name,
  24128. matrix: bone.getLocalMatrix().toArray()
  24129. };
  24130. serializationObject.bones.push(serializedBone);
  24131. if (bone.animations && bone.animations.length > 0) {
  24132. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24133. }
  24134. }
  24135. return serializationObject;
  24136. };
  24137. var serializeParticleSystem = function (particleSystem) {
  24138. var serializationObject = {};
  24139. serializationObject.emitterId = particleSystem.emitter.id;
  24140. serializationObject.capacity = particleSystem.getCapacity();
  24141. if (particleSystem.particleTexture) {
  24142. serializationObject.textureName = particleSystem.particleTexture.name;
  24143. }
  24144. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24145. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24146. serializationObject.minSize = particleSystem.minSize;
  24147. serializationObject.maxSize = particleSystem.maxSize;
  24148. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24149. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24150. serializationObject.emitRate = particleSystem.emitRate;
  24151. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24152. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24153. serializationObject.gravity = particleSystem.gravity.asArray();
  24154. serializationObject.direction1 = particleSystem.direction1.asArray();
  24155. serializationObject.direction2 = particleSystem.direction2.asArray();
  24156. serializationObject.color1 = particleSystem.color1.asArray();
  24157. serializationObject.color2 = particleSystem.color2.asArray();
  24158. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24159. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24160. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24161. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24162. serializationObject.blendMode = particleSystem.blendMode;
  24163. return serializationObject;
  24164. };
  24165. var serializeLensFlareSystem = function (lensFlareSystem) {
  24166. var serializationObject = {};
  24167. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24168. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24169. serializationObject.flares = [];
  24170. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24171. var flare = lensFlareSystem.lensFlares[index];
  24172. serializationObject.flares.push({
  24173. size: flare.size,
  24174. position: flare.position,
  24175. color: flare.color.asArray(),
  24176. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24177. });
  24178. }
  24179. return serializationObject;
  24180. };
  24181. var serializeShadowGenerator = function (light) {
  24182. var serializationObject = {};
  24183. var shadowGenerator = light.getShadowGenerator();
  24184. serializationObject.lightId = light.id;
  24185. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24186. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24187. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24188. serializationObject.renderList = [];
  24189. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24190. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24191. serializationObject.renderList.push(mesh.id);
  24192. }
  24193. return serializationObject;
  24194. };
  24195. var serializedGeometries = [];
  24196. var serializeGeometry = function (geometry, serializationGeometries) {
  24197. if (serializedGeometries[geometry.id]) {
  24198. return;
  24199. }
  24200. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24201. serializationGeometries.boxes.push(serializeBox(geometry));
  24202. }
  24203. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24204. serializationGeometries.spheres.push(serializeSphere(geometry));
  24205. }
  24206. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24207. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24208. }
  24209. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24210. serializationGeometries.toruses.push(serializeTorus(geometry));
  24211. }
  24212. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24213. serializationGeometries.grounds.push(serializeGround(geometry));
  24214. }
  24215. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24216. serializationGeometries.planes.push(serializePlane(geometry));
  24217. }
  24218. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24219. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24220. }
  24221. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24222. throw new Error("Unknown primitive type");
  24223. }
  24224. else {
  24225. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24226. }
  24227. serializedGeometries[geometry.id] = true;
  24228. };
  24229. var serializeGeometryBase = function (geometry) {
  24230. var serializationObject = {};
  24231. serializationObject.id = geometry.id;
  24232. if (BABYLON.Tags.HasTags(geometry)) {
  24233. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24234. }
  24235. return serializationObject;
  24236. };
  24237. var serializeVertexData = function (vertexData) {
  24238. var serializationObject = serializeGeometryBase(vertexData);
  24239. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24240. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24241. }
  24242. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24243. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24244. }
  24245. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24246. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24247. }
  24248. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24249. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24250. }
  24251. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24252. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24253. }
  24254. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24255. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24256. }
  24257. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24258. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24259. }
  24260. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24261. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24262. }
  24263. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24264. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24265. }
  24266. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24267. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24268. serializationObject.matricesIndices._isExpanded = true;
  24269. }
  24270. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24271. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24272. }
  24273. serializationObject.indices = vertexData.getIndices();
  24274. return serializationObject;
  24275. };
  24276. var serializePrimitive = function (primitive) {
  24277. var serializationObject = serializeGeometryBase(primitive);
  24278. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24279. return serializationObject;
  24280. };
  24281. var serializeBox = function (box) {
  24282. var serializationObject = serializePrimitive(box);
  24283. serializationObject.size = box.size;
  24284. return serializationObject;
  24285. };
  24286. var serializeSphere = function (sphere) {
  24287. var serializationObject = serializePrimitive(sphere);
  24288. serializationObject.segments = sphere.segments;
  24289. serializationObject.diameter = sphere.diameter;
  24290. return serializationObject;
  24291. };
  24292. var serializeCylinder = function (cylinder) {
  24293. var serializationObject = serializePrimitive(cylinder);
  24294. serializationObject.height = cylinder.height;
  24295. serializationObject.diameterTop = cylinder.diameterTop;
  24296. serializationObject.diameterBottom = cylinder.diameterBottom;
  24297. serializationObject.tessellation = cylinder.tessellation;
  24298. return serializationObject;
  24299. };
  24300. var serializeTorus = function (torus) {
  24301. var serializationObject = serializePrimitive(torus);
  24302. serializationObject.diameter = torus.diameter;
  24303. serializationObject.thickness = torus.thickness;
  24304. serializationObject.tessellation = torus.tessellation;
  24305. return serializationObject;
  24306. };
  24307. var serializeGround = function (ground) {
  24308. var serializationObject = serializePrimitive(ground);
  24309. serializationObject.width = ground.width;
  24310. serializationObject.height = ground.height;
  24311. serializationObject.subdivisions = ground.subdivisions;
  24312. return serializationObject;
  24313. };
  24314. var serializePlane = function (plane) {
  24315. var serializationObject = serializePrimitive(plane);
  24316. serializationObject.size = plane.size;
  24317. return serializationObject;
  24318. };
  24319. var serializeTorusKnot = function (torusKnot) {
  24320. var serializationObject = serializePrimitive(torusKnot);
  24321. serializationObject.radius = torusKnot.radius;
  24322. serializationObject.tube = torusKnot.tube;
  24323. serializationObject.radialSegments = torusKnot.radialSegments;
  24324. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24325. serializationObject.p = torusKnot.p;
  24326. serializationObject.q = torusKnot.q;
  24327. return serializationObject;
  24328. };
  24329. var serializeMesh = function (mesh, serializationScene) {
  24330. var serializationObject = {};
  24331. serializationObject.name = mesh.name;
  24332. serializationObject.id = mesh.id;
  24333. if (BABYLON.Tags.HasTags(mesh)) {
  24334. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24335. }
  24336. serializationObject.position = mesh.position.asArray();
  24337. if (mesh.rotationQuaternion) {
  24338. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24339. }
  24340. else if (mesh.rotation) {
  24341. serializationObject.rotation = mesh.rotation.asArray();
  24342. }
  24343. serializationObject.scaling = mesh.scaling.asArray();
  24344. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24345. serializationObject.isEnabled = mesh.isEnabled();
  24346. serializationObject.isVisible = mesh.isVisible;
  24347. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24348. serializationObject.pickable = mesh.isPickable;
  24349. serializationObject.receiveShadows = mesh.receiveShadows;
  24350. serializationObject.billboardMode = mesh.billboardMode;
  24351. serializationObject.visibility = mesh.visibility;
  24352. serializationObject.checkCollisions = mesh.checkCollisions;
  24353. // Parent
  24354. if (mesh.parent) {
  24355. serializationObject.parentId = mesh.parent.id;
  24356. }
  24357. // Geometry
  24358. var geometry = mesh._geometry;
  24359. if (geometry) {
  24360. var geometryId = geometry.id;
  24361. serializationObject.geometryId = geometryId;
  24362. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24363. // 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
  24364. serializeGeometry(geometry, serializationScene.geometries);
  24365. }
  24366. // SubMeshes
  24367. serializationObject.subMeshes = [];
  24368. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24369. var subMesh = mesh.subMeshes[subIndex];
  24370. serializationObject.subMeshes.push({
  24371. materialIndex: subMesh.materialIndex,
  24372. verticesStart: subMesh.verticesStart,
  24373. verticesCount: subMesh.verticesCount,
  24374. indexStart: subMesh.indexStart,
  24375. indexCount: subMesh.indexCount
  24376. });
  24377. }
  24378. }
  24379. // Material
  24380. if (mesh.material) {
  24381. serializationObject.materialId = mesh.material.id;
  24382. }
  24383. else {
  24384. mesh.material = null;
  24385. }
  24386. // Skeleton
  24387. if (mesh.skeleton) {
  24388. serializationObject.skeletonId = mesh.skeleton.id;
  24389. }
  24390. // Physics
  24391. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  24392. serializationObject.physicsMass = mesh.getPhysicsMass();
  24393. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  24394. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  24395. switch (mesh.getPhysicsImpostor()) {
  24396. case BABYLON.PhysicsEngine.BoxImpostor:
  24397. serializationObject.physicsImpostor = 1;
  24398. break;
  24399. case BABYLON.PhysicsEngine.SphereImpostor:
  24400. serializationObject.physicsImpostor = 2;
  24401. break;
  24402. }
  24403. }
  24404. // Instances
  24405. serializationObject.instances = [];
  24406. for (var index = 0; index < mesh.instances.length; index++) {
  24407. var instance = mesh.instances[index];
  24408. var serializationInstance = {
  24409. name: instance.name,
  24410. position: instance.position,
  24411. rotation: instance.rotation,
  24412. rotationQuaternion: instance.rotationQuaternion,
  24413. scaling: instance.scaling
  24414. };
  24415. serializationObject.instances.push(serializationInstance);
  24416. // Animations
  24417. appendAnimations(instance, serializationInstance);
  24418. }
  24419. // Animations
  24420. appendAnimations(mesh, serializationObject);
  24421. // Layer mask
  24422. serializationObject.layerMask = mesh.layerMask;
  24423. return serializationObject;
  24424. };
  24425. var finalizeSingleMesh = function (mesh, serializationObject) {
  24426. //only works if the mesh is already loaded
  24427. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24428. //serialize material
  24429. if (mesh.material) {
  24430. if (mesh.material instanceof BABYLON.StandardMaterial) {
  24431. serializationObject.materials = serializationObject.materials || [];
  24432. if (!serializationObject.materials.some(function (mat) {
  24433. return mat.id == mesh.material.id;
  24434. })) {
  24435. serializationObject.materials.push(serializeMaterial(mesh.material));
  24436. }
  24437. }
  24438. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  24439. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  24440. if (!serializationObject.multiMaterials.some(function (mat) {
  24441. return mat.id == mesh.material.id;
  24442. })) {
  24443. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  24444. }
  24445. }
  24446. }
  24447. //serialize geometry
  24448. var geometry = mesh._geometry;
  24449. if (geometry) {
  24450. if (!serializationObject.geometries) {
  24451. serializationObject.geometries = {};
  24452. serializationObject.geometries.boxes = [];
  24453. serializationObject.geometries.spheres = [];
  24454. serializationObject.geometries.cylinders = [];
  24455. serializationObject.geometries.toruses = [];
  24456. serializationObject.geometries.grounds = [];
  24457. serializationObject.geometries.planes = [];
  24458. serializationObject.geometries.torusKnots = [];
  24459. serializationObject.geometries.vertexData = [];
  24460. }
  24461. serializeGeometry(geometry, serializationObject.geometries);
  24462. }
  24463. // Skeletons
  24464. if (mesh.skeleton) {
  24465. serializationObject.skeletons = serializationObject.skeletons || [];
  24466. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  24467. }
  24468. //serialize the actual mesh
  24469. serializationObject.meshes = serializationObject.meshes || [];
  24470. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24471. }
  24472. };
  24473. var SceneSerializer = (function () {
  24474. function SceneSerializer() {
  24475. }
  24476. SceneSerializer.Serialize = function (scene) {
  24477. var serializationObject = {};
  24478. // Scene
  24479. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  24480. serializationObject.autoClear = scene.autoClear;
  24481. serializationObject.clearColor = scene.clearColor.asArray();
  24482. serializationObject.ambientColor = scene.ambientColor.asArray();
  24483. serializationObject.gravity = scene.gravity.asArray();
  24484. // Fog
  24485. if (scene.fogMode && scene.fogMode !== 0) {
  24486. serializationObject.fogMode = scene.fogMode;
  24487. serializationObject.fogColor = scene.fogColor.asArray();
  24488. serializationObject.fogStart = scene.fogStart;
  24489. serializationObject.fogEnd = scene.fogEnd;
  24490. serializationObject.fogDensity = scene.fogDensity;
  24491. }
  24492. // Lights
  24493. serializationObject.lights = [];
  24494. for (var index = 0; index < scene.lights.length; index++) {
  24495. var light = scene.lights[index];
  24496. serializationObject.lights.push(serializeLight(light));
  24497. }
  24498. // Cameras
  24499. serializationObject.cameras = [];
  24500. for (index = 0; index < scene.cameras.length; index++) {
  24501. var camera = scene.cameras[index];
  24502. serializationObject.cameras.push(serializeCamera(camera));
  24503. }
  24504. if (scene.activeCamera) {
  24505. serializationObject.activeCameraID = scene.activeCamera.id;
  24506. }
  24507. // Materials
  24508. serializationObject.materials = [];
  24509. serializationObject.multiMaterials = [];
  24510. for (index = 0; index < scene.materials.length; index++) {
  24511. var material = scene.materials[index];
  24512. if (material instanceof BABYLON.StandardMaterial) {
  24513. serializationObject.materials.push(serializeMaterial(material));
  24514. }
  24515. else if (material instanceof BABYLON.MultiMaterial) {
  24516. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  24517. }
  24518. }
  24519. // Skeletons
  24520. serializationObject.skeletons = [];
  24521. for (index = 0; index < scene.skeletons.length; index++) {
  24522. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  24523. }
  24524. // Geometries
  24525. serializationObject.geometries = {};
  24526. serializationObject.geometries.boxes = [];
  24527. serializationObject.geometries.spheres = [];
  24528. serializationObject.geometries.cylinders = [];
  24529. serializationObject.geometries.toruses = [];
  24530. serializationObject.geometries.grounds = [];
  24531. serializationObject.geometries.planes = [];
  24532. serializationObject.geometries.torusKnots = [];
  24533. serializationObject.geometries.vertexData = [];
  24534. serializedGeometries = [];
  24535. var geometries = scene.getGeometries();
  24536. for (index = 0; index < geometries.length; index++) {
  24537. var geometry = geometries[index];
  24538. if (geometry.isReady()) {
  24539. serializeGeometry(geometry, serializationObject.geometries);
  24540. }
  24541. }
  24542. // Meshes
  24543. serializationObject.meshes = [];
  24544. for (index = 0; index < scene.meshes.length; index++) {
  24545. var abstractMesh = scene.meshes[index];
  24546. if (abstractMesh instanceof BABYLON.Mesh) {
  24547. var mesh = abstractMesh;
  24548. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24549. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24550. }
  24551. }
  24552. }
  24553. // Particles Systems
  24554. serializationObject.particleSystems = [];
  24555. for (index = 0; index < scene.particleSystems.length; index++) {
  24556. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  24557. }
  24558. // Lens flares
  24559. serializationObject.lensFlareSystems = [];
  24560. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  24561. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  24562. }
  24563. // Shadows
  24564. serializationObject.shadowGenerators = [];
  24565. for (index = 0; index < scene.lights.length; index++) {
  24566. light = scene.lights[index];
  24567. if (light.getShadowGenerator()) {
  24568. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  24569. }
  24570. }
  24571. return serializationObject;
  24572. };
  24573. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  24574. if (withParents === void 0) { withParents = false; }
  24575. if (withChildren === void 0) { withChildren = false; }
  24576. var serializationObject = {};
  24577. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  24578. if (withParents || withChildren) {
  24579. //deliberate for loop! not for each, appended should be processed as well.
  24580. for (var i = 0; i < toSerialize.length; ++i) {
  24581. if (withChildren) {
  24582. toSerialize[i].getDescendants().forEach(function (node) {
  24583. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  24584. toSerialize.push(node);
  24585. }
  24586. });
  24587. }
  24588. //make sure the array doesn't contain the object already
  24589. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  24590. toSerialize.push(toSerialize[i].parent);
  24591. }
  24592. }
  24593. }
  24594. toSerialize.forEach(function (mesh) {
  24595. finalizeSingleMesh(mesh, serializationObject);
  24596. });
  24597. return serializationObject;
  24598. };
  24599. return SceneSerializer;
  24600. })();
  24601. BABYLON.SceneSerializer = SceneSerializer;
  24602. })(BABYLON || (BABYLON = {}));
  24603. var BABYLON;
  24604. (function (BABYLON) {
  24605. // Unique ID when we import meshes from Babylon to CSG
  24606. var currentCSGMeshId = 0;
  24607. // # class Vertex
  24608. // Represents a vertex of a polygon. Use your own vertex class instead of this
  24609. // one to provide additional features like texture coordinates and vertex
  24610. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  24611. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  24612. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  24613. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  24614. // is not used anywhere else.
  24615. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  24616. var Vertex = (function () {
  24617. function Vertex(pos, normal, uv) {
  24618. this.pos = pos;
  24619. this.normal = normal;
  24620. this.uv = uv;
  24621. }
  24622. Vertex.prototype.clone = function () {
  24623. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  24624. };
  24625. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  24626. // orientation of a polygon is flipped.
  24627. Vertex.prototype.flip = function () {
  24628. this.normal = this.normal.scale(-1);
  24629. };
  24630. // Create a new vertex between this vertex and `other` by linearly
  24631. // interpolating all properties using a parameter of `t`. Subclasses should
  24632. // override this to interpolate additional properties.
  24633. Vertex.prototype.interpolate = function (other, t) {
  24634. 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));
  24635. };
  24636. return Vertex;
  24637. })();
  24638. // # class Plane
  24639. // Represents a plane in 3D space.
  24640. var Plane = (function () {
  24641. function Plane(normal, w) {
  24642. this.normal = normal;
  24643. this.w = w;
  24644. }
  24645. Plane.FromPoints = function (a, b, c) {
  24646. var v0 = c.subtract(a);
  24647. var v1 = b.subtract(a);
  24648. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  24649. return null;
  24650. }
  24651. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  24652. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  24653. };
  24654. Plane.prototype.clone = function () {
  24655. return new Plane(this.normal.clone(), this.w);
  24656. };
  24657. Plane.prototype.flip = function () {
  24658. this.normal.scaleInPlace(-1);
  24659. this.w = -this.w;
  24660. };
  24661. // Split `polygon` by this plane if needed, then put the polygon or polygon
  24662. // fragments in the appropriate lists. Coplanar polygons go into either
  24663. // `coplanarFront` or `coplanarBack` depending on their orientation with
  24664. // respect to this plane. Polygons in front or in back of this plane go into
  24665. // either `front` or `back`.
  24666. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  24667. var COPLANAR = 0;
  24668. var FRONT = 1;
  24669. var BACK = 2;
  24670. var SPANNING = 3;
  24671. // Classify each point as well as the entire polygon into one of the above
  24672. // four classes.
  24673. var polygonType = 0;
  24674. var types = [];
  24675. for (var i = 0; i < polygon.vertices.length; i++) {
  24676. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  24677. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  24678. polygonType |= type;
  24679. types.push(type);
  24680. }
  24681. // Put the polygon in the correct list, splitting it when necessary.
  24682. switch (polygonType) {
  24683. case COPLANAR:
  24684. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  24685. break;
  24686. case FRONT:
  24687. front.push(polygon);
  24688. break;
  24689. case BACK:
  24690. back.push(polygon);
  24691. break;
  24692. case SPANNING:
  24693. var f = [], b = [];
  24694. for (i = 0; i < polygon.vertices.length; i++) {
  24695. var j = (i + 1) % polygon.vertices.length;
  24696. var ti = types[i], tj = types[j];
  24697. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  24698. if (ti != BACK)
  24699. f.push(vi);
  24700. if (ti != FRONT)
  24701. b.push(ti != BACK ? vi.clone() : vi);
  24702. if ((ti | tj) == SPANNING) {
  24703. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  24704. var v = vi.interpolate(vj, t);
  24705. f.push(v);
  24706. b.push(v.clone());
  24707. }
  24708. }
  24709. if (f.length >= 3) {
  24710. var poly = new Polygon(f, polygon.shared);
  24711. if (poly.plane)
  24712. front.push(poly);
  24713. }
  24714. if (b.length >= 3) {
  24715. poly = new Polygon(b, polygon.shared);
  24716. if (poly.plane)
  24717. back.push(poly);
  24718. }
  24719. break;
  24720. }
  24721. };
  24722. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  24723. // point is on the plane.
  24724. Plane.EPSILON = 1e-5;
  24725. return Plane;
  24726. })();
  24727. // # class Polygon
  24728. // Represents a convex polygon. The vertices used to initialize a polygon must
  24729. // be coplanar and form a convex loop.
  24730. //
  24731. // Each convex polygon has a `shared` property, which is shared between all
  24732. // polygons that are clones of each other or were split from the same polygon.
  24733. // This can be used to define per-polygon properties (such as surface color).
  24734. var Polygon = (function () {
  24735. function Polygon(vertices, shared) {
  24736. this.vertices = vertices;
  24737. this.shared = shared;
  24738. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  24739. }
  24740. Polygon.prototype.clone = function () {
  24741. var vertices = this.vertices.map(function (v) { return v.clone(); });
  24742. return new Polygon(vertices, this.shared);
  24743. };
  24744. Polygon.prototype.flip = function () {
  24745. this.vertices.reverse().map(function (v) { v.flip(); });
  24746. this.plane.flip();
  24747. };
  24748. return Polygon;
  24749. })();
  24750. // # class Node
  24751. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  24752. // by picking a polygon to split along. That polygon (and all other coplanar
  24753. // polygons) are added directly to that node and the other polygons are added to
  24754. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  24755. // no distinction between internal and leaf nodes.
  24756. var Node = (function () {
  24757. function Node(polygons) {
  24758. this.plane = null;
  24759. this.front = null;
  24760. this.back = null;
  24761. this.polygons = [];
  24762. if (polygons) {
  24763. this.build(polygons);
  24764. }
  24765. }
  24766. Node.prototype.clone = function () {
  24767. var node = new Node();
  24768. node.plane = this.plane && this.plane.clone();
  24769. node.front = this.front && this.front.clone();
  24770. node.back = this.back && this.back.clone();
  24771. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24772. return node;
  24773. };
  24774. // Convert solid space to empty space and empty space to solid space.
  24775. Node.prototype.invert = function () {
  24776. for (var i = 0; i < this.polygons.length; i++) {
  24777. this.polygons[i].flip();
  24778. }
  24779. if (this.plane) {
  24780. this.plane.flip();
  24781. }
  24782. if (this.front) {
  24783. this.front.invert();
  24784. }
  24785. if (this.back) {
  24786. this.back.invert();
  24787. }
  24788. var temp = this.front;
  24789. this.front = this.back;
  24790. this.back = temp;
  24791. };
  24792. // Recursively remove all polygons in `polygons` that are inside this BSP
  24793. // tree.
  24794. Node.prototype.clipPolygons = function (polygons) {
  24795. if (!this.plane)
  24796. return polygons.slice();
  24797. var front = [], back = [];
  24798. for (var i = 0; i < polygons.length; i++) {
  24799. this.plane.splitPolygon(polygons[i], front, back, front, back);
  24800. }
  24801. if (this.front) {
  24802. front = this.front.clipPolygons(front);
  24803. }
  24804. if (this.back) {
  24805. back = this.back.clipPolygons(back);
  24806. }
  24807. else {
  24808. back = [];
  24809. }
  24810. return front.concat(back);
  24811. };
  24812. // Remove all polygons in this BSP tree that are inside the other BSP tree
  24813. // `bsp`.
  24814. Node.prototype.clipTo = function (bsp) {
  24815. this.polygons = bsp.clipPolygons(this.polygons);
  24816. if (this.front)
  24817. this.front.clipTo(bsp);
  24818. if (this.back)
  24819. this.back.clipTo(bsp);
  24820. };
  24821. // Return a list of all polygons in this BSP tree.
  24822. Node.prototype.allPolygons = function () {
  24823. var polygons = this.polygons.slice();
  24824. if (this.front)
  24825. polygons = polygons.concat(this.front.allPolygons());
  24826. if (this.back)
  24827. polygons = polygons.concat(this.back.allPolygons());
  24828. return polygons;
  24829. };
  24830. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  24831. // new polygons are filtered down to the bottom of the tree and become new
  24832. // nodes there. Each set of polygons is partitioned using the first polygon
  24833. // (no heuristic is used to pick a good split).
  24834. Node.prototype.build = function (polygons) {
  24835. if (!polygons.length)
  24836. return;
  24837. if (!this.plane)
  24838. this.plane = polygons[0].plane.clone();
  24839. var front = [], back = [];
  24840. for (var i = 0; i < polygons.length; i++) {
  24841. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  24842. }
  24843. if (front.length) {
  24844. if (!this.front)
  24845. this.front = new Node();
  24846. this.front.build(front);
  24847. }
  24848. if (back.length) {
  24849. if (!this.back)
  24850. this.back = new Node();
  24851. this.back.build(back);
  24852. }
  24853. };
  24854. return Node;
  24855. })();
  24856. var CSG = (function () {
  24857. function CSG() {
  24858. this.polygons = new Array();
  24859. }
  24860. // Convert BABYLON.Mesh to BABYLON.CSG
  24861. CSG.FromMesh = function (mesh) {
  24862. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  24863. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  24864. if (mesh instanceof BABYLON.Mesh) {
  24865. mesh.computeWorldMatrix(true);
  24866. matrix = mesh.getWorldMatrix();
  24867. meshPosition = mesh.position.clone();
  24868. meshRotation = mesh.rotation.clone();
  24869. if (mesh.rotationQuaternion) {
  24870. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  24871. }
  24872. meshScaling = mesh.scaling.clone();
  24873. }
  24874. else {
  24875. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  24876. }
  24877. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24878. var subMeshes = mesh.subMeshes;
  24879. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  24880. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  24881. vertices = [];
  24882. for (var j = 0; j < 3; j++) {
  24883. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  24884. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  24885. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  24886. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  24887. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  24888. vertex = new Vertex(position, normal, uv);
  24889. vertices.push(vertex);
  24890. }
  24891. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  24892. // To handle the case of degenerated triangle
  24893. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  24894. if (polygon.plane)
  24895. polygons.push(polygon);
  24896. }
  24897. }
  24898. var csg = CSG.FromPolygons(polygons);
  24899. csg.matrix = matrix;
  24900. csg.position = meshPosition;
  24901. csg.rotation = meshRotation;
  24902. csg.scaling = meshScaling;
  24903. csg.rotationQuaternion = meshRotationQuaternion;
  24904. currentCSGMeshId++;
  24905. return csg;
  24906. };
  24907. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  24908. CSG.FromPolygons = function (polygons) {
  24909. var csg = new CSG();
  24910. csg.polygons = polygons;
  24911. return csg;
  24912. };
  24913. CSG.prototype.clone = function () {
  24914. var csg = new CSG();
  24915. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  24916. csg.copyTransformAttributes(this);
  24917. return csg;
  24918. };
  24919. CSG.prototype.toPolygons = function () {
  24920. return this.polygons;
  24921. };
  24922. CSG.prototype.union = function (csg) {
  24923. var a = new Node(this.clone().polygons);
  24924. var b = new Node(csg.clone().polygons);
  24925. a.clipTo(b);
  24926. b.clipTo(a);
  24927. b.invert();
  24928. b.clipTo(a);
  24929. b.invert();
  24930. a.build(b.allPolygons());
  24931. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24932. };
  24933. CSG.prototype.unionInPlace = function (csg) {
  24934. var a = new Node(this.polygons);
  24935. var b = new Node(csg.polygons);
  24936. a.clipTo(b);
  24937. b.clipTo(a);
  24938. b.invert();
  24939. b.clipTo(a);
  24940. b.invert();
  24941. a.build(b.allPolygons());
  24942. this.polygons = a.allPolygons();
  24943. };
  24944. CSG.prototype.subtract = function (csg) {
  24945. var a = new Node(this.clone().polygons);
  24946. var b = new Node(csg.clone().polygons);
  24947. a.invert();
  24948. a.clipTo(b);
  24949. b.clipTo(a);
  24950. b.invert();
  24951. b.clipTo(a);
  24952. b.invert();
  24953. a.build(b.allPolygons());
  24954. a.invert();
  24955. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24956. };
  24957. CSG.prototype.subtractInPlace = function (csg) {
  24958. var a = new Node(this.polygons);
  24959. var b = new Node(csg.polygons);
  24960. a.invert();
  24961. a.clipTo(b);
  24962. b.clipTo(a);
  24963. b.invert();
  24964. b.clipTo(a);
  24965. b.invert();
  24966. a.build(b.allPolygons());
  24967. a.invert();
  24968. this.polygons = a.allPolygons();
  24969. };
  24970. CSG.prototype.intersect = function (csg) {
  24971. var a = new Node(this.clone().polygons);
  24972. var b = new Node(csg.clone().polygons);
  24973. a.invert();
  24974. b.clipTo(a);
  24975. b.invert();
  24976. a.clipTo(b);
  24977. b.clipTo(a);
  24978. a.build(b.allPolygons());
  24979. a.invert();
  24980. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24981. };
  24982. CSG.prototype.intersectInPlace = function (csg) {
  24983. var a = new Node(this.polygons);
  24984. var b = new Node(csg.polygons);
  24985. a.invert();
  24986. b.clipTo(a);
  24987. b.invert();
  24988. a.clipTo(b);
  24989. b.clipTo(a);
  24990. a.build(b.allPolygons());
  24991. a.invert();
  24992. this.polygons = a.allPolygons();
  24993. };
  24994. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24995. // not modified.
  24996. CSG.prototype.inverse = function () {
  24997. var csg = this.clone();
  24998. csg.inverseInPlace();
  24999. return csg;
  25000. };
  25001. CSG.prototype.inverseInPlace = function () {
  25002. this.polygons.map(function (p) { p.flip(); });
  25003. };
  25004. // This is used to keep meshes transformations so they can be restored
  25005. // when we build back a Babylon Mesh
  25006. // NB : All CSG operations are performed in world coordinates
  25007. CSG.prototype.copyTransformAttributes = function (csg) {
  25008. this.matrix = csg.matrix;
  25009. this.position = csg.position;
  25010. this.rotation = csg.rotation;
  25011. this.scaling = csg.scaling;
  25012. this.rotationQuaternion = csg.rotationQuaternion;
  25013. return this;
  25014. };
  25015. // Build Raw mesh from CSG
  25016. // Coordinates here are in world space
  25017. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25018. var matrix = this.matrix.clone();
  25019. matrix.invert();
  25020. 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;
  25021. if (keepSubMeshes) {
  25022. // Sort Polygons, since subMeshes are indices range
  25023. polygons.sort(function (a, b) {
  25024. if (a.shared.meshId === b.shared.meshId) {
  25025. return a.shared.subMeshId - b.shared.subMeshId;
  25026. }
  25027. else {
  25028. return a.shared.meshId - b.shared.meshId;
  25029. }
  25030. });
  25031. }
  25032. for (var i = 0, il = polygons.length; i < il; i++) {
  25033. polygon = polygons[i];
  25034. // Building SubMeshes
  25035. if (!subMesh_dict[polygon.shared.meshId]) {
  25036. subMesh_dict[polygon.shared.meshId] = {};
  25037. }
  25038. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25039. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25040. indexStart: +Infinity,
  25041. indexEnd: -Infinity,
  25042. materialIndex: polygon.shared.materialIndex
  25043. };
  25044. }
  25045. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25046. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25047. polygonIndices[0] = 0;
  25048. polygonIndices[1] = j - 1;
  25049. polygonIndices[2] = j;
  25050. for (var k = 0; k < 3; k++) {
  25051. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25052. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25053. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25054. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25055. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25056. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25057. // Check if 2 points can be merged
  25058. if (!(typeof vertex_idx !== 'undefined' &&
  25059. normals[vertex_idx * 3] === localNormal.x &&
  25060. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25061. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25062. uvs[vertex_idx * 2] === uv.x &&
  25063. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25064. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25065. uvs.push(uv.x, uv.y);
  25066. normals.push(normal.x, normal.y, normal.z);
  25067. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25068. }
  25069. indices.push(vertex_idx);
  25070. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25071. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25072. currentIndex++;
  25073. }
  25074. }
  25075. }
  25076. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25077. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25078. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25079. mesh.setIndices(indices);
  25080. if (keepSubMeshes) {
  25081. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25082. var materialIndexOffset = 0, materialMaxIndex;
  25083. mesh.subMeshes.length = 0;
  25084. for (var m in subMesh_dict) {
  25085. materialMaxIndex = -1;
  25086. for (var sm in subMesh_dict[m]) {
  25087. subMesh_obj = subMesh_dict[m][sm];
  25088. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25089. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25090. }
  25091. materialIndexOffset += ++materialMaxIndex;
  25092. }
  25093. }
  25094. return mesh;
  25095. };
  25096. // Build Mesh from CSG taking material and transforms into account
  25097. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25098. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25099. mesh.material = material;
  25100. mesh.position.copyFrom(this.position);
  25101. mesh.rotation.copyFrom(this.rotation);
  25102. if (this.rotationQuaternion) {
  25103. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25104. }
  25105. mesh.scaling.copyFrom(this.scaling);
  25106. mesh.computeWorldMatrix(true);
  25107. return mesh;
  25108. };
  25109. return CSG;
  25110. })();
  25111. BABYLON.CSG = CSG;
  25112. })(BABYLON || (BABYLON = {}));
  25113. var BABYLON;
  25114. (function (BABYLON) {
  25115. var VRDistortionCorrectionPostProcess = (function (_super) {
  25116. __extends(VRDistortionCorrectionPostProcess, _super);
  25117. //ANY
  25118. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25119. var _this = this;
  25120. _super.call(this, name, "vrDistortionCorrection", [
  25121. 'LensCenter',
  25122. 'Scale',
  25123. 'ScaleIn',
  25124. 'HmdWarpParam'
  25125. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25126. this._isRightEye = isRightEye;
  25127. this._distortionFactors = vrMetrics.distortionK;
  25128. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25129. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25130. this.onSizeChanged = function () {
  25131. _this.aspectRatio = _this.width * .5 / _this.height;
  25132. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25133. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25134. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25135. };
  25136. this.onApply = function (effect) {
  25137. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25138. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25139. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25140. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25141. };
  25142. }
  25143. return VRDistortionCorrectionPostProcess;
  25144. })(BABYLON.PostProcess);
  25145. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25146. })(BABYLON || (BABYLON = {}));
  25147. // Mainly based on these 2 articles :
  25148. // 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
  25149. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25150. var BABYLON;
  25151. (function (BABYLON) {
  25152. (function (JoystickAxis) {
  25153. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25154. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25155. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25156. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25157. var JoystickAxis = BABYLON.JoystickAxis;
  25158. var VirtualJoystick = (function () {
  25159. function VirtualJoystick(leftJoystick) {
  25160. var _this = this;
  25161. if (leftJoystick) {
  25162. this._leftJoystick = true;
  25163. }
  25164. else {
  25165. this._leftJoystick = false;
  25166. }
  25167. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25168. VirtualJoystick._globalJoystickIndex++;
  25169. // By default left & right arrow keys are moving the X
  25170. // and up & down keys are moving the Y
  25171. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25172. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25173. this.reverseLeftRight = false;
  25174. this.reverseUpDown = false;
  25175. // collections of pointers
  25176. this._touches = new BABYLON.SmartCollection();
  25177. this.deltaPosition = BABYLON.Vector3.Zero();
  25178. this._joystickSensibility = 25;
  25179. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25180. this._rotationSpeed = 25;
  25181. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25182. this._rotateOnAxisRelativeToMesh = false;
  25183. this._onResize = function (evt) {
  25184. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25185. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25186. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25187. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25188. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25189. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25190. };
  25191. // injecting a canvas element on top of the canvas 3D game
  25192. if (!VirtualJoystick.vjCanvas) {
  25193. window.addEventListener("resize", this._onResize, false);
  25194. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25195. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25196. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25197. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25198. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25199. VirtualJoystick.vjCanvas.style.width = "100%";
  25200. VirtualJoystick.vjCanvas.style.height = "100%";
  25201. VirtualJoystick.vjCanvas.style.position = "absolute";
  25202. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25203. VirtualJoystick.vjCanvas.style.top = "0px";
  25204. VirtualJoystick.vjCanvas.style.left = "0px";
  25205. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25206. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25207. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25208. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25209. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25210. document.body.appendChild(VirtualJoystick.vjCanvas);
  25211. }
  25212. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25213. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25214. this.pressed = false;
  25215. // default joystick color
  25216. this._joystickColor = "cyan";
  25217. this._joystickPointerID = -1;
  25218. // current joystick position
  25219. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25220. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25221. // origin joystick position
  25222. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25223. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25224. this._onPointerDownHandlerRef = function (evt) {
  25225. _this._onPointerDown(evt);
  25226. };
  25227. this._onPointerMoveHandlerRef = function (evt) {
  25228. _this._onPointerMove(evt);
  25229. };
  25230. this._onPointerOutHandlerRef = function (evt) {
  25231. _this._onPointerUp(evt);
  25232. };
  25233. this._onPointerUpHandlerRef = function (evt) {
  25234. _this._onPointerUp(evt);
  25235. };
  25236. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25237. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25238. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25239. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25240. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25241. evt.preventDefault(); // Disables system menu
  25242. }, false);
  25243. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25244. }
  25245. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25246. this._joystickSensibility = newJoystickSensibility;
  25247. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25248. };
  25249. VirtualJoystick.prototype._onPointerDown = function (e) {
  25250. var positionOnScreenCondition;
  25251. e.preventDefault();
  25252. if (this._leftJoystick === true) {
  25253. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25254. }
  25255. else {
  25256. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25257. }
  25258. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25259. // First contact will be dedicated to the virtual joystick
  25260. this._joystickPointerID = e.pointerId;
  25261. this._joystickPointerStartPos.x = e.clientX;
  25262. this._joystickPointerStartPos.y = e.clientY;
  25263. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25264. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25265. this._deltaJoystickVector.x = 0;
  25266. this._deltaJoystickVector.y = 0;
  25267. this.pressed = true;
  25268. this._touches.add(e.pointerId.toString(), e);
  25269. }
  25270. else {
  25271. // You can only trigger the action buttons with a joystick declared
  25272. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25273. this._action();
  25274. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25275. }
  25276. }
  25277. };
  25278. VirtualJoystick.prototype._onPointerMove = function (e) {
  25279. // If the current pointer is the one associated to the joystick (first touch contact)
  25280. if (this._joystickPointerID == e.pointerId) {
  25281. this._joystickPointerPos.x = e.clientX;
  25282. this._joystickPointerPos.y = e.clientY;
  25283. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25284. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25285. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25286. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25287. switch (this._axisTargetedByLeftAndRight) {
  25288. case JoystickAxis.X:
  25289. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25290. break;
  25291. case JoystickAxis.Y:
  25292. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25293. break;
  25294. case JoystickAxis.Z:
  25295. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25296. break;
  25297. }
  25298. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25299. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25300. switch (this._axisTargetedByUpAndDown) {
  25301. case JoystickAxis.X:
  25302. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25303. break;
  25304. case JoystickAxis.Y:
  25305. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25306. break;
  25307. case JoystickAxis.Z:
  25308. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25309. break;
  25310. }
  25311. }
  25312. else {
  25313. if (this._touches.item(e.pointerId.toString())) {
  25314. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25315. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25316. }
  25317. }
  25318. };
  25319. VirtualJoystick.prototype._onPointerUp = function (e) {
  25320. if (this._joystickPointerID == e.pointerId) {
  25321. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25322. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25323. this._joystickPointerID = -1;
  25324. this.pressed = false;
  25325. }
  25326. else {
  25327. var touch = this._touches.item(e.pointerId.toString());
  25328. if (touch) {
  25329. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25330. }
  25331. }
  25332. this._deltaJoystickVector.x = 0;
  25333. this._deltaJoystickVector.y = 0;
  25334. this._touches.remove(e.pointerId.toString());
  25335. };
  25336. /**
  25337. * Change the color of the virtual joystick
  25338. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25339. */
  25340. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25341. this._joystickColor = newColor;
  25342. };
  25343. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25344. this._action = action;
  25345. };
  25346. // Define which axis you'd like to control for left & right
  25347. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25348. switch (axis) {
  25349. case JoystickAxis.X:
  25350. case JoystickAxis.Y:
  25351. case JoystickAxis.Z:
  25352. this._axisTargetedByLeftAndRight = axis;
  25353. break;
  25354. default:
  25355. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25356. break;
  25357. }
  25358. };
  25359. // Define which axis you'd like to control for up & down
  25360. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  25361. switch (axis) {
  25362. case JoystickAxis.X:
  25363. case JoystickAxis.Y:
  25364. case JoystickAxis.Z:
  25365. this._axisTargetedByUpAndDown = axis;
  25366. break;
  25367. default:
  25368. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25369. break;
  25370. }
  25371. };
  25372. VirtualJoystick.prototype._clearCanvas = function () {
  25373. if (this._leftJoystick) {
  25374. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  25375. }
  25376. else {
  25377. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  25378. }
  25379. };
  25380. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  25381. var _this = this;
  25382. if (this.pressed) {
  25383. this._touches.forEach(function (touch) {
  25384. if (touch.pointerId === _this._joystickPointerID) {
  25385. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  25386. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  25387. VirtualJoystick.vjCanvasContext.beginPath();
  25388. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25389. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25390. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  25391. VirtualJoystick.vjCanvasContext.stroke();
  25392. VirtualJoystick.vjCanvasContext.closePath();
  25393. VirtualJoystick.vjCanvasContext.beginPath();
  25394. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25395. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25396. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  25397. VirtualJoystick.vjCanvasContext.stroke();
  25398. VirtualJoystick.vjCanvasContext.closePath();
  25399. VirtualJoystick.vjCanvasContext.beginPath();
  25400. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25401. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  25402. VirtualJoystick.vjCanvasContext.stroke();
  25403. VirtualJoystick.vjCanvasContext.closePath();
  25404. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  25405. }
  25406. else {
  25407. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25408. VirtualJoystick.vjCanvasContext.beginPath();
  25409. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  25410. VirtualJoystick.vjCanvasContext.beginPath();
  25411. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  25412. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25413. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  25414. VirtualJoystick.vjCanvasContext.stroke();
  25415. VirtualJoystick.vjCanvasContext.closePath();
  25416. touch.prevX = touch.x;
  25417. touch.prevY = touch.y;
  25418. }
  25419. ;
  25420. });
  25421. }
  25422. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25423. };
  25424. VirtualJoystick.prototype.releaseCanvas = function () {
  25425. if (VirtualJoystick.vjCanvas) {
  25426. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  25427. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  25428. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  25429. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  25430. window.removeEventListener("resize", this._onResize);
  25431. document.body.removeChild(VirtualJoystick.vjCanvas);
  25432. VirtualJoystick.vjCanvas = null;
  25433. }
  25434. };
  25435. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  25436. VirtualJoystick._globalJoystickIndex = 0;
  25437. return VirtualJoystick;
  25438. })();
  25439. BABYLON.VirtualJoystick = VirtualJoystick;
  25440. })(BABYLON || (BABYLON = {}));
  25441. var BABYLON;
  25442. (function (BABYLON) {
  25443. // We're mainly based on the logic defined into the FreeCamera code
  25444. var VirtualJoysticksCamera = (function (_super) {
  25445. __extends(VirtualJoysticksCamera, _super);
  25446. function VirtualJoysticksCamera(name, position, scene) {
  25447. _super.call(this, name, position, scene);
  25448. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  25449. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  25450. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  25451. this._leftjoystick.setJoystickSensibility(0.15);
  25452. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  25453. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  25454. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  25455. this._rightjoystick.reverseUpDown = true;
  25456. this._rightjoystick.setJoystickSensibility(0.05);
  25457. this._rightjoystick.setJoystickColor("yellow");
  25458. }
  25459. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  25460. return this._leftjoystick;
  25461. };
  25462. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  25463. return this._rightjoystick;
  25464. };
  25465. VirtualJoysticksCamera.prototype._checkInputs = function () {
  25466. var speed = this._computeLocalCameraSpeed() * 50;
  25467. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25468. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  25469. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25470. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  25471. if (!this._leftjoystick.pressed) {
  25472. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  25473. }
  25474. if (!this._rightjoystick.pressed) {
  25475. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  25476. }
  25477. _super.prototype._checkInputs.call(this);
  25478. };
  25479. VirtualJoysticksCamera.prototype.dispose = function () {
  25480. this._leftjoystick.releaseCanvas();
  25481. _super.prototype.dispose.call(this);
  25482. };
  25483. return VirtualJoysticksCamera;
  25484. })(BABYLON.FreeCamera);
  25485. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  25486. })(BABYLON || (BABYLON = {}));
  25487. var BABYLON;
  25488. (function (BABYLON) {
  25489. var ShaderMaterial = (function (_super) {
  25490. __extends(ShaderMaterial, _super);
  25491. function ShaderMaterial(name, scene, shaderPath, options) {
  25492. _super.call(this, name, scene);
  25493. this._textures = new Array();
  25494. this._floats = new Array();
  25495. this._floatsArrays = {};
  25496. this._colors3 = new Array();
  25497. this._colors4 = new Array();
  25498. this._vectors2 = new Array();
  25499. this._vectors3 = new Array();
  25500. this._vectors4 = new Array();
  25501. this._matrices = new Array();
  25502. this._matrices3x3 = new Array();
  25503. this._matrices2x2 = new Array();
  25504. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  25505. this._shaderPath = shaderPath;
  25506. options.needAlphaBlending = options.needAlphaBlending || false;
  25507. options.needAlphaTesting = options.needAlphaTesting || false;
  25508. options.attributes = options.attributes || ["position", "normal", "uv"];
  25509. options.uniforms = options.uniforms || ["worldViewProjection"];
  25510. options.samplers = options.samplers || [];
  25511. this._options = options;
  25512. }
  25513. ShaderMaterial.prototype.needAlphaBlending = function () {
  25514. return this._options.needAlphaBlending;
  25515. };
  25516. ShaderMaterial.prototype.needAlphaTesting = function () {
  25517. return this._options.needAlphaTesting;
  25518. };
  25519. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  25520. if (this._options.uniforms.indexOf(uniformName) === -1) {
  25521. this._options.uniforms.push(uniformName);
  25522. }
  25523. };
  25524. ShaderMaterial.prototype.setTexture = function (name, texture) {
  25525. if (this._options.samplers.indexOf(name) === -1) {
  25526. this._options.samplers.push(name);
  25527. }
  25528. this._textures[name] = texture;
  25529. return this;
  25530. };
  25531. ShaderMaterial.prototype.setFloat = function (name, value) {
  25532. this._checkUniform(name);
  25533. this._floats[name] = value;
  25534. return this;
  25535. };
  25536. ShaderMaterial.prototype.setFloats = function (name, value) {
  25537. this._checkUniform(name);
  25538. this._floatsArrays[name] = value;
  25539. return this;
  25540. };
  25541. ShaderMaterial.prototype.setColor3 = function (name, value) {
  25542. this._checkUniform(name);
  25543. this._colors3[name] = value;
  25544. return this;
  25545. };
  25546. ShaderMaterial.prototype.setColor4 = function (name, value) {
  25547. this._checkUniform(name);
  25548. this._colors4[name] = value;
  25549. return this;
  25550. };
  25551. ShaderMaterial.prototype.setVector2 = function (name, value) {
  25552. this._checkUniform(name);
  25553. this._vectors2[name] = value;
  25554. return this;
  25555. };
  25556. ShaderMaterial.prototype.setVector3 = function (name, value) {
  25557. this._checkUniform(name);
  25558. this._vectors3[name] = value;
  25559. return this;
  25560. };
  25561. ShaderMaterial.prototype.setVector4 = function (name, value) {
  25562. this._checkUniform(name);
  25563. this._vectors4[name] = value;
  25564. return this;
  25565. };
  25566. ShaderMaterial.prototype.setMatrix = function (name, value) {
  25567. this._checkUniform(name);
  25568. this._matrices[name] = value;
  25569. return this;
  25570. };
  25571. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  25572. this._checkUniform(name);
  25573. this._matrices3x3[name] = value;
  25574. return this;
  25575. };
  25576. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  25577. this._checkUniform(name);
  25578. this._matrices2x2[name] = value;
  25579. return this;
  25580. };
  25581. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  25582. var scene = this.getScene();
  25583. var engine = scene.getEngine();
  25584. if (!this.checkReadyOnEveryCall) {
  25585. if (this._renderId === scene.getRenderId()) {
  25586. return true;
  25587. }
  25588. }
  25589. // Instances
  25590. var defines = [];
  25591. var fallbacks = new BABYLON.EffectFallbacks();
  25592. if (useInstances) {
  25593. defines.push("#define INSTANCES");
  25594. }
  25595. // Bones
  25596. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25597. defines.push("#define BONES");
  25598. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25599. defines.push("#define BONES4");
  25600. fallbacks.addFallback(0, "BONES4");
  25601. }
  25602. // Alpha test
  25603. if (engine.getAlphaTesting()) {
  25604. defines.push("#define ALPHATEST");
  25605. }
  25606. var previousEffect = this._effect;
  25607. var join = defines.join("\n");
  25608. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  25609. if (!this._effect.isReady()) {
  25610. return false;
  25611. }
  25612. if (previousEffect !== this._effect) {
  25613. scene.resetCachedMaterial();
  25614. }
  25615. this._renderId = scene.getRenderId();
  25616. return true;
  25617. };
  25618. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25619. var scene = this.getScene();
  25620. if (this._options.uniforms.indexOf("world") !== -1) {
  25621. this._effect.setMatrix("world", world);
  25622. }
  25623. if (this._options.uniforms.indexOf("worldView") !== -1) {
  25624. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  25625. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  25626. }
  25627. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  25628. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  25629. }
  25630. };
  25631. ShaderMaterial.prototype.bind = function (world, mesh) {
  25632. // Std values
  25633. this.bindOnlyWorldMatrix(world);
  25634. if (this.getScene().getCachedMaterial() !== this) {
  25635. if (this._options.uniforms.indexOf("view") !== -1) {
  25636. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  25637. }
  25638. if (this._options.uniforms.indexOf("projection") !== -1) {
  25639. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  25640. }
  25641. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  25642. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25643. }
  25644. // Bones
  25645. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25646. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25647. }
  25648. // Texture
  25649. for (var name in this._textures) {
  25650. this._effect.setTexture(name, this._textures[name]);
  25651. }
  25652. // Float
  25653. for (name in this._floats) {
  25654. this._effect.setFloat(name, this._floats[name]);
  25655. }
  25656. // Float s
  25657. for (name in this._floatsArrays) {
  25658. this._effect.setArray(name, this._floatsArrays[name]);
  25659. }
  25660. // Color3
  25661. for (name in this._colors3) {
  25662. this._effect.setColor3(name, this._colors3[name]);
  25663. }
  25664. // Color4
  25665. for (name in this._colors4) {
  25666. var color = this._colors4[name];
  25667. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25668. }
  25669. // Vector2
  25670. for (name in this._vectors2) {
  25671. this._effect.setVector2(name, this._vectors2[name]);
  25672. }
  25673. // Vector3
  25674. for (name in this._vectors3) {
  25675. this._effect.setVector3(name, this._vectors3[name]);
  25676. }
  25677. // Vector4
  25678. for (name in this._vectors4) {
  25679. this._effect.setVector4(name, this._vectors4[name]);
  25680. }
  25681. // Matrix
  25682. for (name in this._matrices) {
  25683. this._effect.setMatrix(name, this._matrices[name]);
  25684. }
  25685. // Matrix 3x3
  25686. for (name in this._matrices3x3) {
  25687. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  25688. }
  25689. // Matrix 2x2
  25690. for (name in this._matrices2x2) {
  25691. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  25692. }
  25693. }
  25694. _super.prototype.bind.call(this, world, mesh);
  25695. };
  25696. ShaderMaterial.prototype.clone = function (name) {
  25697. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  25698. return newShaderMaterial;
  25699. };
  25700. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  25701. for (var name in this._textures) {
  25702. this._textures[name].dispose();
  25703. }
  25704. this._textures = [];
  25705. _super.prototype.dispose.call(this, forceDisposeEffect);
  25706. };
  25707. return ShaderMaterial;
  25708. })(BABYLON.Material);
  25709. BABYLON.ShaderMaterial = ShaderMaterial;
  25710. })(BABYLON || (BABYLON = {}));
  25711. var BABYLON;
  25712. (function (BABYLON) {
  25713. var VertexData = (function () {
  25714. function VertexData() {
  25715. }
  25716. VertexData.prototype.set = function (data, kind) {
  25717. switch (kind) {
  25718. case BABYLON.VertexBuffer.PositionKind:
  25719. this.positions = data;
  25720. break;
  25721. case BABYLON.VertexBuffer.NormalKind:
  25722. this.normals = data;
  25723. break;
  25724. case BABYLON.VertexBuffer.UVKind:
  25725. this.uvs = data;
  25726. break;
  25727. case BABYLON.VertexBuffer.UV2Kind:
  25728. this.uvs2 = data;
  25729. break;
  25730. case BABYLON.VertexBuffer.UV3Kind:
  25731. this.uvs3 = data;
  25732. break;
  25733. case BABYLON.VertexBuffer.UV4Kind:
  25734. this.uvs4 = data;
  25735. break;
  25736. case BABYLON.VertexBuffer.UV5Kind:
  25737. this.uvs5 = data;
  25738. break;
  25739. case BABYLON.VertexBuffer.UV6Kind:
  25740. this.uvs6 = data;
  25741. break;
  25742. case BABYLON.VertexBuffer.ColorKind:
  25743. this.colors = data;
  25744. break;
  25745. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25746. this.matricesIndices = data;
  25747. break;
  25748. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25749. this.matricesWeights = data;
  25750. break;
  25751. }
  25752. };
  25753. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25754. this._applyTo(mesh, updatable);
  25755. };
  25756. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25757. this._applyTo(geometry, updatable);
  25758. };
  25759. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25760. this._update(mesh);
  25761. };
  25762. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25763. this._update(geometry);
  25764. };
  25765. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25766. if (this.positions) {
  25767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25768. }
  25769. if (this.normals) {
  25770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25771. }
  25772. if (this.uvs) {
  25773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25774. }
  25775. if (this.uvs2) {
  25776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25777. }
  25778. if (this.uvs3) {
  25779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25780. }
  25781. if (this.uvs4) {
  25782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25783. }
  25784. if (this.uvs5) {
  25785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25786. }
  25787. if (this.uvs6) {
  25788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25789. }
  25790. if (this.colors) {
  25791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25792. }
  25793. if (this.matricesIndices) {
  25794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25795. }
  25796. if (this.matricesWeights) {
  25797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25798. }
  25799. if (this.indices) {
  25800. meshOrGeometry.setIndices(this.indices);
  25801. }
  25802. };
  25803. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25804. if (this.positions) {
  25805. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25806. }
  25807. if (this.normals) {
  25808. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25809. }
  25810. if (this.uvs) {
  25811. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25812. }
  25813. if (this.uvs2) {
  25814. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25815. }
  25816. if (this.uvs3) {
  25817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25818. }
  25819. if (this.uvs4) {
  25820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25821. }
  25822. if (this.uvs5) {
  25823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25824. }
  25825. if (this.uvs6) {
  25826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25827. }
  25828. if (this.colors) {
  25829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25830. }
  25831. if (this.matricesIndices) {
  25832. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25833. }
  25834. if (this.matricesWeights) {
  25835. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25836. }
  25837. if (this.indices) {
  25838. meshOrGeometry.setIndices(this.indices);
  25839. }
  25840. };
  25841. VertexData.prototype.transform = function (matrix) {
  25842. var transformed = BABYLON.Vector3.Zero();
  25843. if (this.positions) {
  25844. var position = BABYLON.Vector3.Zero();
  25845. for (var index = 0; index < this.positions.length; index += 3) {
  25846. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25847. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25848. this.positions[index] = transformed.x;
  25849. this.positions[index + 1] = transformed.y;
  25850. this.positions[index + 2] = transformed.z;
  25851. }
  25852. }
  25853. if (this.normals) {
  25854. var normal = BABYLON.Vector3.Zero();
  25855. for (index = 0; index < this.normals.length; index += 3) {
  25856. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25857. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25858. this.normals[index] = transformed.x;
  25859. this.normals[index + 1] = transformed.y;
  25860. this.normals[index + 2] = transformed.z;
  25861. }
  25862. }
  25863. };
  25864. VertexData.prototype.merge = function (other) {
  25865. if (other.indices) {
  25866. if (!this.indices) {
  25867. this.indices = [];
  25868. }
  25869. var offset = this.positions ? this.positions.length / 3 : 0;
  25870. for (var index = 0; index < other.indices.length; index++) {
  25871. this.indices.push(other.indices[index] + offset);
  25872. }
  25873. }
  25874. if (other.positions) {
  25875. if (!this.positions) {
  25876. this.positions = [];
  25877. }
  25878. for (index = 0; index < other.positions.length; index++) {
  25879. this.positions.push(other.positions[index]);
  25880. }
  25881. }
  25882. if (other.normals) {
  25883. if (!this.normals) {
  25884. this.normals = [];
  25885. }
  25886. for (index = 0; index < other.normals.length; index++) {
  25887. this.normals.push(other.normals[index]);
  25888. }
  25889. }
  25890. if (other.uvs) {
  25891. if (!this.uvs) {
  25892. this.uvs = [];
  25893. }
  25894. for (index = 0; index < other.uvs.length; index++) {
  25895. this.uvs.push(other.uvs[index]);
  25896. }
  25897. }
  25898. if (other.uvs2) {
  25899. if (!this.uvs2) {
  25900. this.uvs2 = [];
  25901. }
  25902. for (index = 0; index < other.uvs2.length; index++) {
  25903. this.uvs2.push(other.uvs2[index]);
  25904. }
  25905. }
  25906. if (other.uvs3) {
  25907. if (!this.uvs3) {
  25908. this.uvs3 = [];
  25909. }
  25910. for (index = 0; index < other.uvs3.length; index++) {
  25911. this.uvs3.push(other.uvs3[index]);
  25912. }
  25913. }
  25914. if (other.uvs4) {
  25915. if (!this.uvs4) {
  25916. this.uvs4 = [];
  25917. }
  25918. for (index = 0; index < other.uvs4.length; index++) {
  25919. this.uvs4.push(other.uvs4[index]);
  25920. }
  25921. }
  25922. if (other.uvs5) {
  25923. if (!this.uvs5) {
  25924. this.uvs5 = [];
  25925. }
  25926. for (index = 0; index < other.uvs5.length; index++) {
  25927. this.uvs5.push(other.uvs5[index]);
  25928. }
  25929. }
  25930. if (other.uvs6) {
  25931. if (!this.uvs6) {
  25932. this.uvs6 = [];
  25933. }
  25934. for (index = 0; index < other.uvs6.length; index++) {
  25935. this.uvs6.push(other.uvs6[index]);
  25936. }
  25937. }
  25938. if (other.matricesIndices) {
  25939. if (!this.matricesIndices) {
  25940. this.matricesIndices = [];
  25941. }
  25942. for (index = 0; index < other.matricesIndices.length; index++) {
  25943. this.matricesIndices.push(other.matricesIndices[index]);
  25944. }
  25945. }
  25946. if (other.matricesWeights) {
  25947. if (!this.matricesWeights) {
  25948. this.matricesWeights = [];
  25949. }
  25950. for (index = 0; index < other.matricesWeights.length; index++) {
  25951. this.matricesWeights.push(other.matricesWeights[index]);
  25952. }
  25953. }
  25954. if (other.colors) {
  25955. if (!this.colors) {
  25956. this.colors = [];
  25957. }
  25958. for (index = 0; index < other.colors.length; index++) {
  25959. this.colors.push(other.colors[index]);
  25960. }
  25961. }
  25962. };
  25963. // Statics
  25964. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  25965. return VertexData._ExtractFrom(mesh, copyWhenShared);
  25966. };
  25967. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  25968. return VertexData._ExtractFrom(geometry, copyWhenShared);
  25969. };
  25970. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  25971. var result = new VertexData();
  25972. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25973. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  25974. }
  25975. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25976. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  25977. }
  25978. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25979. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  25980. }
  25981. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25982. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  25983. }
  25984. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  25985. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  25986. }
  25987. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  25988. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  25989. }
  25990. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  25991. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  25992. }
  25993. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  25994. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  25995. }
  25996. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25997. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  25998. }
  25999. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26000. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26001. }
  26002. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26003. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26004. }
  26005. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26006. return result;
  26007. };
  26008. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  26009. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26010. closeArray = closeArray || false;
  26011. closePath = closePath || false;
  26012. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26013. offset = offset || defaultOffset;
  26014. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26015. var positions = [];
  26016. var indices = [];
  26017. var normals = [];
  26018. var uvs = [];
  26019. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26020. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26021. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26022. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26023. var minlg; // minimal length among all paths from pathArray
  26024. var lg = []; // array of path lengths : nb of vertex per path
  26025. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26026. var p; // path iterator
  26027. var i; // point iterator
  26028. var j; // point iterator
  26029. // if single path in pathArray
  26030. if (pathArray.length < 2) {
  26031. var ar1 = [];
  26032. var ar2 = [];
  26033. for (i = 0; i < pathArray[0].length - offset; i++) {
  26034. ar1.push(pathArray[0][i]);
  26035. ar2.push(pathArray[0][i + offset]);
  26036. }
  26037. pathArray = [ar1, ar2];
  26038. }
  26039. // positions and horizontal distances (u)
  26040. var idc = 0;
  26041. var closePathCorr = (closePath) ? 1 : 0;
  26042. var path;
  26043. var l;
  26044. minlg = pathArray[0].length;
  26045. for (p = 0; p < pathArray.length; p++) {
  26046. uTotalDistance[p] = 0;
  26047. us[p] = [0];
  26048. path = pathArray[p];
  26049. l = path.length;
  26050. minlg = (minlg < l) ? minlg : l;
  26051. j = 0;
  26052. while (j < l) {
  26053. positions.push(path[j].x, path[j].y, path[j].z);
  26054. if (j > 0) {
  26055. var vectlg = path[j].subtract(path[j - 1]).length();
  26056. var dist = vectlg + uTotalDistance[p];
  26057. us[p].push(dist);
  26058. uTotalDistance[p] = dist;
  26059. }
  26060. j++;
  26061. }
  26062. if (closePath) {
  26063. j--;
  26064. positions.push(path[0].x, path[0].y, path[0].z);
  26065. vectlg = path[j].subtract(path[0]).length();
  26066. dist = vectlg + uTotalDistance[p];
  26067. us[p].push(dist);
  26068. uTotalDistance[p] = dist;
  26069. }
  26070. lg[p] = l + closePathCorr;
  26071. idx[p] = idc;
  26072. idc += (l + closePathCorr);
  26073. }
  26074. // vertical distances (v)
  26075. var path1;
  26076. var path2;
  26077. var vertex1;
  26078. var vertex2;
  26079. for (i = 0; i < minlg + closePathCorr; i++) {
  26080. vTotalDistance[i] = 0;
  26081. vs[i] = [0];
  26082. for (p = 0; p < pathArray.length - 1; p++) {
  26083. path1 = pathArray[p];
  26084. path2 = pathArray[p + 1];
  26085. if (i === minlg) {
  26086. vertex1 = path1[0];
  26087. vertex2 = path2[0];
  26088. }
  26089. else {
  26090. vertex1 = path1[i];
  26091. vertex2 = path2[i];
  26092. }
  26093. vectlg = vertex2.subtract(vertex1).length();
  26094. dist = vectlg + vTotalDistance[i];
  26095. vs[i].push(dist);
  26096. vTotalDistance[i] = dist;
  26097. }
  26098. if (closeArray) {
  26099. path1 = pathArray[p];
  26100. path2 = pathArray[0];
  26101. vectlg = path2[i].subtract(path1[i]).length();
  26102. dist = vectlg + vTotalDistance[i];
  26103. vTotalDistance[i] = dist;
  26104. }
  26105. }
  26106. // uvs
  26107. var u;
  26108. var v;
  26109. for (p = 0; p < pathArray.length; p++) {
  26110. for (i = 0; i < minlg + closePathCorr; i++) {
  26111. u = us[p][i] / uTotalDistance[p];
  26112. v = vs[i][p] / vTotalDistance[i];
  26113. uvs.push(u, v);
  26114. }
  26115. }
  26116. // indices
  26117. p = 0; // path index
  26118. var pi = 0; // positions array index
  26119. var l1 = lg[p] - 1; // path1 length
  26120. var l2 = lg[p + 1] - 1; // path2 length
  26121. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26122. var shft = idx[1] - idx[0]; // shift
  26123. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26124. while (pi <= min && p < path1nb) {
  26125. // 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
  26126. indices.push(pi, pi + shft, pi + 1);
  26127. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26128. pi += 1;
  26129. if (pi === min) {
  26130. p++;
  26131. if (p === lg.length - 1) {
  26132. shft = idx[0] - idx[p];
  26133. l1 = lg[p] - 1;
  26134. l2 = lg[0] - 1;
  26135. }
  26136. else {
  26137. shft = idx[p + 1] - idx[p];
  26138. l1 = lg[p] - 1;
  26139. l2 = lg[p + 1] - 1;
  26140. }
  26141. pi = idx[p];
  26142. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26143. }
  26144. }
  26145. // normals
  26146. VertexData.ComputeNormals(positions, indices, normals);
  26147. if (closePath) {
  26148. var indexFirst = 0;
  26149. var indexLast = 0;
  26150. for (p = 0; p < pathArray.length; p++) {
  26151. indexFirst = idx[p] * 3;
  26152. if (p + 1 < pathArray.length) {
  26153. indexLast = (idx[p + 1] - 1) * 3;
  26154. }
  26155. else {
  26156. indexLast = normals.length - 3;
  26157. }
  26158. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26159. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26160. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26161. normals[indexLast] = normals[indexFirst];
  26162. normals[indexLast + 1] = normals[indexFirst + 1];
  26163. normals[indexLast + 2] = normals[indexFirst + 2];
  26164. }
  26165. }
  26166. // sides
  26167. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26168. // Result
  26169. var vertexData = new VertexData();
  26170. vertexData.indices = indices;
  26171. vertexData.positions = positions;
  26172. vertexData.normals = normals;
  26173. vertexData.uvs = uvs;
  26174. if (closePath) {
  26175. vertexData._idx = idx;
  26176. }
  26177. return vertexData;
  26178. };
  26179. VertexData.CreateBox = function (size, sideOrientation) {
  26180. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26181. var normalsSource = [
  26182. new BABYLON.Vector3(0, 0, 1),
  26183. new BABYLON.Vector3(0, 0, -1),
  26184. new BABYLON.Vector3(1, 0, 0),
  26185. new BABYLON.Vector3(-1, 0, 0),
  26186. new BABYLON.Vector3(0, 1, 0),
  26187. new BABYLON.Vector3(0, -1, 0)
  26188. ];
  26189. var indices = [];
  26190. var positions = [];
  26191. var normals = [];
  26192. var uvs = [];
  26193. size = size || 1;
  26194. // Create each face in turn.
  26195. for (var index = 0; index < normalsSource.length; index++) {
  26196. var normal = normalsSource[index];
  26197. // Get two vectors perpendicular to the face normal and to each other.
  26198. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26199. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26200. // Six indices (two triangles) per face.
  26201. var verticesLength = positions.length / 3;
  26202. indices.push(verticesLength);
  26203. indices.push(verticesLength + 1);
  26204. indices.push(verticesLength + 2);
  26205. indices.push(verticesLength);
  26206. indices.push(verticesLength + 2);
  26207. indices.push(verticesLength + 3);
  26208. // Four vertices per face.
  26209. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  26210. positions.push(vertex.x, vertex.y, vertex.z);
  26211. normals.push(normal.x, normal.y, normal.z);
  26212. uvs.push(1.0, 1.0);
  26213. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  26214. positions.push(vertex.x, vertex.y, vertex.z);
  26215. normals.push(normal.x, normal.y, normal.z);
  26216. uvs.push(0.0, 1.0);
  26217. vertex = normal.add(side1).add(side2).scale(size / 2);
  26218. positions.push(vertex.x, vertex.y, vertex.z);
  26219. normals.push(normal.x, normal.y, normal.z);
  26220. uvs.push(0.0, 0.0);
  26221. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  26222. positions.push(vertex.x, vertex.y, vertex.z);
  26223. normals.push(normal.x, normal.y, normal.z);
  26224. uvs.push(1.0, 0.0);
  26225. }
  26226. // sides
  26227. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26228. // Result
  26229. var vertexData = new VertexData();
  26230. vertexData.indices = indices;
  26231. vertexData.positions = positions;
  26232. vertexData.normals = normals;
  26233. vertexData.uvs = uvs;
  26234. return vertexData;
  26235. };
  26236. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  26237. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26238. segments = segments || 32;
  26239. diameter = diameter || 1;
  26240. var radius = diameter / 2;
  26241. var totalZRotationSteps = 2 + segments;
  26242. var totalYRotationSteps = 2 * totalZRotationSteps;
  26243. var indices = [];
  26244. var positions = [];
  26245. var normals = [];
  26246. var uvs = [];
  26247. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26248. var normalizedZ = zRotationStep / totalZRotationSteps;
  26249. var angleZ = (normalizedZ * Math.PI);
  26250. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26251. var normalizedY = yRotationStep / totalYRotationSteps;
  26252. var angleY = normalizedY * Math.PI * 2;
  26253. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26254. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26255. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26256. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26257. var vertex = complete.scale(radius);
  26258. var normal = BABYLON.Vector3.Normalize(vertex);
  26259. positions.push(vertex.x, vertex.y, vertex.z);
  26260. normals.push(normal.x, normal.y, normal.z);
  26261. uvs.push(normalizedZ, normalizedY);
  26262. }
  26263. if (zRotationStep > 0) {
  26264. var verticesCount = positions.length / 3;
  26265. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26266. indices.push((firstIndex));
  26267. indices.push((firstIndex + 1));
  26268. indices.push(firstIndex + totalYRotationSteps + 1);
  26269. indices.push((firstIndex + totalYRotationSteps + 1));
  26270. indices.push((firstIndex + 1));
  26271. indices.push((firstIndex + totalYRotationSteps + 2));
  26272. }
  26273. }
  26274. }
  26275. // Sides
  26276. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26277. // Result
  26278. var vertexData = new VertexData();
  26279. vertexData.indices = indices;
  26280. vertexData.positions = positions;
  26281. vertexData.normals = normals;
  26282. vertexData.uvs = uvs;
  26283. return vertexData;
  26284. };
  26285. // Cylinder and cone (made using ribbons)
  26286. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  26287. if (subdivisions === void 0) { subdivisions = 1; }
  26288. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26289. // setup tube creation parameters
  26290. var path = [];
  26291. for (var i = 0; i <= subdivisions; i++) {
  26292. path.push(new BABYLON.Vector3(0, height * (-0.5 + i / subdivisions), 0));
  26293. }
  26294. // this is what defines the radius along the cylinder
  26295. var radiusFunction = function (i, distance) {
  26296. return (diameterBottom + (diameterTop - diameterBottom) * distance / height) / 2;
  26297. };
  26298. // shortcut to 3d path data
  26299. var path3D = new BABYLON.Path3D(path);
  26300. var tangents = path3D.getTangents();
  26301. var normals = path3D.getNormals();
  26302. var distances = path3D.getDistances();
  26303. // let's build the array of paths (rings)
  26304. var pathArray = [];
  26305. var ringVertex;
  26306. var angle;
  26307. var angle_step = Math.PI * 2 / tessellation;
  26308. var distance = 0;
  26309. for (var i = 0; i <= subdivisions; i++) {
  26310. pathArray[i] = [];
  26311. for (var j = 0; j < tessellation; j++) {
  26312. angle = j * angle_step;
  26313. ringVertex = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26314. ringVertex.scaleInPlace(radiusFunction(i, distances[i])).addInPlace(path[i]);
  26315. pathArray[i].push(ringVertex);
  26316. }
  26317. }
  26318. // create ribbon based on computed paths (& close seam)
  26319. var vertexdata = VertexData.CreateRibbon(pathArray, false, true, 0, sideOrientation);
  26320. var createCylinderCap = function (isTop) {
  26321. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26322. if (radius === 0) {
  26323. return;
  26324. }
  26325. var vbase = vertexdata.positions.length / 3;
  26326. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  26327. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26328. // Positions, normals & uvs
  26329. var angle;
  26330. var circleVector;
  26331. for (var i = 0; i < tessellation; i++) {
  26332. angle = Math.PI * 2 * i / tessellation;
  26333. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26334. var position = circleVector.scale(radius).add(offset);
  26335. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  26336. vertexdata.positions.push(position.x, position.y, position.z);
  26337. vertexdata.normals.push(0, isTop ? 1 : -1, 0);
  26338. vertexdata.uvs.push(textureCoordinate.x, textureCoordinate.y);
  26339. }
  26340. // Indices
  26341. for (i = 0; i < tessellation - 2; i++) {
  26342. if (!isTop) {
  26343. vertexdata.indices.push(vbase);
  26344. vertexdata.indices.push(vbase + (i + 1) % tessellation);
  26345. vertexdata.indices.push(vbase + (i + 2) % tessellation);
  26346. }
  26347. else {
  26348. vertexdata.indices.push(vbase);
  26349. vertexdata.indices.push(vbase + (i + 2) % tessellation);
  26350. vertexdata.indices.push(vbase + (i + 1) % tessellation);
  26351. }
  26352. }
  26353. };
  26354. // add caps to geometry
  26355. createCylinderCap(true);
  26356. createCylinderCap(false);
  26357. return vertexdata;
  26358. };
  26359. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  26360. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26361. var indices = [];
  26362. var positions = [];
  26363. var normals = [];
  26364. var uvs = [];
  26365. diameter = diameter || 1;
  26366. thickness = thickness || 0.5;
  26367. tessellation = tessellation || 16;
  26368. var stride = tessellation + 1;
  26369. for (var i = 0; i <= tessellation; i++) {
  26370. var u = i / tessellation;
  26371. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26372. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26373. for (var j = 0; j <= tessellation; j++) {
  26374. var v = 1 - j / tessellation;
  26375. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26376. var dx = Math.cos(innerAngle);
  26377. var dy = Math.sin(innerAngle);
  26378. // Create a vertex.
  26379. var normal = new BABYLON.Vector3(dx, dy, 0);
  26380. var position = normal.scale(thickness / 2);
  26381. var textureCoordinate = new BABYLON.Vector2(u, v);
  26382. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26383. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26384. positions.push(position.x, position.y, position.z);
  26385. normals.push(normal.x, normal.y, normal.z);
  26386. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26387. // And create indices for two triangles.
  26388. var nextI = (i + 1) % stride;
  26389. var nextJ = (j + 1) % stride;
  26390. indices.push(i * stride + j);
  26391. indices.push(i * stride + nextJ);
  26392. indices.push(nextI * stride + j);
  26393. indices.push(i * stride + nextJ);
  26394. indices.push(nextI * stride + nextJ);
  26395. indices.push(nextI * stride + j);
  26396. }
  26397. }
  26398. // Sides
  26399. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26400. // Result
  26401. var vertexData = new VertexData();
  26402. vertexData.indices = indices;
  26403. vertexData.positions = positions;
  26404. vertexData.normals = normals;
  26405. vertexData.uvs = uvs;
  26406. return vertexData;
  26407. };
  26408. VertexData.CreateLines = function (points) {
  26409. var indices = [];
  26410. var positions = [];
  26411. for (var index = 0; index < points.length; index++) {
  26412. positions.push(points[index].x, points[index].y, points[index].z);
  26413. if (index > 0) {
  26414. indices.push(index - 1);
  26415. indices.push(index);
  26416. }
  26417. }
  26418. // Result
  26419. var vertexData = new VertexData();
  26420. vertexData.indices = indices;
  26421. vertexData.positions = positions;
  26422. return vertexData;
  26423. };
  26424. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  26425. dashSize = dashSize || 3;
  26426. gapSize = gapSize || 1;
  26427. dashNb = dashNb || 200;
  26428. var positions = new Array();
  26429. var indices = new Array();
  26430. var curvect = BABYLON.Vector3.Zero();
  26431. var lg = 0;
  26432. var nb = 0;
  26433. var shft = 0;
  26434. var dashshft = 0;
  26435. var curshft = 0;
  26436. var idx = 0;
  26437. var i = 0;
  26438. for (i = 0; i < points.length - 1; i++) {
  26439. points[i + 1].subtractToRef(points[i], curvect);
  26440. lg += curvect.length();
  26441. }
  26442. shft = lg / dashNb;
  26443. dashshft = dashSize * shft / (dashSize + gapSize);
  26444. for (i = 0; i < points.length - 1; i++) {
  26445. points[i + 1].subtractToRef(points[i], curvect);
  26446. nb = Math.floor(curvect.length() / shft);
  26447. curvect.normalize();
  26448. for (var j = 0; j < nb; j++) {
  26449. curshft = shft * j;
  26450. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26451. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26452. indices.push(idx, idx + 1);
  26453. idx += 2;
  26454. }
  26455. }
  26456. // Result
  26457. var vertexData = new VertexData();
  26458. vertexData.positions = positions;
  26459. vertexData.indices = indices;
  26460. return vertexData;
  26461. };
  26462. VertexData.CreateGround = function (width, height, subdivisions) {
  26463. var indices = [];
  26464. var positions = [];
  26465. var normals = [];
  26466. var uvs = [];
  26467. var row, col;
  26468. width = width || 1;
  26469. height = height || 1;
  26470. subdivisions = subdivisions || 1;
  26471. for (row = 0; row <= subdivisions; row++) {
  26472. for (col = 0; col <= subdivisions; col++) {
  26473. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26474. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26475. positions.push(position.x, position.y, position.z);
  26476. normals.push(normal.x, normal.y, normal.z);
  26477. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26478. }
  26479. }
  26480. for (row = 0; row < subdivisions; row++) {
  26481. for (col = 0; col < subdivisions; col++) {
  26482. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26483. indices.push(col + 1 + row * (subdivisions + 1));
  26484. indices.push(col + row * (subdivisions + 1));
  26485. indices.push(col + (row + 1) * (subdivisions + 1));
  26486. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26487. indices.push(col + row * (subdivisions + 1));
  26488. }
  26489. }
  26490. // Result
  26491. var vertexData = new VertexData();
  26492. vertexData.indices = indices;
  26493. vertexData.positions = positions;
  26494. vertexData.normals = normals;
  26495. vertexData.uvs = uvs;
  26496. return vertexData;
  26497. };
  26498. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  26499. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  26500. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  26501. var indices = [];
  26502. var positions = [];
  26503. var normals = [];
  26504. var uvs = [];
  26505. var row, col, tileRow, tileCol;
  26506. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26507. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26508. precision.w = (precision.w < 1) ? 1 : precision.w;
  26509. precision.h = (precision.h < 1) ? 1 : precision.h;
  26510. var tileSize = {
  26511. 'w': (xmax - xmin) / subdivisions.w,
  26512. 'h': (zmax - zmin) / subdivisions.h
  26513. };
  26514. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26515. // Indices
  26516. var base = positions.length / 3;
  26517. var rowLength = precision.w + 1;
  26518. for (row = 0; row < precision.h; row++) {
  26519. for (col = 0; col < precision.w; col++) {
  26520. var square = [
  26521. base + col + row * rowLength,
  26522. base + (col + 1) + row * rowLength,
  26523. base + (col + 1) + (row + 1) * rowLength,
  26524. base + col + (row + 1) * rowLength
  26525. ];
  26526. indices.push(square[1]);
  26527. indices.push(square[2]);
  26528. indices.push(square[3]);
  26529. indices.push(square[0]);
  26530. indices.push(square[1]);
  26531. indices.push(square[3]);
  26532. }
  26533. }
  26534. // Position, normals and uvs
  26535. var position = BABYLON.Vector3.Zero();
  26536. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26537. for (row = 0; row <= precision.h; row++) {
  26538. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26539. for (col = 0; col <= precision.w; col++) {
  26540. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26541. position.y = 0;
  26542. positions.push(position.x, position.y, position.z);
  26543. normals.push(normal.x, normal.y, normal.z);
  26544. uvs.push(col / precision.w, row / precision.h);
  26545. }
  26546. }
  26547. }
  26548. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26549. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26550. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26551. }
  26552. }
  26553. // Result
  26554. var vertexData = new VertexData();
  26555. vertexData.indices = indices;
  26556. vertexData.positions = positions;
  26557. vertexData.normals = normals;
  26558. vertexData.uvs = uvs;
  26559. return vertexData;
  26560. };
  26561. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  26562. var indices = [];
  26563. var positions = [];
  26564. var normals = [];
  26565. var uvs = [];
  26566. var row, col;
  26567. // Vertices
  26568. for (row = 0; row <= subdivisions; row++) {
  26569. for (col = 0; col <= subdivisions; col++) {
  26570. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26571. // Compute height
  26572. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  26573. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  26574. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  26575. var r = buffer[pos] / 255.0;
  26576. var g = buffer[pos + 1] / 255.0;
  26577. var b = buffer[pos + 2] / 255.0;
  26578. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26579. position.y = minHeight + (maxHeight - minHeight) * gradient;
  26580. // Add vertex
  26581. positions.push(position.x, position.y, position.z);
  26582. normals.push(0, 0, 0);
  26583. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26584. }
  26585. }
  26586. // Indices
  26587. for (row = 0; row < subdivisions; row++) {
  26588. for (col = 0; col < subdivisions; col++) {
  26589. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26590. indices.push(col + 1 + row * (subdivisions + 1));
  26591. indices.push(col + row * (subdivisions + 1));
  26592. indices.push(col + (row + 1) * (subdivisions + 1));
  26593. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26594. indices.push(col + row * (subdivisions + 1));
  26595. }
  26596. }
  26597. // Normals
  26598. VertexData.ComputeNormals(positions, indices, normals);
  26599. // Result
  26600. var vertexData = new VertexData();
  26601. vertexData.indices = indices;
  26602. vertexData.positions = positions;
  26603. vertexData.normals = normals;
  26604. vertexData.uvs = uvs;
  26605. return vertexData;
  26606. };
  26607. VertexData.CreatePlane = function (size, sideOrientation) {
  26608. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26609. var indices = [];
  26610. var positions = [];
  26611. var normals = [];
  26612. var uvs = [];
  26613. size = size || 1;
  26614. // Vertices
  26615. var halfSize = size / 2.0;
  26616. positions.push(-halfSize, -halfSize, 0);
  26617. normals.push(0, 0, -1.0);
  26618. uvs.push(0.0, 0.0);
  26619. positions.push(halfSize, -halfSize, 0);
  26620. normals.push(0, 0, -1.0);
  26621. uvs.push(1.0, 0.0);
  26622. positions.push(halfSize, halfSize, 0);
  26623. normals.push(0, 0, -1.0);
  26624. uvs.push(1.0, 1.0);
  26625. positions.push(-halfSize, halfSize, 0);
  26626. normals.push(0, 0, -1.0);
  26627. uvs.push(0.0, 1.0);
  26628. // Indices
  26629. indices.push(0);
  26630. indices.push(1);
  26631. indices.push(2);
  26632. indices.push(0);
  26633. indices.push(2);
  26634. indices.push(3);
  26635. // Sides
  26636. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26637. // Result
  26638. var vertexData = new VertexData();
  26639. vertexData.indices = indices;
  26640. vertexData.positions = positions;
  26641. vertexData.normals = normals;
  26642. vertexData.uvs = uvs;
  26643. return vertexData;
  26644. };
  26645. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  26646. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26647. var positions = [];
  26648. var indices = [];
  26649. var normals = [];
  26650. var uvs = [];
  26651. // positions and uvs
  26652. positions.push(0, 0, 0); // disc center first
  26653. uvs.push(0.5, 0.5);
  26654. var step = Math.PI * 2 / tessellation;
  26655. for (var a = 0; a < Math.PI * 2; a += step) {
  26656. var x = Math.cos(a);
  26657. var y = Math.sin(a);
  26658. var u = (x + 1) / 2;
  26659. var v = (1 - y) / 2;
  26660. positions.push(radius * x, radius * y, 0);
  26661. uvs.push(u, v);
  26662. }
  26663. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26664. uvs.push(uvs[2], uvs[3]);
  26665. //indices
  26666. var vertexNb = positions.length / 3;
  26667. for (var i = 1; i < vertexNb - 1; i++) {
  26668. indices.push(i + 1, 0, i);
  26669. }
  26670. // result
  26671. VertexData.ComputeNormals(positions, indices, normals);
  26672. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26673. var vertexData = new VertexData();
  26674. vertexData.indices = indices;
  26675. vertexData.positions = positions;
  26676. vertexData.normals = normals;
  26677. vertexData.uvs = uvs;
  26678. return vertexData;
  26679. };
  26680. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26681. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  26682. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26683. var indices = [];
  26684. var positions = [];
  26685. var normals = [];
  26686. var uvs = [];
  26687. radius = radius || 2;
  26688. tube = tube || 0.5;
  26689. radialSegments = radialSegments || 32;
  26690. tubularSegments = tubularSegments || 32;
  26691. p = p || 2;
  26692. q = q || 3;
  26693. // Helper
  26694. var getPos = function (angle) {
  26695. var cu = Math.cos(angle);
  26696. var su = Math.sin(angle);
  26697. var quOverP = q / p * angle;
  26698. var cs = Math.cos(quOverP);
  26699. var tx = radius * (2 + cs) * 0.5 * cu;
  26700. var ty = radius * (2 + cs) * su * 0.5;
  26701. var tz = radius * Math.sin(quOverP) * 0.5;
  26702. return new BABYLON.Vector3(tx, ty, tz);
  26703. };
  26704. // Vertices
  26705. for (var i = 0; i <= radialSegments; i++) {
  26706. var modI = i % radialSegments;
  26707. var u = modI / radialSegments * 2 * p * Math.PI;
  26708. var p1 = getPos(u);
  26709. var p2 = getPos(u + 0.01);
  26710. var tang = p2.subtract(p1);
  26711. var n = p2.add(p1);
  26712. var bitan = BABYLON.Vector3.Cross(tang, n);
  26713. n = BABYLON.Vector3.Cross(bitan, tang);
  26714. bitan.normalize();
  26715. n.normalize();
  26716. for (var j = 0; j < tubularSegments; j++) {
  26717. var modJ = j % tubularSegments;
  26718. var v = modJ / tubularSegments * 2 * Math.PI;
  26719. var cx = -tube * Math.cos(v);
  26720. var cy = tube * Math.sin(v);
  26721. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26722. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26723. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26724. uvs.push(i / radialSegments);
  26725. uvs.push(j / tubularSegments);
  26726. }
  26727. }
  26728. for (i = 0; i < radialSegments; i++) {
  26729. for (j = 0; j < tubularSegments; j++) {
  26730. var jNext = (j + 1) % tubularSegments;
  26731. var a = i * tubularSegments + j;
  26732. var b = (i + 1) * tubularSegments + j;
  26733. var c = (i + 1) * tubularSegments + jNext;
  26734. var d = i * tubularSegments + jNext;
  26735. indices.push(d);
  26736. indices.push(b);
  26737. indices.push(a);
  26738. indices.push(d);
  26739. indices.push(c);
  26740. indices.push(b);
  26741. }
  26742. }
  26743. // Normals
  26744. VertexData.ComputeNormals(positions, indices, normals);
  26745. // Sides
  26746. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26747. // Result
  26748. var vertexData = new VertexData();
  26749. vertexData.indices = indices;
  26750. vertexData.positions = positions;
  26751. vertexData.normals = normals;
  26752. vertexData.uvs = uvs;
  26753. return vertexData;
  26754. };
  26755. // Tools
  26756. /**
  26757. * @param {any} - positions (number[] or Float32Array)
  26758. * @param {any} - indices (number[] or Uint16Array)
  26759. * @param {any} - normals (number[] or Float32Array)
  26760. */
  26761. VertexData.ComputeNormals = function (positions, indices, normals) {
  26762. var index = 0;
  26763. // temp Vector3
  26764. var p1 = BABYLON.Vector3.Zero();
  26765. var p2 = BABYLON.Vector3.Zero();
  26766. var p3 = BABYLON.Vector3.Zero();
  26767. var p1p2 = BABYLON.Vector3.Zero();
  26768. var p3p2 = BABYLON.Vector3.Zero();
  26769. var faceNormal = BABYLON.Vector3.Zero();
  26770. var vertexNormali1 = BABYLON.Vector3.Zero();
  26771. var vertexNormali2 = BABYLON.Vector3.Zero();
  26772. var vertexNormali3 = BABYLON.Vector3.Zero();
  26773. // indice triplet = 1 face
  26774. var nbFaces = indices.length / 3;
  26775. for (index = 0; index < nbFaces; index++) {
  26776. var i1 = indices[index * 3];
  26777. var i2 = indices[index * 3 + 1];
  26778. var i3 = indices[index * 3 + 2];
  26779. // setting the temp V3
  26780. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  26781. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  26782. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  26783. p1.subtractToRef(p2, p1p2);
  26784. p3.subtractToRef(p2, p3p2);
  26785. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  26786. faceNormal.normalize();
  26787. // All intermediate results are stored in the normals array :
  26788. // get the normals at i1, i2 and i3 indexes
  26789. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  26790. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  26791. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  26792. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  26793. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  26794. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  26795. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  26796. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  26797. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  26798. // make intermediate vectors3 from normals values
  26799. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  26800. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  26801. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  26802. // add the current face normals to these intermediate vectors3
  26803. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  26804. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  26805. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  26806. // store back intermediate vectors3 into the normals array
  26807. normals[i1 * 3] = vertexNormali1.x;
  26808. normals[i1 * 3 + 1] = vertexNormali1.y;
  26809. normals[i1 * 3 + 2] = vertexNormali1.z;
  26810. normals[i2 * 3] = vertexNormali2.x;
  26811. normals[i2 * 3 + 1] = vertexNormali2.y;
  26812. normals[i2 * 3 + 2] = vertexNormali2.z;
  26813. normals[i3 * 3] = vertexNormali3.x;
  26814. normals[i3 * 3 + 1] = vertexNormali3.y;
  26815. normals[i3 * 3 + 2] = vertexNormali3.z;
  26816. }
  26817. // last normalization
  26818. for (index = 0; index < normals.length / 3; index++) {
  26819. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  26820. vertexNormali1.normalize();
  26821. normals[index * 3] = vertexNormali1.x;
  26822. normals[index * 3 + 1] = vertexNormali1.y;
  26823. normals[index * 3 + 2] = vertexNormali1.z;
  26824. }
  26825. };
  26826. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26827. var li = indices.length;
  26828. var ln = normals.length;
  26829. var i;
  26830. var n;
  26831. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26832. switch (sideOrientation) {
  26833. case BABYLON.Mesh.FRONTSIDE:
  26834. // nothing changed
  26835. break;
  26836. case BABYLON.Mesh.BACKSIDE:
  26837. var tmp;
  26838. // indices
  26839. for (i = 0; i < li; i += 3) {
  26840. tmp = indices[i];
  26841. indices[i] = indices[i + 2];
  26842. indices[i + 2] = tmp;
  26843. }
  26844. // normals
  26845. for (n = 0; n < ln; n++) {
  26846. normals[n] = -normals[n];
  26847. }
  26848. break;
  26849. case BABYLON.Mesh.DOUBLESIDE:
  26850. // positions
  26851. var lp = positions.length;
  26852. var l = lp / 3;
  26853. for (var p = 0; p < lp; p++) {
  26854. positions[lp + p] = positions[p];
  26855. }
  26856. // indices
  26857. for (i = 0; i < li; i += 3) {
  26858. indices[i + li] = indices[i + 2] + l;
  26859. indices[i + 1 + li] = indices[i + 1] + l;
  26860. indices[i + 2 + li] = indices[i] + l;
  26861. }
  26862. // normals
  26863. for (n = 0; n < ln; n++) {
  26864. normals[ln + n] = -normals[n];
  26865. }
  26866. // uvs
  26867. var lu = uvs.length;
  26868. for (var u = 0; u < lu; u++) {
  26869. uvs[u + lu] = uvs[u];
  26870. }
  26871. break;
  26872. }
  26873. };
  26874. return VertexData;
  26875. })();
  26876. BABYLON.VertexData = VertexData;
  26877. })(BABYLON || (BABYLON = {}));
  26878. var BABYLON;
  26879. (function (BABYLON) {
  26880. var AnaglyphPostProcess = (function (_super) {
  26881. __extends(AnaglyphPostProcess, _super);
  26882. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26883. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  26884. }
  26885. return AnaglyphPostProcess;
  26886. })(BABYLON.PostProcess);
  26887. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  26888. })(BABYLON || (BABYLON = {}));
  26889. var BABYLON;
  26890. (function (BABYLON) {
  26891. var Tags = (function () {
  26892. function Tags() {
  26893. }
  26894. Tags.EnableFor = function (obj) {
  26895. obj._tags = obj._tags || {};
  26896. obj.hasTags = function () {
  26897. return Tags.HasTags(obj);
  26898. };
  26899. obj.addTags = function (tagsString) {
  26900. return Tags.AddTagsTo(obj, tagsString);
  26901. };
  26902. obj.removeTags = function (tagsString) {
  26903. return Tags.RemoveTagsFrom(obj, tagsString);
  26904. };
  26905. obj.matchesTagsQuery = function (tagsQuery) {
  26906. return Tags.MatchesQuery(obj, tagsQuery);
  26907. };
  26908. };
  26909. Tags.DisableFor = function (obj) {
  26910. delete obj._tags;
  26911. delete obj.hasTags;
  26912. delete obj.addTags;
  26913. delete obj.removeTags;
  26914. delete obj.matchesTagsQuery;
  26915. };
  26916. Tags.HasTags = function (obj) {
  26917. if (!obj._tags) {
  26918. return false;
  26919. }
  26920. return !BABYLON.Tools.IsEmpty(obj._tags);
  26921. };
  26922. Tags.GetTags = function (obj) {
  26923. if (!obj._tags) {
  26924. return null;
  26925. }
  26926. return obj._tags;
  26927. };
  26928. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26929. // a tag cannot start with '||', '&&', and '!'
  26930. // it cannot contain whitespaces
  26931. Tags.AddTagsTo = function (obj, tagsString) {
  26932. if (!tagsString) {
  26933. return;
  26934. }
  26935. var tags = tagsString.split(" ");
  26936. for (var t in tags) {
  26937. Tags._AddTagTo(obj, tags[t]);
  26938. }
  26939. };
  26940. Tags._AddTagTo = function (obj, tag) {
  26941. tag = tag.trim();
  26942. if (tag === "" || tag === "true" || tag === "false") {
  26943. return;
  26944. }
  26945. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26946. return;
  26947. }
  26948. Tags.EnableFor(obj);
  26949. obj._tags[tag] = true;
  26950. };
  26951. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26952. if (!Tags.HasTags(obj)) {
  26953. return;
  26954. }
  26955. var tags = tagsString.split(" ");
  26956. for (var t in tags) {
  26957. Tags._RemoveTagFrom(obj, tags[t]);
  26958. }
  26959. };
  26960. Tags._RemoveTagFrom = function (obj, tag) {
  26961. delete obj._tags[tag];
  26962. };
  26963. Tags.MatchesQuery = function (obj, tagsQuery) {
  26964. if (tagsQuery === undefined) {
  26965. return true;
  26966. }
  26967. if (tagsQuery === "") {
  26968. return Tags.HasTags(obj);
  26969. }
  26970. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  26971. };
  26972. return Tags;
  26973. })();
  26974. BABYLON.Tags = Tags;
  26975. })(BABYLON || (BABYLON = {}));
  26976. var BABYLON;
  26977. (function (BABYLON) {
  26978. var Internals;
  26979. (function (Internals) {
  26980. var AndOrNotEvaluator = (function () {
  26981. function AndOrNotEvaluator() {
  26982. }
  26983. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  26984. if (!query.match(/\([^\(\)]*\)/g)) {
  26985. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  26986. }
  26987. else {
  26988. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  26989. // remove parenthesis
  26990. r = r.slice(1, r.length - 1);
  26991. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  26992. });
  26993. }
  26994. if (query === "true") {
  26995. return true;
  26996. }
  26997. if (query === "false") {
  26998. return false;
  26999. }
  27000. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27001. };
  27002. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27003. evaluateCallback = evaluateCallback || (function (r) {
  27004. return r === "true" ? true : false;
  27005. });
  27006. var result;
  27007. var or = parenthesisContent.split("||");
  27008. for (var i in or) {
  27009. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27010. var and = ori.split("&&");
  27011. if (and.length > 1) {
  27012. for (var j = 0; j < and.length; ++j) {
  27013. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27014. if (andj !== "true" && andj !== "false") {
  27015. if (andj[0] === "!") {
  27016. result = !evaluateCallback(andj.substring(1));
  27017. }
  27018. else {
  27019. result = evaluateCallback(andj);
  27020. }
  27021. }
  27022. else {
  27023. result = andj === "true" ? true : false;
  27024. }
  27025. if (!result) {
  27026. ori = "false";
  27027. break;
  27028. }
  27029. }
  27030. }
  27031. if (result || ori === "true") {
  27032. result = true;
  27033. break;
  27034. }
  27035. // result equals false (or undefined)
  27036. if (ori !== "true" && ori !== "false") {
  27037. if (ori[0] === "!") {
  27038. result = !evaluateCallback(ori.substring(1));
  27039. }
  27040. else {
  27041. result = evaluateCallback(ori);
  27042. }
  27043. }
  27044. else {
  27045. result = ori === "true" ? true : false;
  27046. }
  27047. }
  27048. // the whole parenthesis scope is replaced by 'true' or 'false'
  27049. return result ? "true" : "false";
  27050. };
  27051. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27052. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27053. // remove whitespaces
  27054. r = r.replace(/[\s]/g, function () { return ""; });
  27055. return r.length % 2 ? "!" : "";
  27056. });
  27057. booleanString = booleanString.trim();
  27058. if (booleanString === "!true") {
  27059. booleanString = "false";
  27060. }
  27061. else if (booleanString === "!false") {
  27062. booleanString = "true";
  27063. }
  27064. return booleanString;
  27065. };
  27066. return AndOrNotEvaluator;
  27067. })();
  27068. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27069. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27070. })(BABYLON || (BABYLON = {}));
  27071. var BABYLON;
  27072. (function (BABYLON) {
  27073. var PostProcessRenderPass = (function () {
  27074. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27075. this._enabled = true;
  27076. this._refCount = 0;
  27077. this._name = name;
  27078. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27079. this.setRenderList(renderList);
  27080. this._renderTexture.onBeforeRender = beforeRender;
  27081. this._renderTexture.onAfterRender = afterRender;
  27082. this._scene = scene;
  27083. this._renderList = renderList;
  27084. }
  27085. // private
  27086. PostProcessRenderPass.prototype._incRefCount = function () {
  27087. if (this._refCount === 0) {
  27088. this._scene.customRenderTargets.push(this._renderTexture);
  27089. }
  27090. return ++this._refCount;
  27091. };
  27092. PostProcessRenderPass.prototype._decRefCount = function () {
  27093. this._refCount--;
  27094. if (this._refCount <= 0) {
  27095. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27096. }
  27097. return this._refCount;
  27098. };
  27099. PostProcessRenderPass.prototype._update = function () {
  27100. this.setRenderList(this._renderList);
  27101. };
  27102. // public
  27103. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27104. this._renderTexture.renderList = renderList;
  27105. };
  27106. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27107. return this._renderTexture;
  27108. };
  27109. return PostProcessRenderPass;
  27110. })();
  27111. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27112. })(BABYLON || (BABYLON = {}));
  27113. var BABYLON;
  27114. (function (BABYLON) {
  27115. var PostProcessRenderEffect = (function () {
  27116. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27117. this._engine = engine;
  27118. this._name = name;
  27119. this._singleInstance = singleInstance || true;
  27120. this._getPostProcess = getPostProcess;
  27121. this._cameras = [];
  27122. this._indicesForCamera = [];
  27123. this._postProcesses = {};
  27124. this._renderPasses = {};
  27125. this._renderEffectAsPasses = {};
  27126. }
  27127. PostProcessRenderEffect.prototype._update = function () {
  27128. for (var renderPassName in this._renderPasses) {
  27129. this._renderPasses[renderPassName]._update();
  27130. }
  27131. };
  27132. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27133. this._renderPasses[renderPass._name] = renderPass;
  27134. this._linkParameters();
  27135. };
  27136. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27137. delete this._renderPasses[renderPass._name];
  27138. this._linkParameters();
  27139. };
  27140. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27141. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27142. this._linkParameters();
  27143. };
  27144. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27145. for (var renderPassName in this._renderPasses) {
  27146. if (renderPassName === passName) {
  27147. return this._renderPasses[passName];
  27148. }
  27149. }
  27150. };
  27151. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27152. this._renderPasses = {};
  27153. this._linkParameters();
  27154. };
  27155. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27156. var cameraKey;
  27157. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27158. for (var i = 0; i < _cam.length; i++) {
  27159. var camera = _cam[i];
  27160. var cameraName = camera.name;
  27161. if (this._singleInstance) {
  27162. cameraKey = 0;
  27163. }
  27164. else {
  27165. cameraKey = cameraName;
  27166. }
  27167. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27168. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27169. if (!this._indicesForCamera[cameraName]) {
  27170. this._indicesForCamera[cameraName] = [];
  27171. }
  27172. this._indicesForCamera[cameraName].push(index);
  27173. if (this._cameras.indexOf(camera) === -1) {
  27174. this._cameras[cameraName] = camera;
  27175. }
  27176. for (var passName in this._renderPasses) {
  27177. this._renderPasses[passName]._incRefCount();
  27178. }
  27179. }
  27180. this._linkParameters();
  27181. };
  27182. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27183. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27184. for (var i = 0; i < _cam.length; i++) {
  27185. var camera = _cam[i];
  27186. var cameraName = camera.name;
  27187. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27188. var index = this._cameras.indexOf(cameraName);
  27189. this._indicesForCamera.splice(index, 1);
  27190. this._cameras.splice(index, 1);
  27191. for (var passName in this._renderPasses) {
  27192. this._renderPasses[passName]._decRefCount();
  27193. }
  27194. }
  27195. };
  27196. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27197. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27198. for (var i = 0; i < _cam.length; i++) {
  27199. var camera = _cam[i];
  27200. var cameraName = camera.name;
  27201. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27202. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27203. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27204. }
  27205. }
  27206. for (var passName in this._renderPasses) {
  27207. this._renderPasses[passName]._incRefCount();
  27208. }
  27209. }
  27210. };
  27211. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27212. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27213. for (var i = 0; i < _cam.length; i++) {
  27214. var camera = _cam[i];
  27215. var cameraName = camera.Name;
  27216. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27217. for (var passName in this._renderPasses) {
  27218. this._renderPasses[passName]._decRefCount();
  27219. }
  27220. }
  27221. };
  27222. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27223. if (this._singleInstance) {
  27224. return this._postProcesses[0];
  27225. }
  27226. else {
  27227. return this._postProcesses[camera.name];
  27228. }
  27229. };
  27230. PostProcessRenderEffect.prototype._linkParameters = function () {
  27231. var _this = this;
  27232. for (var index in this._postProcesses) {
  27233. if (this.applyParameters) {
  27234. this.applyParameters(this._postProcesses[index]);
  27235. }
  27236. this._postProcesses[index].onBeforeRender = function (effect) {
  27237. _this._linkTextures(effect);
  27238. };
  27239. }
  27240. };
  27241. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27242. for (var renderPassName in this._renderPasses) {
  27243. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27244. }
  27245. for (var renderEffectName in this._renderEffectAsPasses) {
  27246. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27247. }
  27248. };
  27249. return PostProcessRenderEffect;
  27250. })();
  27251. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27252. })(BABYLON || (BABYLON = {}));
  27253. var BABYLON;
  27254. (function (BABYLON) {
  27255. var PostProcessRenderPipeline = (function () {
  27256. function PostProcessRenderPipeline(engine, name) {
  27257. this._engine = engine;
  27258. this._name = name;
  27259. this._renderEffects = {};
  27260. this._renderEffectsForIsolatedPass = {};
  27261. this._cameras = [];
  27262. }
  27263. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  27264. this._renderEffects[renderEffect._name] = renderEffect;
  27265. };
  27266. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  27267. var renderEffects = this._renderEffects[renderEffectName];
  27268. if (!renderEffects) {
  27269. return;
  27270. }
  27271. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27272. };
  27273. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  27274. var renderEffects = this._renderEffects[renderEffectName];
  27275. if (!renderEffects) {
  27276. return;
  27277. }
  27278. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27279. };
  27280. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  27281. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27282. var indicesToDelete = [];
  27283. for (var i = 0; i < _cam.length; i++) {
  27284. var camera = _cam[i];
  27285. var cameraName = camera.name;
  27286. if (this._cameras.indexOf(camera) === -1) {
  27287. this._cameras[cameraName] = camera;
  27288. }
  27289. else if (unique) {
  27290. indicesToDelete.push(i);
  27291. }
  27292. }
  27293. for (var i = 0; i < indicesToDelete.length; i++) {
  27294. cameras.splice(indicesToDelete[i], 1);
  27295. }
  27296. for (var renderEffectName in this._renderEffects) {
  27297. this._renderEffects[renderEffectName]._attachCameras(_cam);
  27298. }
  27299. };
  27300. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  27301. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27302. for (var renderEffectName in this._renderEffects) {
  27303. this._renderEffects[renderEffectName]._detachCameras(_cam);
  27304. }
  27305. for (var i = 0; i < _cam.length; i++) {
  27306. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  27307. }
  27308. };
  27309. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  27310. var _this = this;
  27311. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27312. var pass = null;
  27313. for (var renderEffectName in this._renderEffects) {
  27314. pass = this._renderEffects[renderEffectName].getPass(passName);
  27315. if (pass != null) {
  27316. break;
  27317. }
  27318. }
  27319. if (pass === null) {
  27320. return;
  27321. }
  27322. for (var renderEffectName in this._renderEffects) {
  27323. this._renderEffects[renderEffectName]._disable(_cam);
  27324. }
  27325. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  27326. for (var i = 0; i < _cam.length; i++) {
  27327. var camera = _cam[i];
  27328. var cameraName = camera.name;
  27329. 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); });
  27330. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  27331. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  27332. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  27333. }
  27334. };
  27335. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  27336. var _this = this;
  27337. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27338. for (var i = 0; i < _cam.length; i++) {
  27339. var camera = _cam[i];
  27340. var cameraName = camera.name;
  27341. 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); });
  27342. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  27343. }
  27344. for (var renderEffectName in this._renderEffects) {
  27345. this._renderEffects[renderEffectName]._enable(_cam);
  27346. }
  27347. };
  27348. PostProcessRenderPipeline.prototype._update = function () {
  27349. for (var renderEffectName in this._renderEffects) {
  27350. this._renderEffects[renderEffectName]._update();
  27351. }
  27352. for (var i = 0; i < this._cameras.length; i++) {
  27353. var cameraName = this._cameras[i].name;
  27354. if (this._renderEffectsForIsolatedPass[cameraName]) {
  27355. this._renderEffectsForIsolatedPass[cameraName]._update();
  27356. }
  27357. }
  27358. };
  27359. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  27360. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  27361. return PostProcessRenderPipeline;
  27362. })();
  27363. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  27364. })(BABYLON || (BABYLON = {}));
  27365. var BABYLON;
  27366. (function (BABYLON) {
  27367. var PostProcessRenderPipelineManager = (function () {
  27368. function PostProcessRenderPipelineManager() {
  27369. this._renderPipelines = {};
  27370. }
  27371. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  27372. this._renderPipelines[renderPipeline._name] = renderPipeline;
  27373. };
  27374. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  27375. var renderPipeline = this._renderPipelines[renderPipelineName];
  27376. if (!renderPipeline) {
  27377. return;
  27378. }
  27379. renderPipeline._attachCameras(cameras, unique);
  27380. };
  27381. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  27382. var renderPipeline = this._renderPipelines[renderPipelineName];
  27383. if (!renderPipeline) {
  27384. return;
  27385. }
  27386. renderPipeline._detachCameras(cameras);
  27387. };
  27388. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27389. var renderPipeline = this._renderPipelines[renderPipelineName];
  27390. if (!renderPipeline) {
  27391. return;
  27392. }
  27393. renderPipeline._enableEffect(renderEffectName, cameras);
  27394. };
  27395. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27396. var renderPipeline = this._renderPipelines[renderPipelineName];
  27397. if (!renderPipeline) {
  27398. return;
  27399. }
  27400. renderPipeline._disableEffect(renderEffectName, cameras);
  27401. };
  27402. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  27403. var renderPipeline = this._renderPipelines[renderPipelineName];
  27404. if (!renderPipeline) {
  27405. return;
  27406. }
  27407. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  27408. };
  27409. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  27410. var renderPipeline = this._renderPipelines[renderPipelineName];
  27411. if (!renderPipeline) {
  27412. return;
  27413. }
  27414. renderPipeline._disableDisplayOnlyPass(cameras);
  27415. };
  27416. PostProcessRenderPipelineManager.prototype.update = function () {
  27417. for (var renderPipelineName in this._renderPipelines) {
  27418. this._renderPipelines[renderPipelineName]._update();
  27419. }
  27420. };
  27421. return PostProcessRenderPipelineManager;
  27422. })();
  27423. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  27424. })(BABYLON || (BABYLON = {}));
  27425. var BABYLON;
  27426. (function (BABYLON) {
  27427. var DisplayPassPostProcess = (function (_super) {
  27428. __extends(DisplayPassPostProcess, _super);
  27429. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27430. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  27431. }
  27432. return DisplayPassPostProcess;
  27433. })(BABYLON.PostProcess);
  27434. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  27435. })(BABYLON || (BABYLON = {}));
  27436. var BABYLON;
  27437. (function (BABYLON) {
  27438. var BoundingBoxRenderer = (function () {
  27439. function BoundingBoxRenderer(scene) {
  27440. this.frontColor = new BABYLON.Color3(1, 1, 1);
  27441. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  27442. this.showBackLines = true;
  27443. this.renderList = new BABYLON.SmartArray(32);
  27444. this._scene = scene;
  27445. }
  27446. BoundingBoxRenderer.prototype._prepareRessources = function () {
  27447. if (this._colorShader) {
  27448. return;
  27449. }
  27450. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  27451. attributes: ["position"],
  27452. uniforms: ["worldViewProjection", "color"]
  27453. });
  27454. var engine = this._scene.getEngine();
  27455. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  27456. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  27457. 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]);
  27458. };
  27459. BoundingBoxRenderer.prototype.reset = function () {
  27460. this.renderList.reset();
  27461. };
  27462. BoundingBoxRenderer.prototype.render = function () {
  27463. if (this.renderList.length === 0) {
  27464. return;
  27465. }
  27466. this._prepareRessources();
  27467. if (!this._colorShader.isReady()) {
  27468. return;
  27469. }
  27470. var engine = this._scene.getEngine();
  27471. engine.setDepthWrite(false);
  27472. this._colorShader._preBind();
  27473. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27474. var boundingBox = this.renderList.data[boundingBoxIndex];
  27475. var min = boundingBox.minimum;
  27476. var max = boundingBox.maximum;
  27477. var diff = max.subtract(min);
  27478. var median = min.add(diff.scale(0.5));
  27479. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27480. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27481. .multiply(boundingBox.getWorldMatrix());
  27482. // VBOs
  27483. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27484. if (this.showBackLines) {
  27485. // Back
  27486. engine.setDepthFunctionToGreaterOrEqual();
  27487. this._scene.resetCachedMaterial();
  27488. this._colorShader.setColor4("color", this.backColor.toColor4());
  27489. this._colorShader.bind(worldMatrix);
  27490. // Draw order
  27491. engine.draw(false, 0, 24);
  27492. }
  27493. // Front
  27494. engine.setDepthFunctionToLess();
  27495. this._scene.resetCachedMaterial();
  27496. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27497. this._colorShader.bind(worldMatrix);
  27498. // Draw order
  27499. engine.draw(false, 0, 24);
  27500. }
  27501. this._colorShader.unbind();
  27502. engine.setDepthFunctionToLessOrEqual();
  27503. engine.setDepthWrite(true);
  27504. };
  27505. BoundingBoxRenderer.prototype.dispose = function () {
  27506. if (!this._colorShader) {
  27507. return;
  27508. }
  27509. this._colorShader.dispose();
  27510. this._vb.dispose();
  27511. this._scene.getEngine()._releaseBuffer(this._ib);
  27512. };
  27513. return BoundingBoxRenderer;
  27514. })();
  27515. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27516. })(BABYLON || (BABYLON = {}));
  27517. var BABYLON;
  27518. (function (BABYLON) {
  27519. var Condition = (function () {
  27520. function Condition(actionManager) {
  27521. this._actionManager = actionManager;
  27522. }
  27523. Condition.prototype.isValid = function () {
  27524. return true;
  27525. };
  27526. Condition.prototype._getProperty = function (propertyPath) {
  27527. return this._actionManager._getProperty(propertyPath);
  27528. };
  27529. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27530. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27531. };
  27532. return Condition;
  27533. })();
  27534. BABYLON.Condition = Condition;
  27535. var ValueCondition = (function (_super) {
  27536. __extends(ValueCondition, _super);
  27537. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27538. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27539. _super.call(this, actionManager);
  27540. this.propertyPath = propertyPath;
  27541. this.value = value;
  27542. this.operator = operator;
  27543. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27544. this._property = this._getProperty(this.propertyPath);
  27545. }
  27546. Object.defineProperty(ValueCondition, "IsEqual", {
  27547. get: function () {
  27548. return ValueCondition._IsEqual;
  27549. },
  27550. enumerable: true,
  27551. configurable: true
  27552. });
  27553. Object.defineProperty(ValueCondition, "IsDifferent", {
  27554. get: function () {
  27555. return ValueCondition._IsDifferent;
  27556. },
  27557. enumerable: true,
  27558. configurable: true
  27559. });
  27560. Object.defineProperty(ValueCondition, "IsGreater", {
  27561. get: function () {
  27562. return ValueCondition._IsGreater;
  27563. },
  27564. enumerable: true,
  27565. configurable: true
  27566. });
  27567. Object.defineProperty(ValueCondition, "IsLesser", {
  27568. get: function () {
  27569. return ValueCondition._IsLesser;
  27570. },
  27571. enumerable: true,
  27572. configurable: true
  27573. });
  27574. // Methods
  27575. ValueCondition.prototype.isValid = function () {
  27576. switch (this.operator) {
  27577. case ValueCondition.IsGreater:
  27578. return this._target[this._property] > this.value;
  27579. case ValueCondition.IsLesser:
  27580. return this._target[this._property] < this.value;
  27581. case ValueCondition.IsEqual:
  27582. case ValueCondition.IsDifferent:
  27583. var check;
  27584. if (this.value.equals) {
  27585. check = this.value.equals(this._target[this._property]);
  27586. }
  27587. else {
  27588. check = this.value === this._target[this._property];
  27589. }
  27590. return this.operator === ValueCondition.IsEqual ? check : !check;
  27591. }
  27592. return false;
  27593. };
  27594. // Statics
  27595. ValueCondition._IsEqual = 0;
  27596. ValueCondition._IsDifferent = 1;
  27597. ValueCondition._IsGreater = 2;
  27598. ValueCondition._IsLesser = 3;
  27599. return ValueCondition;
  27600. })(Condition);
  27601. BABYLON.ValueCondition = ValueCondition;
  27602. var PredicateCondition = (function (_super) {
  27603. __extends(PredicateCondition, _super);
  27604. function PredicateCondition(actionManager, predicate) {
  27605. _super.call(this, actionManager);
  27606. this.predicate = predicate;
  27607. }
  27608. PredicateCondition.prototype.isValid = function () {
  27609. return this.predicate();
  27610. };
  27611. return PredicateCondition;
  27612. })(Condition);
  27613. BABYLON.PredicateCondition = PredicateCondition;
  27614. var StateCondition = (function (_super) {
  27615. __extends(StateCondition, _super);
  27616. function StateCondition(actionManager, target, value) {
  27617. _super.call(this, actionManager);
  27618. this.value = value;
  27619. this._target = target;
  27620. }
  27621. // Methods
  27622. StateCondition.prototype.isValid = function () {
  27623. return this._target.state === this.value;
  27624. };
  27625. return StateCondition;
  27626. })(Condition);
  27627. BABYLON.StateCondition = StateCondition;
  27628. })(BABYLON || (BABYLON = {}));
  27629. var BABYLON;
  27630. (function (BABYLON) {
  27631. var Action = (function () {
  27632. function Action(triggerOptions, condition) {
  27633. this.triggerOptions = triggerOptions;
  27634. if (triggerOptions.parameter) {
  27635. this.trigger = triggerOptions.trigger;
  27636. this._triggerParameter = triggerOptions.parameter;
  27637. }
  27638. else {
  27639. this.trigger = triggerOptions;
  27640. }
  27641. this._nextActiveAction = this;
  27642. this._condition = condition;
  27643. }
  27644. // Methods
  27645. Action.prototype._prepare = function () {
  27646. };
  27647. Action.prototype.getTriggerParameter = function () {
  27648. return this._triggerParameter;
  27649. };
  27650. Action.prototype._executeCurrent = function (evt) {
  27651. if (this._nextActiveAction._condition) {
  27652. var condition = this._nextActiveAction._condition;
  27653. var currentRenderId = this._actionManager.getScene().getRenderId();
  27654. // We cache the current evaluation for the current frame
  27655. if (condition._evaluationId === currentRenderId) {
  27656. if (!condition._currentResult) {
  27657. return;
  27658. }
  27659. }
  27660. else {
  27661. condition._evaluationId = currentRenderId;
  27662. if (!condition.isValid()) {
  27663. condition._currentResult = false;
  27664. return;
  27665. }
  27666. condition._currentResult = true;
  27667. }
  27668. }
  27669. this._nextActiveAction.execute(evt);
  27670. if (this._nextActiveAction._child) {
  27671. if (!this._nextActiveAction._child._actionManager) {
  27672. this._nextActiveAction._child._actionManager = this._actionManager;
  27673. }
  27674. this._nextActiveAction = this._nextActiveAction._child;
  27675. }
  27676. else {
  27677. this._nextActiveAction = this;
  27678. }
  27679. };
  27680. Action.prototype.execute = function (evt) {
  27681. };
  27682. Action.prototype.then = function (action) {
  27683. this._child = action;
  27684. action._actionManager = this._actionManager;
  27685. action._prepare();
  27686. return action;
  27687. };
  27688. Action.prototype._getProperty = function (propertyPath) {
  27689. return this._actionManager._getProperty(propertyPath);
  27690. };
  27691. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27692. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27693. };
  27694. return Action;
  27695. })();
  27696. BABYLON.Action = Action;
  27697. })(BABYLON || (BABYLON = {}));
  27698. var BABYLON;
  27699. (function (BABYLON) {
  27700. /**
  27701. * ActionEvent is the event beint sent when an action is triggered.
  27702. */
  27703. var ActionEvent = (function () {
  27704. /**
  27705. * @constructor
  27706. * @param source The mesh that triggered the action.
  27707. * @param pointerX the X mouse cursor position at the time of the event
  27708. * @param pointerY the Y mouse cursor position at the time of the event
  27709. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27710. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27711. */
  27712. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27713. this.source = source;
  27714. this.pointerX = pointerX;
  27715. this.pointerY = pointerY;
  27716. this.meshUnderPointer = meshUnderPointer;
  27717. this.sourceEvent = sourceEvent;
  27718. this.additionalData = additionalData;
  27719. }
  27720. /**
  27721. * Helper function to auto-create an ActionEvent from a source mesh.
  27722. * @param source the source mesh that triggered the event
  27723. * @param evt {Event} The original (browser) event
  27724. */
  27725. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27726. var scene = source.getScene();
  27727. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27728. };
  27729. /**
  27730. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27731. * @param scene the scene where the event occurred
  27732. * @param evt {Event} The original (browser) event
  27733. */
  27734. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27735. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27736. };
  27737. return ActionEvent;
  27738. })();
  27739. BABYLON.ActionEvent = ActionEvent;
  27740. /**
  27741. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27742. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27743. */
  27744. var ActionManager = (function () {
  27745. function ActionManager(scene) {
  27746. // Members
  27747. this.actions = new Array();
  27748. this._scene = scene;
  27749. scene._actionManagers.push(this);
  27750. }
  27751. Object.defineProperty(ActionManager, "NothingTrigger", {
  27752. get: function () {
  27753. return ActionManager._NothingTrigger;
  27754. },
  27755. enumerable: true,
  27756. configurable: true
  27757. });
  27758. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27759. get: function () {
  27760. return ActionManager._OnPickTrigger;
  27761. },
  27762. enumerable: true,
  27763. configurable: true
  27764. });
  27765. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27766. get: function () {
  27767. return ActionManager._OnLeftPickTrigger;
  27768. },
  27769. enumerable: true,
  27770. configurable: true
  27771. });
  27772. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27773. get: function () {
  27774. return ActionManager._OnRightPickTrigger;
  27775. },
  27776. enumerable: true,
  27777. configurable: true
  27778. });
  27779. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27780. get: function () {
  27781. return ActionManager._OnCenterPickTrigger;
  27782. },
  27783. enumerable: true,
  27784. configurable: true
  27785. });
  27786. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27787. get: function () {
  27788. return ActionManager._OnPointerOverTrigger;
  27789. },
  27790. enumerable: true,
  27791. configurable: true
  27792. });
  27793. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27794. get: function () {
  27795. return ActionManager._OnPointerOutTrigger;
  27796. },
  27797. enumerable: true,
  27798. configurable: true
  27799. });
  27800. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27801. get: function () {
  27802. return ActionManager._OnEveryFrameTrigger;
  27803. },
  27804. enumerable: true,
  27805. configurable: true
  27806. });
  27807. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27808. get: function () {
  27809. return ActionManager._OnIntersectionEnterTrigger;
  27810. },
  27811. enumerable: true,
  27812. configurable: true
  27813. });
  27814. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27815. get: function () {
  27816. return ActionManager._OnIntersectionExitTrigger;
  27817. },
  27818. enumerable: true,
  27819. configurable: true
  27820. });
  27821. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27822. get: function () {
  27823. return ActionManager._OnKeyDownTrigger;
  27824. },
  27825. enumerable: true,
  27826. configurable: true
  27827. });
  27828. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27829. get: function () {
  27830. return ActionManager._OnKeyUpTrigger;
  27831. },
  27832. enumerable: true,
  27833. configurable: true
  27834. });
  27835. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27836. get: function () {
  27837. return ActionManager._OnPickUpTrigger;
  27838. },
  27839. enumerable: true,
  27840. configurable: true
  27841. });
  27842. // Methods
  27843. ActionManager.prototype.dispose = function () {
  27844. var index = this._scene._actionManagers.indexOf(this);
  27845. if (index > -1) {
  27846. this._scene._actionManagers.splice(index, 1);
  27847. }
  27848. };
  27849. ActionManager.prototype.getScene = function () {
  27850. return this._scene;
  27851. };
  27852. /**
  27853. * Does this action manager handles actions of any of the given triggers
  27854. * @param {number[]} triggers - the triggers to be tested
  27855. * @return {boolean} whether one (or more) of the triggers is handeled
  27856. */
  27857. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27858. for (var index = 0; index < this.actions.length; index++) {
  27859. var action = this.actions[index];
  27860. if (triggers.indexOf(action.trigger) > -1) {
  27861. return true;
  27862. }
  27863. }
  27864. return false;
  27865. };
  27866. /**
  27867. * Does this action manager handles actions of a given trigger
  27868. * @param {number} trigger - the trigger to be tested
  27869. * @return {boolean} whether the trigger is handeled
  27870. */
  27871. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27872. for (var index = 0; index < this.actions.length; index++) {
  27873. var action = this.actions[index];
  27874. if (action.trigger === trigger) {
  27875. return true;
  27876. }
  27877. }
  27878. return false;
  27879. };
  27880. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27881. /**
  27882. * Does this action manager has pointer triggers
  27883. * @return {boolean} whether or not it has pointer triggers
  27884. */
  27885. get: function () {
  27886. for (var index = 0; index < this.actions.length; index++) {
  27887. var action = this.actions[index];
  27888. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27889. return true;
  27890. }
  27891. if (action.trigger == ActionManager._OnPickUpTrigger) {
  27892. return true;
  27893. }
  27894. }
  27895. return false;
  27896. },
  27897. enumerable: true,
  27898. configurable: true
  27899. });
  27900. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27901. /**
  27902. * Does this action manager has pick triggers
  27903. * @return {boolean} whether or not it has pick triggers
  27904. */
  27905. get: function () {
  27906. for (var index = 0; index < this.actions.length; index++) {
  27907. var action = this.actions[index];
  27908. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  27909. return true;
  27910. }
  27911. }
  27912. return false;
  27913. },
  27914. enumerable: true,
  27915. configurable: true
  27916. });
  27917. /**
  27918. * Registers an action to this action manager
  27919. * @param {BABYLON.Action} action - the action to be registered
  27920. * @return {BABYLON.Action} the action amended (prepared) after registration
  27921. */
  27922. ActionManager.prototype.registerAction = function (action) {
  27923. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27924. if (this.getScene().actionManager !== this) {
  27925. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27926. return null;
  27927. }
  27928. }
  27929. this.actions.push(action);
  27930. action._actionManager = this;
  27931. action._prepare();
  27932. return action;
  27933. };
  27934. /**
  27935. * Process a specific trigger
  27936. * @param {number} trigger - the trigger to process
  27937. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27938. */
  27939. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27940. for (var index = 0; index < this.actions.length; index++) {
  27941. var action = this.actions[index];
  27942. if (action.trigger === trigger) {
  27943. if (trigger === ActionManager.OnKeyUpTrigger
  27944. || trigger === ActionManager.OnKeyDownTrigger) {
  27945. var parameter = action.getTriggerParameter();
  27946. if (parameter) {
  27947. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27948. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27949. if (actualkey !== parameter.toLowerCase()) {
  27950. continue;
  27951. }
  27952. }
  27953. }
  27954. action._executeCurrent(evt);
  27955. }
  27956. }
  27957. };
  27958. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  27959. var properties = propertyPath.split(".");
  27960. for (var index = 0; index < properties.length - 1; index++) {
  27961. target = target[properties[index]];
  27962. }
  27963. return target;
  27964. };
  27965. ActionManager.prototype._getProperty = function (propertyPath) {
  27966. var properties = propertyPath.split(".");
  27967. return properties[properties.length - 1];
  27968. };
  27969. // Statics
  27970. ActionManager._NothingTrigger = 0;
  27971. ActionManager._OnPickTrigger = 1;
  27972. ActionManager._OnLeftPickTrigger = 2;
  27973. ActionManager._OnRightPickTrigger = 3;
  27974. ActionManager._OnCenterPickTrigger = 4;
  27975. ActionManager._OnPointerOverTrigger = 5;
  27976. ActionManager._OnPointerOutTrigger = 6;
  27977. ActionManager._OnEveryFrameTrigger = 7;
  27978. ActionManager._OnIntersectionEnterTrigger = 8;
  27979. ActionManager._OnIntersectionExitTrigger = 9;
  27980. ActionManager._OnKeyDownTrigger = 10;
  27981. ActionManager._OnKeyUpTrigger = 11;
  27982. ActionManager._OnPickUpTrigger = 12;
  27983. return ActionManager;
  27984. })();
  27985. BABYLON.ActionManager = ActionManager;
  27986. })(BABYLON || (BABYLON = {}));
  27987. var BABYLON;
  27988. (function (BABYLON) {
  27989. var InterpolateValueAction = (function (_super) {
  27990. __extends(InterpolateValueAction, _super);
  27991. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  27992. if (duration === void 0) { duration = 1000; }
  27993. _super.call(this, triggerOptions, condition);
  27994. this.propertyPath = propertyPath;
  27995. this.value = value;
  27996. this.duration = duration;
  27997. this.stopOtherAnimations = stopOtherAnimations;
  27998. this._target = target;
  27999. }
  28000. InterpolateValueAction.prototype._prepare = function () {
  28001. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28002. this._property = this._getProperty(this.propertyPath);
  28003. };
  28004. InterpolateValueAction.prototype.execute = function () {
  28005. var scene = this._actionManager.getScene();
  28006. var keys = [
  28007. {
  28008. frame: 0,
  28009. value: this._target[this._property]
  28010. }, {
  28011. frame: 100,
  28012. value: this.value
  28013. }
  28014. ];
  28015. var dataType;
  28016. if (typeof this.value === "number") {
  28017. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28018. }
  28019. else if (this.value instanceof BABYLON.Color3) {
  28020. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28021. }
  28022. else if (this.value instanceof BABYLON.Vector3) {
  28023. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28024. }
  28025. else if (this.value instanceof BABYLON.Matrix) {
  28026. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28027. }
  28028. else if (this.value instanceof BABYLON.Quaternion) {
  28029. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28030. }
  28031. else {
  28032. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28033. return;
  28034. }
  28035. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28036. animation.setKeys(keys);
  28037. if (this.stopOtherAnimations) {
  28038. scene.stopAnimation(this._target);
  28039. }
  28040. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  28041. };
  28042. return InterpolateValueAction;
  28043. })(BABYLON.Action);
  28044. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28045. })(BABYLON || (BABYLON = {}));
  28046. var BABYLON;
  28047. (function (BABYLON) {
  28048. var SwitchBooleanAction = (function (_super) {
  28049. __extends(SwitchBooleanAction, _super);
  28050. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28051. _super.call(this, triggerOptions, condition);
  28052. this.propertyPath = propertyPath;
  28053. this._target = target;
  28054. }
  28055. SwitchBooleanAction.prototype._prepare = function () {
  28056. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28057. this._property = this._getProperty(this.propertyPath);
  28058. };
  28059. SwitchBooleanAction.prototype.execute = function () {
  28060. this._target[this._property] = !this._target[this._property];
  28061. };
  28062. return SwitchBooleanAction;
  28063. })(BABYLON.Action);
  28064. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28065. var SetStateAction = (function (_super) {
  28066. __extends(SetStateAction, _super);
  28067. function SetStateAction(triggerOptions, target, value, condition) {
  28068. _super.call(this, triggerOptions, condition);
  28069. this.value = value;
  28070. this._target = target;
  28071. }
  28072. SetStateAction.prototype.execute = function () {
  28073. this._target.state = this.value;
  28074. };
  28075. return SetStateAction;
  28076. })(BABYLON.Action);
  28077. BABYLON.SetStateAction = SetStateAction;
  28078. var SetValueAction = (function (_super) {
  28079. __extends(SetValueAction, _super);
  28080. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28081. _super.call(this, triggerOptions, condition);
  28082. this.propertyPath = propertyPath;
  28083. this.value = value;
  28084. this._target = target;
  28085. }
  28086. SetValueAction.prototype._prepare = function () {
  28087. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28088. this._property = this._getProperty(this.propertyPath);
  28089. };
  28090. SetValueAction.prototype.execute = function () {
  28091. this._target[this._property] = this.value;
  28092. };
  28093. return SetValueAction;
  28094. })(BABYLON.Action);
  28095. BABYLON.SetValueAction = SetValueAction;
  28096. var IncrementValueAction = (function (_super) {
  28097. __extends(IncrementValueAction, _super);
  28098. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28099. _super.call(this, triggerOptions, condition);
  28100. this.propertyPath = propertyPath;
  28101. this.value = value;
  28102. this._target = target;
  28103. }
  28104. IncrementValueAction.prototype._prepare = function () {
  28105. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28106. this._property = this._getProperty(this.propertyPath);
  28107. if (typeof this._target[this._property] !== "number") {
  28108. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28109. }
  28110. };
  28111. IncrementValueAction.prototype.execute = function () {
  28112. this._target[this._property] += this.value;
  28113. };
  28114. return IncrementValueAction;
  28115. })(BABYLON.Action);
  28116. BABYLON.IncrementValueAction = IncrementValueAction;
  28117. var PlayAnimationAction = (function (_super) {
  28118. __extends(PlayAnimationAction, _super);
  28119. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28120. _super.call(this, triggerOptions, condition);
  28121. this.from = from;
  28122. this.to = to;
  28123. this.loop = loop;
  28124. this._target = target;
  28125. }
  28126. PlayAnimationAction.prototype._prepare = function () {
  28127. };
  28128. PlayAnimationAction.prototype.execute = function () {
  28129. var scene = this._actionManager.getScene();
  28130. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28131. };
  28132. return PlayAnimationAction;
  28133. })(BABYLON.Action);
  28134. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28135. var StopAnimationAction = (function (_super) {
  28136. __extends(StopAnimationAction, _super);
  28137. function StopAnimationAction(triggerOptions, target, condition) {
  28138. _super.call(this, triggerOptions, condition);
  28139. this._target = target;
  28140. }
  28141. StopAnimationAction.prototype._prepare = function () {
  28142. };
  28143. StopAnimationAction.prototype.execute = function () {
  28144. var scene = this._actionManager.getScene();
  28145. scene.stopAnimation(this._target);
  28146. };
  28147. return StopAnimationAction;
  28148. })(BABYLON.Action);
  28149. BABYLON.StopAnimationAction = StopAnimationAction;
  28150. var DoNothingAction = (function (_super) {
  28151. __extends(DoNothingAction, _super);
  28152. function DoNothingAction(triggerOptions, condition) {
  28153. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28154. _super.call(this, triggerOptions, condition);
  28155. }
  28156. DoNothingAction.prototype.execute = function () {
  28157. };
  28158. return DoNothingAction;
  28159. })(BABYLON.Action);
  28160. BABYLON.DoNothingAction = DoNothingAction;
  28161. var CombineAction = (function (_super) {
  28162. __extends(CombineAction, _super);
  28163. function CombineAction(triggerOptions, children, condition) {
  28164. _super.call(this, triggerOptions, condition);
  28165. this.children = children;
  28166. }
  28167. CombineAction.prototype._prepare = function () {
  28168. for (var index = 0; index < this.children.length; index++) {
  28169. this.children[index]._actionManager = this._actionManager;
  28170. this.children[index]._prepare();
  28171. }
  28172. };
  28173. CombineAction.prototype.execute = function (evt) {
  28174. for (var index = 0; index < this.children.length; index++) {
  28175. this.children[index].execute(evt);
  28176. }
  28177. };
  28178. return CombineAction;
  28179. })(BABYLON.Action);
  28180. BABYLON.CombineAction = CombineAction;
  28181. var ExecuteCodeAction = (function (_super) {
  28182. __extends(ExecuteCodeAction, _super);
  28183. function ExecuteCodeAction(triggerOptions, func, condition) {
  28184. _super.call(this, triggerOptions, condition);
  28185. this.func = func;
  28186. }
  28187. ExecuteCodeAction.prototype.execute = function (evt) {
  28188. this.func(evt);
  28189. };
  28190. return ExecuteCodeAction;
  28191. })(BABYLON.Action);
  28192. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28193. var SetParentAction = (function (_super) {
  28194. __extends(SetParentAction, _super);
  28195. function SetParentAction(triggerOptions, target, parent, condition) {
  28196. _super.call(this, triggerOptions, condition);
  28197. this._target = target;
  28198. this._parent = parent;
  28199. }
  28200. SetParentAction.prototype._prepare = function () {
  28201. };
  28202. SetParentAction.prototype.execute = function () {
  28203. if (this._target.parent === this._parent) {
  28204. return;
  28205. }
  28206. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28207. invertParentWorldMatrix.invert();
  28208. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28209. this._target.parent = this._parent;
  28210. };
  28211. return SetParentAction;
  28212. })(BABYLON.Action);
  28213. BABYLON.SetParentAction = SetParentAction;
  28214. var PlaySoundAction = (function (_super) {
  28215. __extends(PlaySoundAction, _super);
  28216. function PlaySoundAction(triggerOptions, sound, condition) {
  28217. _super.call(this, triggerOptions, condition);
  28218. this._sound = sound;
  28219. }
  28220. PlaySoundAction.prototype._prepare = function () {
  28221. };
  28222. PlaySoundAction.prototype.execute = function () {
  28223. if (this._sound !== undefined)
  28224. this._sound.play();
  28225. };
  28226. return PlaySoundAction;
  28227. })(BABYLON.Action);
  28228. BABYLON.PlaySoundAction = PlaySoundAction;
  28229. var StopSoundAction = (function (_super) {
  28230. __extends(StopSoundAction, _super);
  28231. function StopSoundAction(triggerOptions, sound, condition) {
  28232. _super.call(this, triggerOptions, condition);
  28233. this._sound = sound;
  28234. }
  28235. StopSoundAction.prototype._prepare = function () {
  28236. };
  28237. StopSoundAction.prototype.execute = function () {
  28238. if (this._sound !== undefined)
  28239. this._sound.stop();
  28240. };
  28241. return StopSoundAction;
  28242. })(BABYLON.Action);
  28243. BABYLON.StopSoundAction = StopSoundAction;
  28244. })(BABYLON || (BABYLON = {}));
  28245. var BABYLON;
  28246. (function (BABYLON) {
  28247. var Geometry = (function () {
  28248. function Geometry(id, scene, vertexData, updatable, mesh) {
  28249. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28250. this._totalVertices = 0;
  28251. this._indices = [];
  28252. this._isDisposed = false;
  28253. this.id = id;
  28254. this._engine = scene.getEngine();
  28255. this._meshes = [];
  28256. this._scene = scene;
  28257. // vertexData
  28258. if (vertexData) {
  28259. this.setAllVerticesData(vertexData, updatable);
  28260. }
  28261. else {
  28262. this._totalVertices = 0;
  28263. this._indices = [];
  28264. }
  28265. // applyToMesh
  28266. if (mesh) {
  28267. this.applyToMesh(mesh);
  28268. mesh.computeWorldMatrix(true);
  28269. }
  28270. }
  28271. Geometry.prototype.getScene = function () {
  28272. return this._scene;
  28273. };
  28274. Geometry.prototype.getEngine = function () {
  28275. return this._engine;
  28276. };
  28277. Geometry.prototype.isReady = function () {
  28278. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28279. };
  28280. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28281. vertexData.applyToGeometry(this, updatable);
  28282. this.notifyUpdate();
  28283. };
  28284. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28285. this._vertexBuffers = this._vertexBuffers || {};
  28286. if (this._vertexBuffers[kind]) {
  28287. this._vertexBuffers[kind].dispose();
  28288. }
  28289. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28290. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28291. stride = this._vertexBuffers[kind].getStrideSize();
  28292. this._totalVertices = data.length / stride;
  28293. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28294. var meshes = this._meshes;
  28295. var numOfMeshes = meshes.length;
  28296. for (var index = 0; index < numOfMeshes; index++) {
  28297. var mesh = meshes[index];
  28298. mesh._resetPointsArrayCache();
  28299. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28300. mesh._createGlobalSubMesh();
  28301. mesh.computeWorldMatrix(true);
  28302. }
  28303. }
  28304. this.notifyUpdate(kind);
  28305. };
  28306. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28307. var vertexBuffer = this.getVertexBuffer(kind);
  28308. if (!vertexBuffer) {
  28309. return;
  28310. }
  28311. vertexBuffer.updateDirectly(data, offset);
  28312. this.notifyUpdate(kind);
  28313. };
  28314. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28315. var vertexBuffer = this.getVertexBuffer(kind);
  28316. if (!vertexBuffer) {
  28317. return;
  28318. }
  28319. vertexBuffer.update(data);
  28320. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28321. var extend;
  28322. var stride = vertexBuffer.getStrideSize();
  28323. this._totalVertices = data.length / stride;
  28324. if (updateExtends) {
  28325. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28326. }
  28327. var meshes = this._meshes;
  28328. var numOfMeshes = meshes.length;
  28329. for (var index = 0; index < numOfMeshes; index++) {
  28330. var mesh = meshes[index];
  28331. mesh._resetPointsArrayCache();
  28332. if (updateExtends) {
  28333. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28334. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28335. var subMesh = mesh.subMeshes[subIndex];
  28336. subMesh.refreshBoundingInfo();
  28337. }
  28338. }
  28339. }
  28340. }
  28341. this.notifyUpdate(kind);
  28342. };
  28343. Geometry.prototype.getTotalVertices = function () {
  28344. if (!this.isReady()) {
  28345. return 0;
  28346. }
  28347. return this._totalVertices;
  28348. };
  28349. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28350. var vertexBuffer = this.getVertexBuffer(kind);
  28351. if (!vertexBuffer) {
  28352. return null;
  28353. }
  28354. var orig = vertexBuffer.getData();
  28355. if (!copyWhenShared || this._meshes.length === 1) {
  28356. return orig;
  28357. }
  28358. else {
  28359. var len = orig.length;
  28360. var copy = [];
  28361. for (var i = 0; i < len; i++) {
  28362. copy.push(orig[i]);
  28363. }
  28364. return copy;
  28365. }
  28366. };
  28367. Geometry.prototype.getVertexBuffer = function (kind) {
  28368. if (!this.isReady()) {
  28369. return null;
  28370. }
  28371. return this._vertexBuffers[kind];
  28372. };
  28373. Geometry.prototype.getVertexBuffers = function () {
  28374. if (!this.isReady()) {
  28375. return null;
  28376. }
  28377. return this._vertexBuffers;
  28378. };
  28379. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28380. if (!this._vertexBuffers) {
  28381. if (this._delayInfo) {
  28382. return this._delayInfo.indexOf(kind) !== -1;
  28383. }
  28384. return false;
  28385. }
  28386. return this._vertexBuffers[kind] !== undefined;
  28387. };
  28388. Geometry.prototype.getVerticesDataKinds = function () {
  28389. var result = [];
  28390. if (!this._vertexBuffers && this._delayInfo) {
  28391. for (var kind in this._delayInfo) {
  28392. result.push(kind);
  28393. }
  28394. }
  28395. else {
  28396. for (kind in this._vertexBuffers) {
  28397. result.push(kind);
  28398. }
  28399. }
  28400. return result;
  28401. };
  28402. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28403. if (this._indexBuffer) {
  28404. this._engine._releaseBuffer(this._indexBuffer);
  28405. }
  28406. this._indices = indices;
  28407. if (this._meshes.length !== 0 && this._indices) {
  28408. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28409. }
  28410. if (totalVertices !== undefined) {
  28411. this._totalVertices = totalVertices;
  28412. }
  28413. var meshes = this._meshes;
  28414. var numOfMeshes = meshes.length;
  28415. for (var index = 0; index < numOfMeshes; index++) {
  28416. meshes[index]._createGlobalSubMesh();
  28417. }
  28418. this.notifyUpdate();
  28419. };
  28420. Geometry.prototype.getTotalIndices = function () {
  28421. if (!this.isReady()) {
  28422. return 0;
  28423. }
  28424. return this._indices.length;
  28425. };
  28426. Geometry.prototype.getIndices = function (copyWhenShared) {
  28427. if (!this.isReady()) {
  28428. return null;
  28429. }
  28430. var orig = this._indices;
  28431. if (!copyWhenShared || this._meshes.length === 1) {
  28432. return orig;
  28433. }
  28434. else {
  28435. var len = orig.length;
  28436. var copy = [];
  28437. for (var i = 0; i < len; i++) {
  28438. copy.push(orig[i]);
  28439. }
  28440. return copy;
  28441. }
  28442. };
  28443. Geometry.prototype.getIndexBuffer = function () {
  28444. if (!this.isReady()) {
  28445. return null;
  28446. }
  28447. return this._indexBuffer;
  28448. };
  28449. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28450. var meshes = this._meshes;
  28451. var index = meshes.indexOf(mesh);
  28452. if (index === -1) {
  28453. return;
  28454. }
  28455. for (var kind in this._vertexBuffers) {
  28456. this._vertexBuffers[kind].dispose();
  28457. }
  28458. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28459. this._indexBuffer = null;
  28460. }
  28461. meshes.splice(index, 1);
  28462. mesh._geometry = null;
  28463. if (meshes.length === 0 && shouldDispose) {
  28464. this.dispose();
  28465. }
  28466. };
  28467. Geometry.prototype.applyToMesh = function (mesh) {
  28468. if (mesh._geometry === this) {
  28469. return;
  28470. }
  28471. var previousGeometry = mesh._geometry;
  28472. if (previousGeometry) {
  28473. previousGeometry.releaseForMesh(mesh);
  28474. }
  28475. var meshes = this._meshes;
  28476. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28477. mesh._geometry = this;
  28478. this._scene.pushGeometry(this);
  28479. meshes.push(mesh);
  28480. if (this.isReady()) {
  28481. this._applyToMesh(mesh);
  28482. }
  28483. else {
  28484. mesh._boundingInfo = this._boundingInfo;
  28485. }
  28486. };
  28487. Geometry.prototype._applyToMesh = function (mesh) {
  28488. var numOfMeshes = this._meshes.length;
  28489. // vertexBuffers
  28490. for (var kind in this._vertexBuffers) {
  28491. if (numOfMeshes === 1) {
  28492. this._vertexBuffers[kind].create();
  28493. }
  28494. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28495. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28496. mesh._resetPointsArrayCache();
  28497. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28498. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28499. mesh._createGlobalSubMesh();
  28500. //bounding info was just created again, world matrix should be applied again.
  28501. mesh._updateBoundingInfo();
  28502. }
  28503. }
  28504. // indexBuffer
  28505. if (numOfMeshes === 1 && this._indices) {
  28506. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28507. }
  28508. if (this._indexBuffer) {
  28509. this._indexBuffer.references = numOfMeshes;
  28510. }
  28511. };
  28512. Geometry.prototype.notifyUpdate = function (kind) {
  28513. if (this.onGeometryUpdated) {
  28514. this.onGeometryUpdated(this, kind);
  28515. }
  28516. };
  28517. Geometry.prototype.load = function (scene, onLoaded) {
  28518. var _this = this;
  28519. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28520. return;
  28521. }
  28522. if (this.isReady()) {
  28523. if (onLoaded) {
  28524. onLoaded();
  28525. }
  28526. return;
  28527. }
  28528. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28529. scene._addPendingData(this);
  28530. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28531. _this._delayLoadingFunction(JSON.parse(data), _this);
  28532. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28533. _this._delayInfo = [];
  28534. scene._removePendingData(_this);
  28535. var meshes = _this._meshes;
  28536. var numOfMeshes = meshes.length;
  28537. for (var index = 0; index < numOfMeshes; index++) {
  28538. _this._applyToMesh(meshes[index]);
  28539. }
  28540. if (onLoaded) {
  28541. onLoaded();
  28542. }
  28543. }, function () { }, scene.database);
  28544. };
  28545. Geometry.prototype.isDisposed = function () {
  28546. return this._isDisposed;
  28547. };
  28548. Geometry.prototype.dispose = function () {
  28549. var meshes = this._meshes;
  28550. var numOfMeshes = meshes.length;
  28551. var index;
  28552. for (index = 0; index < numOfMeshes; index++) {
  28553. this.releaseForMesh(meshes[index]);
  28554. }
  28555. this._meshes = [];
  28556. for (var kind in this._vertexBuffers) {
  28557. this._vertexBuffers[kind].dispose();
  28558. }
  28559. this._vertexBuffers = [];
  28560. this._totalVertices = 0;
  28561. if (this._indexBuffer) {
  28562. this._engine._releaseBuffer(this._indexBuffer);
  28563. }
  28564. this._indexBuffer = null;
  28565. this._indices = [];
  28566. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28567. this.delayLoadingFile = null;
  28568. this._delayLoadingFunction = null;
  28569. this._delayInfo = [];
  28570. this._boundingInfo = null; // todo: .dispose()
  28571. this._scene.removeGeometry(this);
  28572. this._isDisposed = true;
  28573. };
  28574. Geometry.prototype.copy = function (id) {
  28575. var vertexData = new BABYLON.VertexData();
  28576. vertexData.indices = [];
  28577. var indices = this.getIndices();
  28578. for (var index = 0; index < indices.length; index++) {
  28579. vertexData.indices.push(indices[index]);
  28580. }
  28581. var updatable = false;
  28582. var stopChecking = false;
  28583. for (var kind in this._vertexBuffers) {
  28584. // using slice() to make a copy of the array and not just reference it
  28585. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  28586. if (!stopChecking) {
  28587. updatable = this.getVertexBuffer(kind).isUpdatable();
  28588. stopChecking = !updatable;
  28589. }
  28590. }
  28591. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28592. geometry.delayLoadState = this.delayLoadState;
  28593. geometry.delayLoadingFile = this.delayLoadingFile;
  28594. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28595. for (kind in this._delayInfo) {
  28596. geometry._delayInfo = geometry._delayInfo || [];
  28597. geometry._delayInfo.push(kind);
  28598. }
  28599. // Bounding info
  28600. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  28601. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28602. return geometry;
  28603. };
  28604. // Statics
  28605. Geometry.ExtractFromMesh = function (mesh, id) {
  28606. var geometry = mesh._geometry;
  28607. if (!geometry) {
  28608. return null;
  28609. }
  28610. return geometry.copy(id);
  28611. };
  28612. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28613. // be aware Math.random() could cause collisions
  28614. Geometry.RandomId = function () {
  28615. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28616. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28617. return v.toString(16);
  28618. });
  28619. };
  28620. return Geometry;
  28621. })();
  28622. BABYLON.Geometry = Geometry;
  28623. /////// Primitives //////////////////////////////////////////////
  28624. var Geometry;
  28625. (function (Geometry) {
  28626. var Primitives;
  28627. (function (Primitives) {
  28628. /// Abstract class
  28629. var _Primitive = (function (_super) {
  28630. __extends(_Primitive, _super);
  28631. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  28632. this._beingRegenerated = true;
  28633. this._canBeRegenerated = canBeRegenerated;
  28634. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  28635. this._beingRegenerated = false;
  28636. }
  28637. _Primitive.prototype.canBeRegenerated = function () {
  28638. return this._canBeRegenerated;
  28639. };
  28640. _Primitive.prototype.regenerate = function () {
  28641. if (!this._canBeRegenerated) {
  28642. return;
  28643. }
  28644. this._beingRegenerated = true;
  28645. this.setAllVerticesData(this._regenerateVertexData(), false);
  28646. this._beingRegenerated = false;
  28647. };
  28648. _Primitive.prototype.asNewGeometry = function (id) {
  28649. return _super.prototype.copy.call(this, id);
  28650. };
  28651. // overrides
  28652. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28653. if (!this._beingRegenerated) {
  28654. return;
  28655. }
  28656. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28657. };
  28658. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28659. if (!this._beingRegenerated) {
  28660. return;
  28661. }
  28662. _super.prototype.setVerticesData.call(this, kind, data, false);
  28663. };
  28664. // to override
  28665. // protected
  28666. _Primitive.prototype._regenerateVertexData = function () {
  28667. throw new Error("Abstract method");
  28668. };
  28669. _Primitive.prototype.copy = function (id) {
  28670. throw new Error("Must be overriden in sub-classes.");
  28671. };
  28672. return _Primitive;
  28673. })(Geometry);
  28674. Primitives._Primitive = _Primitive;
  28675. var Ribbon = (function (_super) {
  28676. __extends(Ribbon, _super);
  28677. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28678. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28679. this.pathArray = pathArray;
  28680. this.closeArray = closeArray;
  28681. this.closePath = closePath;
  28682. this.offset = offset;
  28683. this.side = side;
  28684. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28685. }
  28686. Ribbon.prototype._regenerateVertexData = function () {
  28687. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  28688. };
  28689. Ribbon.prototype.copy = function (id) {
  28690. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28691. };
  28692. return Ribbon;
  28693. })(_Primitive);
  28694. Primitives.Ribbon = Ribbon;
  28695. var Box = (function (_super) {
  28696. __extends(Box, _super);
  28697. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28698. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28699. this.size = size;
  28700. this.side = side;
  28701. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28702. }
  28703. Box.prototype._regenerateVertexData = function () {
  28704. return BABYLON.VertexData.CreateBox(this.size, this.side);
  28705. };
  28706. Box.prototype.copy = function (id) {
  28707. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28708. };
  28709. return Box;
  28710. })(_Primitive);
  28711. Primitives.Box = Box;
  28712. var Sphere = (function (_super) {
  28713. __extends(Sphere, _super);
  28714. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28715. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28716. this.segments = segments;
  28717. this.diameter = diameter;
  28718. this.side = side;
  28719. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28720. }
  28721. Sphere.prototype._regenerateVertexData = function () {
  28722. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  28723. };
  28724. Sphere.prototype.copy = function (id) {
  28725. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28726. };
  28727. return Sphere;
  28728. })(_Primitive);
  28729. Primitives.Sphere = Sphere;
  28730. var Cylinder = (function (_super) {
  28731. __extends(Cylinder, _super);
  28732. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28733. if (subdivisions === void 0) { subdivisions = 1; }
  28734. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28735. this.height = height;
  28736. this.diameterTop = diameterTop;
  28737. this.diameterBottom = diameterBottom;
  28738. this.tessellation = tessellation;
  28739. this.subdivisions = subdivisions;
  28740. this.side = side;
  28741. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28742. }
  28743. Cylinder.prototype._regenerateVertexData = function () {
  28744. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  28745. };
  28746. Cylinder.prototype.copy = function (id) {
  28747. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28748. };
  28749. return Cylinder;
  28750. })(_Primitive);
  28751. Primitives.Cylinder = Cylinder;
  28752. var Torus = (function (_super) {
  28753. __extends(Torus, _super);
  28754. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28755. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28756. this.diameter = diameter;
  28757. this.thickness = thickness;
  28758. this.tessellation = tessellation;
  28759. this.side = side;
  28760. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28761. }
  28762. Torus.prototype._regenerateVertexData = function () {
  28763. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  28764. };
  28765. Torus.prototype.copy = function (id) {
  28766. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28767. };
  28768. return Torus;
  28769. })(_Primitive);
  28770. Primitives.Torus = Torus;
  28771. var Ground = (function (_super) {
  28772. __extends(Ground, _super);
  28773. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28774. this.width = width;
  28775. this.height = height;
  28776. this.subdivisions = subdivisions;
  28777. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28778. }
  28779. Ground.prototype._regenerateVertexData = function () {
  28780. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  28781. };
  28782. Ground.prototype.copy = function (id) {
  28783. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28784. };
  28785. return Ground;
  28786. })(_Primitive);
  28787. Primitives.Ground = Ground;
  28788. var TiledGround = (function (_super) {
  28789. __extends(TiledGround, _super);
  28790. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28791. this.xmin = xmin;
  28792. this.zmin = zmin;
  28793. this.xmax = xmax;
  28794. this.zmax = zmax;
  28795. this.subdivisions = subdivisions;
  28796. this.precision = precision;
  28797. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28798. }
  28799. TiledGround.prototype._regenerateVertexData = function () {
  28800. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  28801. };
  28802. TiledGround.prototype.copy = function (id) {
  28803. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28804. };
  28805. return TiledGround;
  28806. })(_Primitive);
  28807. Primitives.TiledGround = TiledGround;
  28808. var Plane = (function (_super) {
  28809. __extends(Plane, _super);
  28810. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28811. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28812. this.size = size;
  28813. this.side = side;
  28814. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28815. }
  28816. Plane.prototype._regenerateVertexData = function () {
  28817. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  28818. };
  28819. Plane.prototype.copy = function (id) {
  28820. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28821. };
  28822. return Plane;
  28823. })(_Primitive);
  28824. Primitives.Plane = Plane;
  28825. var TorusKnot = (function (_super) {
  28826. __extends(TorusKnot, _super);
  28827. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28828. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28829. this.radius = radius;
  28830. this.tube = tube;
  28831. this.radialSegments = radialSegments;
  28832. this.tubularSegments = tubularSegments;
  28833. this.p = p;
  28834. this.q = q;
  28835. this.side = side;
  28836. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28837. }
  28838. TorusKnot.prototype._regenerateVertexData = function () {
  28839. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  28840. };
  28841. TorusKnot.prototype.copy = function (id) {
  28842. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28843. };
  28844. return TorusKnot;
  28845. })(_Primitive);
  28846. Primitives.TorusKnot = TorusKnot;
  28847. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28848. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28849. })(BABYLON || (BABYLON = {}));
  28850. var BABYLON;
  28851. (function (BABYLON) {
  28852. var GroundMesh = (function (_super) {
  28853. __extends(GroundMesh, _super);
  28854. function GroundMesh(name, scene) {
  28855. _super.call(this, name, scene);
  28856. this.generateOctree = false;
  28857. this._worldInverse = new BABYLON.Matrix();
  28858. }
  28859. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28860. get: function () {
  28861. return this._subdivisions;
  28862. },
  28863. enumerable: true,
  28864. configurable: true
  28865. });
  28866. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28867. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28868. this._subdivisions = chunksCount;
  28869. this.subdivide(this._subdivisions);
  28870. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28871. };
  28872. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28873. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  28874. this.getWorldMatrix().invertToRef(this._worldInverse);
  28875. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  28876. var pickInfo = this.intersects(ray);
  28877. if (pickInfo.hit) {
  28878. return pickInfo.pickedPoint.y;
  28879. }
  28880. return 0;
  28881. };
  28882. return GroundMesh;
  28883. })(BABYLON.Mesh);
  28884. BABYLON.GroundMesh = GroundMesh;
  28885. })(BABYLON || (BABYLON = {}));
  28886. var BABYLON;
  28887. (function (BABYLON) {
  28888. var LinesMesh = (function (_super) {
  28889. __extends(LinesMesh, _super);
  28890. function LinesMesh(name, scene, updatable) {
  28891. if (updatable === void 0) { updatable = false; }
  28892. _super.call(this, name, scene);
  28893. this.color = new BABYLON.Color3(1, 1, 1);
  28894. this.alpha = 1;
  28895. this._indices = new Array();
  28896. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28897. attributes: ["position"],
  28898. uniforms: ["worldViewProjection", "color"],
  28899. needAlphaBlending: true
  28900. });
  28901. }
  28902. Object.defineProperty(LinesMesh.prototype, "material", {
  28903. get: function () {
  28904. return this._colorShader;
  28905. },
  28906. enumerable: true,
  28907. configurable: true
  28908. });
  28909. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28910. get: function () {
  28911. return false;
  28912. },
  28913. enumerable: true,
  28914. configurable: true
  28915. });
  28916. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28917. get: function () {
  28918. return false;
  28919. },
  28920. enumerable: true,
  28921. configurable: true
  28922. });
  28923. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28924. var engine = this.getScene().getEngine();
  28925. var indexToBind = this._geometry.getIndexBuffer();
  28926. // VBOs
  28927. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28928. // Color
  28929. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28930. };
  28931. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28932. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28933. return;
  28934. }
  28935. var engine = this.getScene().getEngine();
  28936. // Draw order
  28937. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28938. };
  28939. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28940. return null;
  28941. };
  28942. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28943. this._colorShader.dispose();
  28944. _super.prototype.dispose.call(this, doNotRecurse);
  28945. };
  28946. return LinesMesh;
  28947. })(BABYLON.Mesh);
  28948. BABYLON.LinesMesh = LinesMesh;
  28949. })(BABYLON || (BABYLON = {}));
  28950. var BABYLON;
  28951. (function (BABYLON) {
  28952. var OutlineRenderer = (function () {
  28953. function OutlineRenderer(scene) {
  28954. this._scene = scene;
  28955. }
  28956. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  28957. var _this = this;
  28958. if (useOverlay === void 0) { useOverlay = false; }
  28959. var scene = this._scene;
  28960. var engine = this._scene.getEngine();
  28961. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28962. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  28963. return;
  28964. }
  28965. var mesh = subMesh.getRenderingMesh();
  28966. var material = subMesh.getMaterial();
  28967. engine.enableEffect(this._effect);
  28968. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  28969. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  28970. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28971. // Bones
  28972. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  28973. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28974. }
  28975. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  28976. // Alpha test
  28977. if (material && material.needAlphaTesting()) {
  28978. var alphaTexture = material.getAlphaTestTexture();
  28979. this._effect.setTexture("diffuseSampler", alphaTexture);
  28980. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28981. }
  28982. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  28983. };
  28984. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  28985. var defines = [];
  28986. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  28987. var mesh = subMesh.getMesh();
  28988. var material = subMesh.getMaterial();
  28989. // Alpha test
  28990. if (material && material.needAlphaTesting()) {
  28991. defines.push("#define ALPHATEST");
  28992. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28993. attribs.push(BABYLON.VertexBuffer.UVKind);
  28994. defines.push("#define UV1");
  28995. }
  28996. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28997. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28998. defines.push("#define UV2");
  28999. }
  29000. }
  29001. // Bones
  29002. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29003. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29004. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29005. defines.push("#define BONES");
  29006. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29007. }
  29008. // Instances
  29009. if (useInstances) {
  29010. defines.push("#define INSTANCES");
  29011. attribs.push("world0");
  29012. attribs.push("world1");
  29013. attribs.push("world2");
  29014. attribs.push("world3");
  29015. }
  29016. // Get correct effect
  29017. var join = defines.join("\n");
  29018. if (this._cachedDefines !== join) {
  29019. this._cachedDefines = join;
  29020. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29021. }
  29022. return this._effect.isReady();
  29023. };
  29024. return OutlineRenderer;
  29025. })();
  29026. BABYLON.OutlineRenderer = OutlineRenderer;
  29027. })(BABYLON || (BABYLON = {}));
  29028. var BABYLON;
  29029. (function (BABYLON) {
  29030. var MeshAssetTask = (function () {
  29031. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29032. this.name = name;
  29033. this.meshesNames = meshesNames;
  29034. this.rootUrl = rootUrl;
  29035. this.sceneFilename = sceneFilename;
  29036. this.isCompleted = false;
  29037. }
  29038. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29039. var _this = this;
  29040. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29041. _this.loadedMeshes = meshes;
  29042. _this.loadedParticleSystems = particleSystems;
  29043. _this.loadedSkeletons = skeletons;
  29044. _this.isCompleted = true;
  29045. if (_this.onSuccess) {
  29046. _this.onSuccess(_this);
  29047. }
  29048. onSuccess();
  29049. }, null, function () {
  29050. if (_this.onError) {
  29051. _this.onError(_this);
  29052. }
  29053. onError();
  29054. });
  29055. };
  29056. return MeshAssetTask;
  29057. })();
  29058. BABYLON.MeshAssetTask = MeshAssetTask;
  29059. var TextFileAssetTask = (function () {
  29060. function TextFileAssetTask(name, url) {
  29061. this.name = name;
  29062. this.url = url;
  29063. this.isCompleted = false;
  29064. }
  29065. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29066. var _this = this;
  29067. BABYLON.Tools.LoadFile(this.url, function (data) {
  29068. _this.text = data;
  29069. _this.isCompleted = true;
  29070. if (_this.onSuccess) {
  29071. _this.onSuccess(_this);
  29072. }
  29073. onSuccess();
  29074. }, null, scene.database, false, function () {
  29075. if (_this.onError) {
  29076. _this.onError(_this);
  29077. }
  29078. onError();
  29079. });
  29080. };
  29081. return TextFileAssetTask;
  29082. })();
  29083. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29084. var BinaryFileAssetTask = (function () {
  29085. function BinaryFileAssetTask(name, url) {
  29086. this.name = name;
  29087. this.url = url;
  29088. this.isCompleted = false;
  29089. }
  29090. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29091. var _this = this;
  29092. BABYLON.Tools.LoadFile(this.url, function (data) {
  29093. _this.data = data;
  29094. _this.isCompleted = true;
  29095. if (_this.onSuccess) {
  29096. _this.onSuccess(_this);
  29097. }
  29098. onSuccess();
  29099. }, null, scene.database, true, function () {
  29100. if (_this.onError) {
  29101. _this.onError(_this);
  29102. }
  29103. onError();
  29104. });
  29105. };
  29106. return BinaryFileAssetTask;
  29107. })();
  29108. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29109. var ImageAssetTask = (function () {
  29110. function ImageAssetTask(name, url) {
  29111. this.name = name;
  29112. this.url = url;
  29113. this.isCompleted = false;
  29114. }
  29115. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29116. var _this = this;
  29117. var img = new Image();
  29118. img.onload = function () {
  29119. _this.image = img;
  29120. _this.isCompleted = true;
  29121. if (_this.onSuccess) {
  29122. _this.onSuccess(_this);
  29123. }
  29124. onSuccess();
  29125. };
  29126. img.onerror = function () {
  29127. if (_this.onError) {
  29128. _this.onError(_this);
  29129. }
  29130. onError();
  29131. };
  29132. img.src = this.url;
  29133. };
  29134. return ImageAssetTask;
  29135. })();
  29136. BABYLON.ImageAssetTask = ImageAssetTask;
  29137. var TextureAssetTask = (function () {
  29138. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29139. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29140. this.name = name;
  29141. this.url = url;
  29142. this.noMipmap = noMipmap;
  29143. this.invertY = invertY;
  29144. this.samplingMode = samplingMode;
  29145. this.isCompleted = false;
  29146. }
  29147. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29148. var _this = this;
  29149. var onload = function () {
  29150. _this.isCompleted = true;
  29151. if (_this.onSuccess) {
  29152. _this.onSuccess(_this);
  29153. }
  29154. onSuccess();
  29155. };
  29156. var onerror = function () {
  29157. if (_this.onError) {
  29158. _this.onError(_this);
  29159. }
  29160. onError();
  29161. };
  29162. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29163. };
  29164. return TextureAssetTask;
  29165. })();
  29166. BABYLON.TextureAssetTask = TextureAssetTask;
  29167. var AssetsManager = (function () {
  29168. function AssetsManager(scene) {
  29169. this._tasks = new Array();
  29170. this._waitingTasksCount = 0;
  29171. this.useDefaultLoadingScreen = true;
  29172. this._scene = scene;
  29173. }
  29174. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29175. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29176. this._tasks.push(task);
  29177. return task;
  29178. };
  29179. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29180. var task = new TextFileAssetTask(taskName, url);
  29181. this._tasks.push(task);
  29182. return task;
  29183. };
  29184. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29185. var task = new BinaryFileAssetTask(taskName, url);
  29186. this._tasks.push(task);
  29187. return task;
  29188. };
  29189. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29190. var task = new ImageAssetTask(taskName, url);
  29191. this._tasks.push(task);
  29192. return task;
  29193. };
  29194. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29195. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29196. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29197. this._tasks.push(task);
  29198. return task;
  29199. };
  29200. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29201. this._waitingTasksCount--;
  29202. if (this._waitingTasksCount === 0) {
  29203. if (this.onFinish) {
  29204. this.onFinish(this._tasks);
  29205. }
  29206. this._scene.getEngine().hideLoadingUI();
  29207. }
  29208. };
  29209. AssetsManager.prototype._runTask = function (task) {
  29210. var _this = this;
  29211. task.run(this._scene, function () {
  29212. if (_this.onTaskSuccess) {
  29213. _this.onTaskSuccess(task);
  29214. }
  29215. _this._decreaseWaitingTasksCount();
  29216. }, function () {
  29217. if (_this.onTaskError) {
  29218. _this.onTaskError(task);
  29219. }
  29220. _this._decreaseWaitingTasksCount();
  29221. });
  29222. };
  29223. AssetsManager.prototype.reset = function () {
  29224. this._tasks = new Array();
  29225. return this;
  29226. };
  29227. AssetsManager.prototype.load = function () {
  29228. this._waitingTasksCount = this._tasks.length;
  29229. if (this._waitingTasksCount === 0) {
  29230. if (this.onFinish) {
  29231. this.onFinish(this._tasks);
  29232. }
  29233. return this;
  29234. }
  29235. if (this.useDefaultLoadingScreen) {
  29236. this._scene.getEngine().displayLoadingUI();
  29237. }
  29238. for (var index = 0; index < this._tasks.length; index++) {
  29239. var task = this._tasks[index];
  29240. this._runTask(task);
  29241. }
  29242. return this;
  29243. };
  29244. return AssetsManager;
  29245. })();
  29246. BABYLON.AssetsManager = AssetsManager;
  29247. })(BABYLON || (BABYLON = {}));
  29248. var BABYLON;
  29249. (function (BABYLON) {
  29250. var VRDeviceOrientationFreeCamera = (function (_super) {
  29251. __extends(VRDeviceOrientationFreeCamera, _super);
  29252. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  29253. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29254. _super.call(this, name, position, scene);
  29255. this._alpha = 0;
  29256. this._beta = 0;
  29257. this._gamma = 0;
  29258. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29259. metrics.compensateDistorsion = compensateDistorsion;
  29260. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29261. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  29262. }
  29263. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  29264. this._alpha = +evt.alpha | 0;
  29265. this._beta = +evt.beta | 0;
  29266. this._gamma = +evt.gamma | 0;
  29267. if (this._gamma < 0) {
  29268. this._gamma = 90 + this._gamma;
  29269. }
  29270. else {
  29271. // Incline it in the correct angle.
  29272. this._gamma = 270 - this._gamma;
  29273. }
  29274. this.rotation.x = this._gamma / 180.0 * Math.PI;
  29275. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  29276. this.rotation.z = this._beta / 180.0 * Math.PI;
  29277. };
  29278. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29279. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29280. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  29281. };
  29282. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  29283. _super.prototype.detachControl.call(this, element);
  29284. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  29285. };
  29286. return VRDeviceOrientationFreeCamera;
  29287. })(BABYLON.FreeCamera);
  29288. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  29289. })(BABYLON || (BABYLON = {}));
  29290. var BABYLON;
  29291. (function (BABYLON) {
  29292. var WebVRFreeCamera = (function (_super) {
  29293. __extends(WebVRFreeCamera, _super);
  29294. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  29295. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29296. _super.call(this, name, position, scene);
  29297. this._hmdDevice = null;
  29298. this._sensorDevice = null;
  29299. this._cacheState = null;
  29300. this._cacheQuaternion = new BABYLON.Quaternion();
  29301. this._cacheRotation = BABYLON.Vector3.Zero();
  29302. this._vrEnabled = false;
  29303. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29304. metrics.compensateDistorsion = compensateDistorsion;
  29305. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29306. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  29307. }
  29308. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  29309. var size = devices.length;
  29310. var i = 0;
  29311. // Reset devices.
  29312. this._sensorDevice = null;
  29313. this._hmdDevice = null;
  29314. // Search for a HmdDevice.
  29315. while (i < size && this._hmdDevice === null) {
  29316. if (devices[i] instanceof HMDVRDevice) {
  29317. this._hmdDevice = devices[i];
  29318. }
  29319. i++;
  29320. }
  29321. i = 0;
  29322. while (i < size && this._sensorDevice === null) {
  29323. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  29324. this._sensorDevice = devices[i];
  29325. }
  29326. i++;
  29327. }
  29328. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  29329. };
  29330. WebVRFreeCamera.prototype._checkInputs = function () {
  29331. if (this._vrEnabled) {
  29332. this._cacheState = this._sensorDevice.getState();
  29333. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  29334. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  29335. this.rotation.x = -this._cacheRotation.z;
  29336. this.rotation.y = -this._cacheRotation.y;
  29337. this.rotation.z = this._cacheRotation.x;
  29338. }
  29339. _super.prototype._checkInputs.call(this);
  29340. };
  29341. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29342. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29343. if (navigator.getVRDevices) {
  29344. navigator.getVRDevices().then(this._getWebVRDevices);
  29345. }
  29346. else if (navigator.mozGetVRDevices) {
  29347. navigator.mozGetVRDevices(this._getWebVRDevices);
  29348. }
  29349. };
  29350. WebVRFreeCamera.prototype.detachControl = function (element) {
  29351. _super.prototype.detachControl.call(this, element);
  29352. this._vrEnabled = false;
  29353. };
  29354. return WebVRFreeCamera;
  29355. })(BABYLON.FreeCamera);
  29356. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  29357. })(BABYLON || (BABYLON = {}));
  29358. var BABYLON;
  29359. (function (BABYLON) {
  29360. // Standard optimizations
  29361. var SceneOptimization = (function () {
  29362. function SceneOptimization(priority) {
  29363. if (priority === void 0) { priority = 0; }
  29364. this.priority = priority;
  29365. this.apply = function (scene) {
  29366. return true; // Return true if everything that can be done was applied
  29367. };
  29368. }
  29369. return SceneOptimization;
  29370. })();
  29371. BABYLON.SceneOptimization = SceneOptimization;
  29372. var TextureOptimization = (function (_super) {
  29373. __extends(TextureOptimization, _super);
  29374. function TextureOptimization(priority, maximumSize) {
  29375. var _this = this;
  29376. if (priority === void 0) { priority = 0; }
  29377. if (maximumSize === void 0) { maximumSize = 1024; }
  29378. _super.call(this, priority);
  29379. this.priority = priority;
  29380. this.maximumSize = maximumSize;
  29381. this.apply = function (scene) {
  29382. var allDone = true;
  29383. for (var index = 0; index < scene.textures.length; index++) {
  29384. var texture = scene.textures[index];
  29385. if (!texture.canRescale) {
  29386. continue;
  29387. }
  29388. var currentSize = texture.getSize();
  29389. var maxDimension = Math.max(currentSize.width, currentSize.height);
  29390. if (maxDimension > _this.maximumSize) {
  29391. texture.scale(0.5);
  29392. allDone = false;
  29393. }
  29394. }
  29395. return allDone;
  29396. };
  29397. }
  29398. return TextureOptimization;
  29399. })(SceneOptimization);
  29400. BABYLON.TextureOptimization = TextureOptimization;
  29401. var HardwareScalingOptimization = (function (_super) {
  29402. __extends(HardwareScalingOptimization, _super);
  29403. function HardwareScalingOptimization(priority, maximumScale) {
  29404. var _this = this;
  29405. if (priority === void 0) { priority = 0; }
  29406. if (maximumScale === void 0) { maximumScale = 2; }
  29407. _super.call(this, priority);
  29408. this.priority = priority;
  29409. this.maximumScale = maximumScale;
  29410. this._currentScale = 1;
  29411. this.apply = function (scene) {
  29412. _this._currentScale++;
  29413. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  29414. return _this._currentScale >= _this.maximumScale;
  29415. };
  29416. }
  29417. return HardwareScalingOptimization;
  29418. })(SceneOptimization);
  29419. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  29420. var ShadowsOptimization = (function (_super) {
  29421. __extends(ShadowsOptimization, _super);
  29422. function ShadowsOptimization() {
  29423. _super.apply(this, arguments);
  29424. this.apply = function (scene) {
  29425. scene.shadowsEnabled = false;
  29426. return true;
  29427. };
  29428. }
  29429. return ShadowsOptimization;
  29430. })(SceneOptimization);
  29431. BABYLON.ShadowsOptimization = ShadowsOptimization;
  29432. var PostProcessesOptimization = (function (_super) {
  29433. __extends(PostProcessesOptimization, _super);
  29434. function PostProcessesOptimization() {
  29435. _super.apply(this, arguments);
  29436. this.apply = function (scene) {
  29437. scene.postProcessesEnabled = false;
  29438. return true;
  29439. };
  29440. }
  29441. return PostProcessesOptimization;
  29442. })(SceneOptimization);
  29443. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  29444. var LensFlaresOptimization = (function (_super) {
  29445. __extends(LensFlaresOptimization, _super);
  29446. function LensFlaresOptimization() {
  29447. _super.apply(this, arguments);
  29448. this.apply = function (scene) {
  29449. scene.lensFlaresEnabled = false;
  29450. return true;
  29451. };
  29452. }
  29453. return LensFlaresOptimization;
  29454. })(SceneOptimization);
  29455. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  29456. var ParticlesOptimization = (function (_super) {
  29457. __extends(ParticlesOptimization, _super);
  29458. function ParticlesOptimization() {
  29459. _super.apply(this, arguments);
  29460. this.apply = function (scene) {
  29461. scene.particlesEnabled = false;
  29462. return true;
  29463. };
  29464. }
  29465. return ParticlesOptimization;
  29466. })(SceneOptimization);
  29467. BABYLON.ParticlesOptimization = ParticlesOptimization;
  29468. var RenderTargetsOptimization = (function (_super) {
  29469. __extends(RenderTargetsOptimization, _super);
  29470. function RenderTargetsOptimization() {
  29471. _super.apply(this, arguments);
  29472. this.apply = function (scene) {
  29473. scene.renderTargetsEnabled = false;
  29474. return true;
  29475. };
  29476. }
  29477. return RenderTargetsOptimization;
  29478. })(SceneOptimization);
  29479. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  29480. var MergeMeshesOptimization = (function (_super) {
  29481. __extends(MergeMeshesOptimization, _super);
  29482. function MergeMeshesOptimization() {
  29483. var _this = this;
  29484. _super.apply(this, arguments);
  29485. this._canBeMerged = function (abstractMesh) {
  29486. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  29487. return false;
  29488. }
  29489. var mesh = abstractMesh;
  29490. if (!mesh.isVisible || !mesh.isEnabled()) {
  29491. return false;
  29492. }
  29493. if (mesh.instances.length > 0) {
  29494. return false;
  29495. }
  29496. if (mesh.skeleton || mesh.hasLODLevels) {
  29497. return false;
  29498. }
  29499. return true;
  29500. };
  29501. this.apply = function (scene, updateSelectionTree) {
  29502. var globalPool = scene.meshes.slice(0);
  29503. var globalLength = globalPool.length;
  29504. for (var index = 0; index < globalLength; index++) {
  29505. var currentPool = new Array();
  29506. var current = globalPool[index];
  29507. // Checks
  29508. if (!_this._canBeMerged(current)) {
  29509. continue;
  29510. }
  29511. currentPool.push(current);
  29512. // Find compatible meshes
  29513. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  29514. var otherMesh = globalPool[subIndex];
  29515. if (!_this._canBeMerged(otherMesh)) {
  29516. continue;
  29517. }
  29518. if (otherMesh.material !== current.material) {
  29519. continue;
  29520. }
  29521. if (otherMesh.checkCollisions !== current.checkCollisions) {
  29522. continue;
  29523. }
  29524. currentPool.push(otherMesh);
  29525. globalLength--;
  29526. globalPool.splice(subIndex, 1);
  29527. subIndex--;
  29528. }
  29529. if (currentPool.length < 2) {
  29530. continue;
  29531. }
  29532. // Merge meshes
  29533. BABYLON.Mesh.MergeMeshes(currentPool);
  29534. }
  29535. if (updateSelectionTree != undefined) {
  29536. if (updateSelectionTree) {
  29537. scene.createOrUpdateSelectionOctree();
  29538. }
  29539. }
  29540. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  29541. scene.createOrUpdateSelectionOctree();
  29542. }
  29543. return true;
  29544. };
  29545. }
  29546. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  29547. get: function () {
  29548. return MergeMeshesOptimization._UpdateSelectionTree;
  29549. },
  29550. set: function (value) {
  29551. MergeMeshesOptimization._UpdateSelectionTree = value;
  29552. },
  29553. enumerable: true,
  29554. configurable: true
  29555. });
  29556. MergeMeshesOptimization._UpdateSelectionTree = false;
  29557. return MergeMeshesOptimization;
  29558. })(SceneOptimization);
  29559. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  29560. // Options
  29561. var SceneOptimizerOptions = (function () {
  29562. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  29563. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  29564. if (trackerDuration === void 0) { trackerDuration = 2000; }
  29565. this.targetFrameRate = targetFrameRate;
  29566. this.trackerDuration = trackerDuration;
  29567. this.optimizations = new Array();
  29568. }
  29569. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  29570. var result = new SceneOptimizerOptions(targetFrameRate);
  29571. var priority = 0;
  29572. result.optimizations.push(new MergeMeshesOptimization(priority));
  29573. result.optimizations.push(new ShadowsOptimization(priority));
  29574. result.optimizations.push(new LensFlaresOptimization(priority));
  29575. // Next priority
  29576. priority++;
  29577. result.optimizations.push(new PostProcessesOptimization(priority));
  29578. result.optimizations.push(new ParticlesOptimization(priority));
  29579. // Next priority
  29580. priority++;
  29581. result.optimizations.push(new TextureOptimization(priority, 1024));
  29582. return result;
  29583. };
  29584. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  29585. var result = new SceneOptimizerOptions(targetFrameRate);
  29586. var priority = 0;
  29587. result.optimizations.push(new MergeMeshesOptimization(priority));
  29588. result.optimizations.push(new ShadowsOptimization(priority));
  29589. result.optimizations.push(new LensFlaresOptimization(priority));
  29590. // Next priority
  29591. priority++;
  29592. result.optimizations.push(new PostProcessesOptimization(priority));
  29593. result.optimizations.push(new ParticlesOptimization(priority));
  29594. // Next priority
  29595. priority++;
  29596. result.optimizations.push(new TextureOptimization(priority, 512));
  29597. // Next priority
  29598. priority++;
  29599. result.optimizations.push(new RenderTargetsOptimization(priority));
  29600. // Next priority
  29601. priority++;
  29602. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  29603. return result;
  29604. };
  29605. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  29606. var result = new SceneOptimizerOptions(targetFrameRate);
  29607. var priority = 0;
  29608. result.optimizations.push(new MergeMeshesOptimization(priority));
  29609. result.optimizations.push(new ShadowsOptimization(priority));
  29610. result.optimizations.push(new LensFlaresOptimization(priority));
  29611. // Next priority
  29612. priority++;
  29613. result.optimizations.push(new PostProcessesOptimization(priority));
  29614. result.optimizations.push(new ParticlesOptimization(priority));
  29615. // Next priority
  29616. priority++;
  29617. result.optimizations.push(new TextureOptimization(priority, 256));
  29618. // Next priority
  29619. priority++;
  29620. result.optimizations.push(new RenderTargetsOptimization(priority));
  29621. // Next priority
  29622. priority++;
  29623. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  29624. return result;
  29625. };
  29626. return SceneOptimizerOptions;
  29627. })();
  29628. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  29629. // Scene optimizer tool
  29630. var SceneOptimizer = (function () {
  29631. function SceneOptimizer() {
  29632. }
  29633. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  29634. // TODO: add an epsilon
  29635. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  29636. if (onSuccess) {
  29637. onSuccess();
  29638. }
  29639. return;
  29640. }
  29641. // Apply current level of optimizations
  29642. var allDone = true;
  29643. var noOptimizationApplied = true;
  29644. for (var index = 0; index < options.optimizations.length; index++) {
  29645. var optimization = options.optimizations[index];
  29646. if (optimization.priority === currentPriorityLevel) {
  29647. noOptimizationApplied = false;
  29648. allDone = allDone && optimization.apply(scene);
  29649. }
  29650. }
  29651. // If no optimization was applied, this is a failure :(
  29652. if (noOptimizationApplied) {
  29653. if (onFailure) {
  29654. onFailure();
  29655. }
  29656. return;
  29657. }
  29658. // If all optimizations were done, move to next level
  29659. if (allDone) {
  29660. currentPriorityLevel++;
  29661. }
  29662. // Let's the system running for a specific amount of time before checking FPS
  29663. scene.executeWhenReady(function () {
  29664. setTimeout(function () {
  29665. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  29666. }, options.trackerDuration);
  29667. });
  29668. };
  29669. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  29670. if (!options) {
  29671. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  29672. }
  29673. // Let's the system running for a specific amount of time before checking FPS
  29674. scene.executeWhenReady(function () {
  29675. setTimeout(function () {
  29676. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  29677. }, options.trackerDuration);
  29678. });
  29679. };
  29680. return SceneOptimizer;
  29681. })();
  29682. BABYLON.SceneOptimizer = SceneOptimizer;
  29683. })(BABYLON || (BABYLON = {}));
  29684. var BABYLON;
  29685. (function (BABYLON) {
  29686. var Internals;
  29687. (function (Internals) {
  29688. var MeshLODLevel = (function () {
  29689. function MeshLODLevel(distance, mesh) {
  29690. this.distance = distance;
  29691. this.mesh = mesh;
  29692. }
  29693. return MeshLODLevel;
  29694. })();
  29695. Internals.MeshLODLevel = MeshLODLevel;
  29696. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29697. })(BABYLON || (BABYLON = {}));
  29698. var BABYLON;
  29699. (function (BABYLON) {
  29700. var AudioEngine = (function () {
  29701. function AudioEngine() {
  29702. this._audioContext = null;
  29703. this._audioContextInitialized = false;
  29704. this.canUseWebAudio = false;
  29705. this.WarnedWebAudioUnsupported = false;
  29706. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  29707. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  29708. this.canUseWebAudio = true;
  29709. }
  29710. }
  29711. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  29712. get: function () {
  29713. if (!this._audioContextInitialized) {
  29714. this._initializeAudioContext();
  29715. }
  29716. return this._audioContext;
  29717. },
  29718. enumerable: true,
  29719. configurable: true
  29720. });
  29721. AudioEngine.prototype._initializeAudioContext = function () {
  29722. try {
  29723. if (this.canUseWebAudio) {
  29724. this._audioContext = new AudioContext();
  29725. // create a global volume gain node
  29726. this.masterGain = this._audioContext.createGain();
  29727. this.masterGain.gain.value = 1;
  29728. this.masterGain.connect(this._audioContext.destination);
  29729. this._audioContextInitialized = true;
  29730. }
  29731. }
  29732. catch (e) {
  29733. this.canUseWebAudio = false;
  29734. BABYLON.Tools.Error("Web Audio: " + e.message);
  29735. }
  29736. };
  29737. AudioEngine.prototype.dispose = function () {
  29738. if (this.canUseWebAudio && this._audioContextInitialized) {
  29739. if (this._connectedAnalyser) {
  29740. this._connectedAnalyser.stopDebugCanvas();
  29741. this._connectedAnalyser.dispose();
  29742. this.masterGain.disconnect();
  29743. this.masterGain.connect(this._audioContext.destination);
  29744. this._connectedAnalyser = null;
  29745. }
  29746. this.masterGain.gain.value = 1;
  29747. }
  29748. this.WarnedWebAudioUnsupported = false;
  29749. };
  29750. AudioEngine.prototype.getGlobalVolume = function () {
  29751. if (this.canUseWebAudio && this._audioContextInitialized) {
  29752. return this.masterGain.gain.value;
  29753. }
  29754. else {
  29755. return -1;
  29756. }
  29757. };
  29758. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  29759. if (this.canUseWebAudio && this._audioContextInitialized) {
  29760. this.masterGain.gain.value = newVolume;
  29761. }
  29762. };
  29763. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  29764. if (this._connectedAnalyser) {
  29765. this._connectedAnalyser.stopDebugCanvas();
  29766. }
  29767. if (this.canUseWebAudio && this._audioContextInitialized) {
  29768. this._connectedAnalyser = analyser;
  29769. this.masterGain.disconnect();
  29770. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  29771. }
  29772. };
  29773. return AudioEngine;
  29774. })();
  29775. BABYLON.AudioEngine = AudioEngine;
  29776. })(BABYLON || (BABYLON = {}));
  29777. var BABYLON;
  29778. (function (BABYLON) {
  29779. var Sound = (function () {
  29780. /**
  29781. * Create a sound and attach it to a scene
  29782. * @param name Name of your sound
  29783. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  29784. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  29785. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  29786. */
  29787. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  29788. var _this = this;
  29789. this.autoplay = false;
  29790. this.loop = false;
  29791. this.useCustomAttenuation = false;
  29792. this.spatialSound = false;
  29793. this.refDistance = 1;
  29794. this.rolloffFactor = 1;
  29795. this.maxDistance = 100;
  29796. this.distanceModel = "linear";
  29797. this._panningModel = "equalpower";
  29798. this._playbackRate = 1;
  29799. this._startTime = 0;
  29800. this._startOffset = 0;
  29801. this._position = BABYLON.Vector3.Zero();
  29802. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  29803. this._volume = 1;
  29804. this._isLoaded = false;
  29805. this._isReadyToPlay = false;
  29806. this.isPlaying = false;
  29807. this.isPaused = false;
  29808. this._isDirectional = false;
  29809. // Used if you'd like to create a directional sound.
  29810. // If not set, the sound will be omnidirectional
  29811. this._coneInnerAngle = 360;
  29812. this._coneOuterAngle = 360;
  29813. this._coneOuterGain = 0;
  29814. this.name = name;
  29815. this._scene = scene;
  29816. this._readyToPlayCallback = readyToPlayCallback;
  29817. // Default custom attenuation function is a linear attenuation
  29818. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  29819. if (currentDistance < maxDistance) {
  29820. return currentVolume * (1 - currentDistance / maxDistance);
  29821. }
  29822. else {
  29823. return 0;
  29824. }
  29825. };
  29826. if (options) {
  29827. this.autoplay = options.autoplay || false;
  29828. this.loop = options.loop || false;
  29829. // if volume === 0, we need another way to check this option
  29830. if (options.volume !== undefined) {
  29831. this._volume = options.volume;
  29832. }
  29833. this.spatialSound = options.spatialSound || false;
  29834. this.maxDistance = options.maxDistance || 100;
  29835. this.useCustomAttenuation = options.useCustomAttenuation || false;
  29836. this.rolloffFactor = options.rolloffFactor || 1;
  29837. this.refDistance = options.refDistance || 1;
  29838. this.distanceModel = options.distanceModel || "linear";
  29839. this._playbackRate = options.playbackRate || 1;
  29840. }
  29841. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29842. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  29843. this._soundGain.gain.value = this._volume;
  29844. this._inputAudioNode = this._soundGain;
  29845. this._ouputAudioNode = this._soundGain;
  29846. if (this.spatialSound) {
  29847. this._createSpatialParameters();
  29848. }
  29849. this._scene.mainSoundTrack.AddSound(this);
  29850. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29851. if (urlOrArrayBuffer) {
  29852. // If it's an URL
  29853. if (typeof (urlOrArrayBuffer) === "string") {
  29854. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  29855. }
  29856. else {
  29857. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29858. this._soundLoaded(urlOrArrayBuffer);
  29859. }
  29860. else {
  29861. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29862. }
  29863. }
  29864. }
  29865. }
  29866. else {
  29867. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29868. this._scene.mainSoundTrack.AddSound(this);
  29869. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29870. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29871. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  29872. }
  29873. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  29874. if (this._readyToPlayCallback) {
  29875. window.setTimeout(function () {
  29876. _this._readyToPlayCallback();
  29877. }, 1000);
  29878. }
  29879. }
  29880. }
  29881. Sound.prototype.dispose = function () {
  29882. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  29883. if (this.isPlaying) {
  29884. this.stop();
  29885. }
  29886. this._isReadyToPlay = false;
  29887. if (this.soundTrackId === -1) {
  29888. this._scene.mainSoundTrack.RemoveSound(this);
  29889. }
  29890. else {
  29891. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  29892. }
  29893. if (this._soundGain) {
  29894. this._soundGain.disconnect();
  29895. this._soundGain = null;
  29896. }
  29897. if (this._soundPanner) {
  29898. this._soundPanner.disconnect();
  29899. this._soundPanner = null;
  29900. }
  29901. if (this._soundSource) {
  29902. this._soundSource.disconnect();
  29903. this._soundSource = null;
  29904. }
  29905. this._audioBuffer = null;
  29906. if (this._connectedMesh) {
  29907. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29908. this._connectedMesh = null;
  29909. }
  29910. }
  29911. };
  29912. Sound.prototype._soundLoaded = function (audioData) {
  29913. var _this = this;
  29914. this._isLoaded = true;
  29915. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  29916. _this._audioBuffer = buffer;
  29917. _this._isReadyToPlay = true;
  29918. if (_this.autoplay) {
  29919. _this.play();
  29920. }
  29921. if (_this._readyToPlayCallback) {
  29922. _this._readyToPlayCallback();
  29923. }
  29924. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  29925. };
  29926. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  29927. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29928. this._audioBuffer = audioBuffer;
  29929. this._isReadyToPlay = true;
  29930. }
  29931. };
  29932. Sound.prototype.updateOptions = function (options) {
  29933. if (options) {
  29934. this.loop = options.loop || this.loop;
  29935. this.maxDistance = options.maxDistance || this.maxDistance;
  29936. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  29937. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  29938. this.refDistance = options.refDistance || this.refDistance;
  29939. this.distanceModel = options.distanceModel || this.distanceModel;
  29940. this._playbackRate = options.playbackRate || this._playbackRate;
  29941. this._updateSpatialParameters();
  29942. if (this.isPlaying) {
  29943. this._soundSource.playbackRate.value = this._playbackRate;
  29944. }
  29945. }
  29946. };
  29947. Sound.prototype._createSpatialParameters = function () {
  29948. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29949. if (this._scene.headphone) {
  29950. this._panningModel = "HRTF";
  29951. }
  29952. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  29953. this._updateSpatialParameters();
  29954. this._soundPanner.connect(this._ouputAudioNode);
  29955. this._inputAudioNode = this._soundPanner;
  29956. }
  29957. };
  29958. Sound.prototype._updateSpatialParameters = function () {
  29959. if (this.spatialSound) {
  29960. if (this.useCustomAttenuation) {
  29961. // Tricks to disable in a way embedded Web Audio attenuation
  29962. this._soundPanner.distanceModel = "linear";
  29963. this._soundPanner.maxDistance = Number.MAX_VALUE;
  29964. this._soundPanner.refDistance = 1;
  29965. this._soundPanner.rolloffFactor = 1;
  29966. this._soundPanner.panningModel = this._panningModel;
  29967. }
  29968. else {
  29969. this._soundPanner.distanceModel = this.distanceModel;
  29970. this._soundPanner.maxDistance = this.maxDistance;
  29971. this._soundPanner.refDistance = this.refDistance;
  29972. this._soundPanner.rolloffFactor = this.rolloffFactor;
  29973. this._soundPanner.panningModel = this._panningModel;
  29974. }
  29975. }
  29976. };
  29977. Sound.prototype.switchPanningModelToHRTF = function () {
  29978. this._panningModel = "HRTF";
  29979. this._switchPanningModel();
  29980. };
  29981. Sound.prototype.switchPanningModelToEqualPower = function () {
  29982. this._panningModel = "equalpower";
  29983. this._switchPanningModel();
  29984. };
  29985. Sound.prototype._switchPanningModel = function () {
  29986. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  29987. this._soundPanner.panningModel = this._panningModel;
  29988. }
  29989. };
  29990. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  29991. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29992. this._ouputAudioNode.disconnect();
  29993. this._ouputAudioNode.connect(soundTrackAudioNode);
  29994. }
  29995. };
  29996. /**
  29997. * Transform this sound into a directional source
  29998. * @param coneInnerAngle Size of the inner cone in degree
  29999. * @param coneOuterAngle Size of the outer cone in degree
  30000. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30001. */
  30002. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30003. if (coneOuterAngle < coneInnerAngle) {
  30004. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30005. return;
  30006. }
  30007. this._coneInnerAngle = coneInnerAngle;
  30008. this._coneOuterAngle = coneOuterAngle;
  30009. this._coneOuterGain = coneOuterGain;
  30010. this._isDirectional = true;
  30011. if (this.isPlaying && this.loop) {
  30012. this.stop();
  30013. this.play();
  30014. }
  30015. };
  30016. Sound.prototype.setPosition = function (newPosition) {
  30017. this._position = newPosition;
  30018. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30019. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30020. }
  30021. };
  30022. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30023. this._localDirection = newLocalDirection;
  30024. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30025. this._updateDirection();
  30026. }
  30027. };
  30028. Sound.prototype._updateDirection = function () {
  30029. var mat = this._connectedMesh.getWorldMatrix();
  30030. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30031. direction.normalize();
  30032. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30033. };
  30034. Sound.prototype.updateDistanceFromListener = function () {
  30035. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30036. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30037. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30038. }
  30039. };
  30040. Sound.prototype.setAttenuationFunction = function (callback) {
  30041. this._customAttenuationFunction = callback;
  30042. };
  30043. /**
  30044. * Play the sound
  30045. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30046. */
  30047. Sound.prototype.play = function (time) {
  30048. var _this = this;
  30049. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30050. try {
  30051. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30052. if (!this._soundSource) {
  30053. if (this.spatialSound) {
  30054. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30055. if (this._isDirectional) {
  30056. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30057. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30058. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30059. if (this._connectedMesh) {
  30060. this._updateDirection();
  30061. }
  30062. else {
  30063. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30064. }
  30065. }
  30066. }
  30067. }
  30068. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30069. this._soundSource.buffer = this._audioBuffer;
  30070. this._soundSource.connect(this._inputAudioNode);
  30071. this._soundSource.loop = this.loop;
  30072. this._soundSource.playbackRate.value = this._playbackRate;
  30073. this._startTime = startTime;
  30074. this._soundSource.onended = function () { _this._onended(); };
  30075. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30076. this.isPlaying = true;
  30077. this.isPaused = false;
  30078. }
  30079. catch (ex) {
  30080. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30081. }
  30082. }
  30083. };
  30084. Sound.prototype._onended = function () {
  30085. this.isPlaying = false;
  30086. if (this.onended) {
  30087. this.onended();
  30088. }
  30089. };
  30090. /**
  30091. * Stop the sound
  30092. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30093. */
  30094. Sound.prototype.stop = function (time) {
  30095. if (this.isPlaying) {
  30096. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30097. this._soundSource.stop(stopTime);
  30098. this.isPlaying = false;
  30099. }
  30100. };
  30101. Sound.prototype.pause = function () {
  30102. if (this.isPlaying) {
  30103. this.stop(0);
  30104. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30105. this.isPaused = true;
  30106. }
  30107. };
  30108. Sound.prototype.setVolume = function (newVolume, time) {
  30109. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30110. if (time) {
  30111. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30112. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30113. }
  30114. else {
  30115. this._soundGain.gain.value = newVolume;
  30116. }
  30117. }
  30118. this._volume = newVolume;
  30119. };
  30120. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30121. this._playbackRate = newPlaybackRate;
  30122. if (this.isPlaying) {
  30123. this._soundSource.playbackRate.value = this._playbackRate;
  30124. }
  30125. };
  30126. Sound.prototype.getVolume = function () {
  30127. return this._volume;
  30128. };
  30129. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30130. var _this = this;
  30131. this._connectedMesh = meshToConnectTo;
  30132. if (!this.spatialSound) {
  30133. this.spatialSound = true;
  30134. this._createSpatialParameters();
  30135. if (this.isPlaying && this.loop) {
  30136. this.stop();
  30137. this.play();
  30138. }
  30139. }
  30140. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30141. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30142. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30143. };
  30144. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30145. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30146. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30147. this._updateDirection();
  30148. }
  30149. };
  30150. return Sound;
  30151. })();
  30152. BABYLON.Sound = Sound;
  30153. })(BABYLON || (BABYLON = {}));
  30154. var BABYLON;
  30155. (function (BABYLON) {
  30156. var SoundTrack = (function () {
  30157. function SoundTrack(scene, options) {
  30158. this.id = -1;
  30159. this._isMainTrack = false;
  30160. this._scene = scene;
  30161. this._audioEngine = BABYLON.Engine.audioEngine;
  30162. this.soundCollection = new Array();
  30163. if (this._audioEngine.canUseWebAudio) {
  30164. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30165. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30166. if (options) {
  30167. if (options.volume) {
  30168. this._outputAudioNode.gain.value = options.volume;
  30169. }
  30170. if (options.mainTrack) {
  30171. this._isMainTrack = options.mainTrack;
  30172. }
  30173. }
  30174. }
  30175. if (!this._isMainTrack) {
  30176. this._scene.soundTracks.push(this);
  30177. this.id = this._scene.soundTracks.length - 1;
  30178. }
  30179. }
  30180. SoundTrack.prototype.dispose = function () {
  30181. if (this._audioEngine.canUseWebAudio) {
  30182. if (this._connectedAnalyser) {
  30183. this._connectedAnalyser.stopDebugCanvas();
  30184. }
  30185. while (this.soundCollection.length) {
  30186. this.soundCollection[0].dispose();
  30187. }
  30188. if (this._outputAudioNode) {
  30189. this._outputAudioNode.disconnect();
  30190. }
  30191. this._outputAudioNode = null;
  30192. }
  30193. };
  30194. SoundTrack.prototype.AddSound = function (sound) {
  30195. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30196. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30197. }
  30198. if (sound.soundTrackId) {
  30199. if (sound.soundTrackId === -1) {
  30200. this._scene.mainSoundTrack.RemoveSound(sound);
  30201. }
  30202. else {
  30203. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30204. }
  30205. }
  30206. this.soundCollection.push(sound);
  30207. sound.soundTrackId = this.id;
  30208. };
  30209. SoundTrack.prototype.RemoveSound = function (sound) {
  30210. var index = this.soundCollection.indexOf(sound);
  30211. if (index !== -1) {
  30212. this.soundCollection.splice(index, 1);
  30213. }
  30214. };
  30215. SoundTrack.prototype.setVolume = function (newVolume) {
  30216. if (this._audioEngine.canUseWebAudio) {
  30217. this._outputAudioNode.gain.value = newVolume;
  30218. }
  30219. };
  30220. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30221. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30222. for (var i = 0; i < this.soundCollection.length; i++) {
  30223. this.soundCollection[i].switchPanningModelToHRTF();
  30224. }
  30225. }
  30226. };
  30227. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30228. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30229. for (var i = 0; i < this.soundCollection.length; i++) {
  30230. this.soundCollection[i].switchPanningModelToEqualPower();
  30231. }
  30232. }
  30233. };
  30234. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30235. if (this._connectedAnalyser) {
  30236. this._connectedAnalyser.stopDebugCanvas();
  30237. }
  30238. this._connectedAnalyser = analyser;
  30239. if (this._audioEngine.canUseWebAudio) {
  30240. this._outputAudioNode.disconnect();
  30241. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  30242. }
  30243. };
  30244. return SoundTrack;
  30245. })();
  30246. BABYLON.SoundTrack = SoundTrack;
  30247. })(BABYLON || (BABYLON = {}));
  30248. var BABYLON;
  30249. (function (BABYLON) {
  30250. var DebugLayer = (function () {
  30251. function DebugLayer(scene) {
  30252. var _this = this;
  30253. this._transformationMatrix = BABYLON.Matrix.Identity();
  30254. this._enabled = false;
  30255. this._labelsEnabled = false;
  30256. this._displayStatistics = true;
  30257. this._displayTree = false;
  30258. this._displayLogs = false;
  30259. this._identityMatrix = BABYLON.Matrix.Identity();
  30260. this.axisRatio = 0.02;
  30261. this.accentColor = "orange";
  30262. this._scene = scene;
  30263. this._syncPositions = function () {
  30264. var engine = _this._scene.getEngine();
  30265. var canvasRect = engine.getRenderingCanvasClientRect();
  30266. if (_this._showUI) {
  30267. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30268. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30269. _this._statsDiv.style.width = "400px";
  30270. _this._statsDiv.style.height = "auto";
  30271. _this._statsSubsetDiv.style.maxHeight = "240px";
  30272. _this._optionsDiv.style.left = "0px";
  30273. _this._optionsDiv.style.top = "10px";
  30274. _this._optionsDiv.style.width = "200px";
  30275. _this._optionsDiv.style.height = "auto";
  30276. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30277. _this._logDiv.style.left = "0px";
  30278. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30279. _this._logDiv.style.width = "600px";
  30280. _this._logDiv.style.height = "160px";
  30281. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30282. _this._treeDiv.style.top = "10px";
  30283. _this._treeDiv.style.width = "300px";
  30284. _this._treeDiv.style.height = "auto";
  30285. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30286. }
  30287. _this._globalDiv.style.left = canvasRect.left + "px";
  30288. _this._globalDiv.style.top = canvasRect.top + "px";
  30289. _this._drawingCanvas.style.left = "0px";
  30290. _this._drawingCanvas.style.top = "0px";
  30291. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30292. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30293. var devicePixelRatio = window.devicePixelRatio || 1;
  30294. var context = _this._drawingContext;
  30295. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30296. context.mozBackingStorePixelRatio ||
  30297. context.msBackingStorePixelRatio ||
  30298. context.oBackingStorePixelRatio ||
  30299. context.backingStorePixelRatio || 1;
  30300. _this._ratio = devicePixelRatio / backingStoreRatio;
  30301. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30302. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30303. };
  30304. this._onCanvasClick = function (evt) {
  30305. _this._clickPosition = {
  30306. x: evt.clientX * _this._ratio,
  30307. y: evt.clientY * _this._ratio
  30308. };
  30309. };
  30310. this._syncUI = function () {
  30311. if (_this._showUI) {
  30312. if (_this._displayStatistics) {
  30313. _this._displayStats();
  30314. _this._statsDiv.style.display = "";
  30315. }
  30316. else {
  30317. _this._statsDiv.style.display = "none";
  30318. }
  30319. if (_this._displayLogs) {
  30320. _this._logDiv.style.display = "";
  30321. }
  30322. else {
  30323. _this._logDiv.style.display = "none";
  30324. }
  30325. if (_this._displayTree) {
  30326. _this._treeDiv.style.display = "";
  30327. if (_this._needToRefreshMeshesTree) {
  30328. _this._needToRefreshMeshesTree = false;
  30329. _this._refreshMeshesTreeContent();
  30330. }
  30331. }
  30332. else {
  30333. _this._treeDiv.style.display = "none";
  30334. }
  30335. }
  30336. };
  30337. this._syncData = function () {
  30338. if (_this._labelsEnabled || !_this._showUI) {
  30339. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30340. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30341. var engine = _this._scene.getEngine();
  30342. var viewport = _this._camera.viewport;
  30343. var globalViewport = viewport.toGlobal(engine);
  30344. // Meshes
  30345. var meshes = _this._camera.getActiveMeshes();
  30346. for (var index = 0; index < meshes.length; index++) {
  30347. var mesh = meshes.data[index];
  30348. var position = mesh.getBoundingInfo().boundingSphere.center;
  30349. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30350. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30351. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30352. }
  30353. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30354. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30355. }
  30356. }
  30357. // Cameras
  30358. var cameras = _this._scene.cameras;
  30359. for (index = 0; index < cameras.length; index++) {
  30360. var camera = cameras[index];
  30361. if (camera === _this._camera) {
  30362. continue;
  30363. }
  30364. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30365. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30366. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30367. _this._camera.detachControl(engine.getRenderingCanvas());
  30368. _this._camera = camera;
  30369. _this._camera.attachControl(engine.getRenderingCanvas());
  30370. }, function () { return "purple"; });
  30371. }
  30372. }
  30373. // Lights
  30374. var lights = _this._scene.lights;
  30375. for (index = 0; index < lights.length; index++) {
  30376. var light = lights[index];
  30377. if (light.position) {
  30378. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30379. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30380. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30381. light.setEnabled(!light.isEnabled());
  30382. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30383. }
  30384. }
  30385. }
  30386. }
  30387. _this._clickPosition = undefined;
  30388. };
  30389. }
  30390. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30391. while (this._treeSubsetDiv.hasChildNodes()) {
  30392. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30393. }
  30394. // Add meshes
  30395. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30396. sortedArray.sort(function (a, b) {
  30397. if (a.name === b.name) {
  30398. return 0;
  30399. }
  30400. return (a.name > b.name) ? 1 : -1;
  30401. });
  30402. for (var index = 0; index < sortedArray.length; index++) {
  30403. var mesh = sortedArray[index];
  30404. if (!mesh.isEnabled()) {
  30405. continue;
  30406. }
  30407. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30408. m.isVisible = element.checked;
  30409. }, mesh);
  30410. }
  30411. };
  30412. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30413. this._drawingContext.beginPath();
  30414. this._drawingContext.moveTo(zero.x, zero.y);
  30415. this._drawingContext.lineTo(unit.x, unit.y);
  30416. this._drawingContext.strokeStyle = color;
  30417. this._drawingContext.lineWidth = 4;
  30418. this._drawingContext.stroke();
  30419. this._drawingContext.font = "normal 14px Segoe UI";
  30420. this._drawingContext.fillStyle = color;
  30421. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30422. };
  30423. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30424. var position = mesh.getBoundingInfo().boundingSphere.center;
  30425. var worldMatrix = mesh.getWorldMatrix();
  30426. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30427. var unit = (unprojectedVector.subtract(position)).length();
  30428. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30429. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30430. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30431. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30432. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30433. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30434. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30435. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30436. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30437. };
  30438. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30439. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30440. this._drawingContext.font = "normal 12px Segoe UI";
  30441. var textMetrics = this._drawingContext.measureText(text);
  30442. var centerX = projectedPosition.x - textMetrics.width / 2;
  30443. var centerY = projectedPosition.y;
  30444. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30445. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30446. onClick();
  30447. }
  30448. this._drawingContext.beginPath();
  30449. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30450. this._drawingContext.fillStyle = getFillStyle();
  30451. this._drawingContext.globalAlpha = 0.5;
  30452. this._drawingContext.fill();
  30453. this._drawingContext.globalAlpha = 1.0;
  30454. this._drawingContext.strokeStyle = '#FFFFFF';
  30455. this._drawingContext.lineWidth = 1;
  30456. this._drawingContext.stroke();
  30457. this._drawingContext.fillStyle = "#FFFFFF";
  30458. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30459. this._drawingContext.beginPath();
  30460. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30461. this._drawingContext.fill();
  30462. }
  30463. };
  30464. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30465. if (!this._clickPosition) {
  30466. return false;
  30467. }
  30468. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30469. return false;
  30470. }
  30471. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30472. return false;
  30473. }
  30474. return true;
  30475. };
  30476. DebugLayer.prototype.isVisible = function () {
  30477. return this._enabled;
  30478. };
  30479. DebugLayer.prototype.hide = function () {
  30480. if (!this._enabled) {
  30481. return;
  30482. }
  30483. this._enabled = false;
  30484. var engine = this._scene.getEngine();
  30485. this._scene.unregisterBeforeRender(this._syncData);
  30486. this._scene.unregisterAfterRender(this._syncUI);
  30487. document.body.removeChild(this._globalDiv);
  30488. window.removeEventListener("resize", this._syncPositions);
  30489. this._scene.forceShowBoundingBoxes = false;
  30490. this._scene.forceWireframe = false;
  30491. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30492. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30493. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30494. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30495. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30496. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30497. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30498. this._scene.shadowsEnabled = true;
  30499. this._scene.particlesEnabled = true;
  30500. this._scene.postProcessesEnabled = true;
  30501. this._scene.collisionsEnabled = true;
  30502. this._scene.lightsEnabled = true;
  30503. this._scene.texturesEnabled = true;
  30504. this._scene.lensFlaresEnabled = true;
  30505. this._scene.proceduralTexturesEnabled = true;
  30506. this._scene.renderTargetsEnabled = true;
  30507. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30508. };
  30509. DebugLayer.prototype.show = function (showUI, camera) {
  30510. if (showUI === void 0) { showUI = true; }
  30511. if (camera === void 0) { camera = null; }
  30512. if (this._enabled) {
  30513. return;
  30514. }
  30515. this._enabled = true;
  30516. if (camera) {
  30517. this._camera = camera;
  30518. }
  30519. else {
  30520. this._camera = this._scene.activeCamera;
  30521. }
  30522. this._showUI = showUI;
  30523. var engine = this._scene.getEngine();
  30524. this._globalDiv = document.createElement("div");
  30525. document.body.appendChild(this._globalDiv);
  30526. this._generateDOMelements();
  30527. window.addEventListener("resize", this._syncPositions);
  30528. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30529. this._syncPositions();
  30530. this._scene.registerBeforeRender(this._syncData);
  30531. this._scene.registerAfterRender(this._syncUI);
  30532. };
  30533. DebugLayer.prototype._clearLabels = function () {
  30534. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30535. for (var index = 0; index < this._scene.meshes.length; index++) {
  30536. var mesh = this._scene.meshes[index];
  30537. mesh.renderOverlay = false;
  30538. }
  30539. };
  30540. DebugLayer.prototype._generateheader = function (root, text) {
  30541. var header = document.createElement("div");
  30542. header.innerHTML = text + "&nbsp;";
  30543. header.style.textAlign = "right";
  30544. header.style.width = "100%";
  30545. header.style.color = "white";
  30546. header.style.backgroundColor = "Black";
  30547. header.style.padding = "5px 5px 4px 0px";
  30548. header.style.marginLeft = "-5px";
  30549. header.style.fontWeight = "bold";
  30550. root.appendChild(header);
  30551. };
  30552. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30553. var label = document.createElement("label");
  30554. label.innerHTML = title;
  30555. label.style.color = color;
  30556. root.appendChild(label);
  30557. root.appendChild(document.createElement("br"));
  30558. };
  30559. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30560. if (tag === void 0) { tag = null; }
  30561. var label = document.createElement("label");
  30562. var boundingBoxesCheckbox = document.createElement("input");
  30563. boundingBoxesCheckbox.type = "checkbox";
  30564. boundingBoxesCheckbox.checked = initialState;
  30565. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30566. task(evt.target, tag);
  30567. });
  30568. label.appendChild(boundingBoxesCheckbox);
  30569. var container = document.createElement("span");
  30570. var leftPart = document.createElement("span");
  30571. var rightPart = document.createElement("span");
  30572. rightPart.style.cssFloat = "right";
  30573. leftPart.innerHTML = leftTitle;
  30574. rightPart.innerHTML = rightTitle;
  30575. rightPart.style.fontSize = "12px";
  30576. rightPart.style.maxWidth = "200px";
  30577. container.appendChild(leftPart);
  30578. container.appendChild(rightPart);
  30579. label.appendChild(container);
  30580. root.appendChild(label);
  30581. root.appendChild(document.createElement("br"));
  30582. };
  30583. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30584. if (tag === void 0) { tag = null; }
  30585. var label = document.createElement("label");
  30586. var checkBox = document.createElement("input");
  30587. checkBox.type = "checkbox";
  30588. checkBox.checked = initialState;
  30589. checkBox.addEventListener("change", function (evt) {
  30590. task(evt.target, tag);
  30591. });
  30592. label.appendChild(checkBox);
  30593. label.appendChild(document.createTextNode(title));
  30594. root.appendChild(label);
  30595. root.appendChild(document.createElement("br"));
  30596. };
  30597. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30598. if (tag === void 0) { tag = null; }
  30599. var button = document.createElement("button");
  30600. button.innerHTML = title;
  30601. button.style.height = "24px";
  30602. button.style.color = "#444444";
  30603. button.style.border = "1px solid white";
  30604. button.className = "debugLayerButton";
  30605. button.addEventListener("click", function (evt) {
  30606. task(evt.target, tag);
  30607. });
  30608. root.appendChild(button);
  30609. root.appendChild(document.createElement("br"));
  30610. };
  30611. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30612. if (tag === void 0) { tag = null; }
  30613. var label = document.createElement("label");
  30614. var boundingBoxesRadio = document.createElement("input");
  30615. boundingBoxesRadio.type = "radio";
  30616. boundingBoxesRadio.name = name;
  30617. boundingBoxesRadio.checked = initialState;
  30618. boundingBoxesRadio.addEventListener("change", function (evt) {
  30619. task(evt.target, tag);
  30620. });
  30621. label.appendChild(boundingBoxesRadio);
  30622. label.appendChild(document.createTextNode(title));
  30623. root.appendChild(label);
  30624. root.appendChild(document.createElement("br"));
  30625. };
  30626. DebugLayer.prototype._generateDOMelements = function () {
  30627. var _this = this;
  30628. this._globalDiv.id = "DebugLayer";
  30629. this._globalDiv.style.position = "absolute";
  30630. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30631. this._globalDiv.style.fontSize = "14px";
  30632. this._globalDiv.style.color = "white";
  30633. // Drawing canvas
  30634. this._drawingCanvas = document.createElement("canvas");
  30635. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30636. this._drawingCanvas.style.position = "absolute";
  30637. this._drawingCanvas.style.pointerEvents = "none";
  30638. this._drawingContext = this._drawingCanvas.getContext("2d");
  30639. this._globalDiv.appendChild(this._drawingCanvas);
  30640. if (this._showUI) {
  30641. var background = "rgba(128, 128, 128, 0.4)";
  30642. var border = "rgb(180, 180, 180) solid 1px";
  30643. // Stats
  30644. this._statsDiv = document.createElement("div");
  30645. this._statsDiv.id = "DebugLayerStats";
  30646. this._statsDiv.style.border = border;
  30647. this._statsDiv.style.position = "absolute";
  30648. this._statsDiv.style.background = background;
  30649. this._statsDiv.style.padding = "0px 0px 0px 5px";
  30650. this._generateheader(this._statsDiv, "STATISTICS");
  30651. this._statsSubsetDiv = document.createElement("div");
  30652. this._statsSubsetDiv.style.paddingTop = "5px";
  30653. this._statsSubsetDiv.style.paddingBottom = "5px";
  30654. this._statsSubsetDiv.style.overflowY = "auto";
  30655. this._statsDiv.appendChild(this._statsSubsetDiv);
  30656. // Tree
  30657. this._treeDiv = document.createElement("div");
  30658. this._treeDiv.id = "DebugLayerTree";
  30659. this._treeDiv.style.border = border;
  30660. this._treeDiv.style.position = "absolute";
  30661. this._treeDiv.style.background = background;
  30662. this._treeDiv.style.padding = "0px 0px 0px 5px";
  30663. this._treeDiv.style.display = "none";
  30664. this._generateheader(this._treeDiv, "MESHES TREE");
  30665. this._treeSubsetDiv = document.createElement("div");
  30666. this._treeSubsetDiv.style.paddingTop = "5px";
  30667. this._treeSubsetDiv.style.paddingRight = "5px";
  30668. this._treeSubsetDiv.style.overflowY = "auto";
  30669. this._treeSubsetDiv.style.maxHeight = "300px";
  30670. this._treeDiv.appendChild(this._treeSubsetDiv);
  30671. this._needToRefreshMeshesTree = true;
  30672. // Logs
  30673. this._logDiv = document.createElement("div");
  30674. this._logDiv.style.border = border;
  30675. this._logDiv.id = "DebugLayerLogs";
  30676. this._logDiv.style.position = "absolute";
  30677. this._logDiv.style.background = background;
  30678. this._logDiv.style.padding = "0px 0px 0px 5px";
  30679. this._logDiv.style.display = "none";
  30680. this._generateheader(this._logDiv, "LOGS");
  30681. this._logSubsetDiv = document.createElement("div");
  30682. this._logSubsetDiv.style.height = "127px";
  30683. this._logSubsetDiv.style.paddingTop = "5px";
  30684. this._logSubsetDiv.style.overflowY = "auto";
  30685. this._logSubsetDiv.style.fontSize = "12px";
  30686. this._logSubsetDiv.style.fontFamily = "consolas";
  30687. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  30688. this._logDiv.appendChild(this._logSubsetDiv);
  30689. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  30690. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  30691. };
  30692. // Options
  30693. this._optionsDiv = document.createElement("div");
  30694. this._optionsDiv.id = "DebugLayerOptions";
  30695. this._optionsDiv.style.border = border;
  30696. this._optionsDiv.style.position = "absolute";
  30697. this._optionsDiv.style.background = background;
  30698. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  30699. this._optionsDiv.style.overflowY = "auto";
  30700. this._generateheader(this._optionsDiv, "OPTIONS");
  30701. this._optionsSubsetDiv = document.createElement("div");
  30702. this._optionsSubsetDiv.style.paddingTop = "5px";
  30703. this._optionsSubsetDiv.style.paddingBottom = "5px";
  30704. this._optionsSubsetDiv.style.overflowY = "auto";
  30705. this._optionsSubsetDiv.style.maxHeight = "200px";
  30706. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  30707. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  30708. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  30709. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  30710. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  30711. _this._displayTree = element.checked;
  30712. _this._needToRefreshMeshesTree = true;
  30713. });
  30714. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30715. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  30716. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  30717. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  30718. _this._labelsEnabled = element.checked;
  30719. if (!_this._labelsEnabled) {
  30720. _this._clearLabels();
  30721. }
  30722. });
  30723. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  30724. if (element.checked) {
  30725. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  30726. }
  30727. else {
  30728. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  30729. }
  30730. });
  30731. ;
  30732. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30733. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  30734. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  30735. if (element.checked) {
  30736. _this._scene.forceWireframe = false;
  30737. _this._scene.forcePointsCloud = false;
  30738. }
  30739. });
  30740. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  30741. if (element.checked) {
  30742. _this._scene.forceWireframe = true;
  30743. _this._scene.forcePointsCloud = false;
  30744. }
  30745. });
  30746. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  30747. if (element.checked) {
  30748. _this._scene.forceWireframe = false;
  30749. _this._scene.forcePointsCloud = true;
  30750. }
  30751. });
  30752. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30753. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  30754. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  30755. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  30756. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  30757. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  30758. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  30759. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  30760. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  30761. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  30762. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30763. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  30764. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  30765. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  30766. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  30767. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  30768. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  30769. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  30770. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  30771. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  30772. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  30773. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  30774. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  30775. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  30776. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  30777. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30778. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30779. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  30780. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  30781. if (element.checked) {
  30782. _this._scene.headphone = true;
  30783. }
  30784. });
  30785. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  30786. if (element.checked) {
  30787. _this._scene.headphone = false;
  30788. }
  30789. });
  30790. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  30791. _this._scene.audioEnabled = !element.checked;
  30792. });
  30793. }
  30794. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30795. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  30796. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  30797. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30798. this._globalDiv.appendChild(this._statsDiv);
  30799. this._globalDiv.appendChild(this._logDiv);
  30800. this._globalDiv.appendChild(this._optionsDiv);
  30801. this._globalDiv.appendChild(this._treeDiv);
  30802. }
  30803. };
  30804. DebugLayer.prototype._displayStats = function () {
  30805. var scene = this._scene;
  30806. var engine = scene.getEngine();
  30807. var glInfo = engine.getGlInfo();
  30808. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  30809. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30810. + "<b>Count</b><br>"
  30811. + "Total meshes: " + scene.meshes.length + "<br>"
  30812. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  30813. + "Total materials: " + scene.materials.length + "<br>"
  30814. + "Total textures: " + scene.textures.length + "<br>"
  30815. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  30816. + "Active indices: " + scene.getActiveIndices() + "<br>"
  30817. + "Active bones: " + scene.getActiveBones() + "<br>"
  30818. + "Active particles: " + scene.getActiveParticles() + "<br>"
  30819. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  30820. + "<b>Duration</b><br>"
  30821. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  30822. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  30823. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  30824. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  30825. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  30826. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  30827. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  30828. + "</div>"
  30829. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30830. + "<b>Extensions</b><br>"
  30831. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  30832. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  30833. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  30834. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  30835. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  30836. + "<b>Caps.</b><br>"
  30837. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  30838. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  30839. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  30840. + "</div><br>"
  30841. + "<b>Info</b><br>"
  30842. + glInfo.version + "<br>"
  30843. + glInfo.renderer + "<br>";
  30844. if (this.customStatsFunction) {
  30845. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  30846. }
  30847. };
  30848. return DebugLayer;
  30849. })();
  30850. BABYLON.DebugLayer = DebugLayer;
  30851. })(BABYLON || (BABYLON = {}));
  30852. var BABYLON;
  30853. (function (BABYLON) {
  30854. var RawTexture = (function (_super) {
  30855. __extends(RawTexture, _super);
  30856. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  30857. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30858. if (invertY === void 0) { invertY = false; }
  30859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30860. _super.call(this, null, scene, !generateMipMaps, invertY);
  30861. this.format = format;
  30862. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  30863. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30864. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30865. }
  30866. RawTexture.prototype.update = function (data) {
  30867. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  30868. };
  30869. // Statics
  30870. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30871. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30872. if (invertY === void 0) { invertY = false; }
  30873. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30874. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  30875. };
  30876. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30877. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30878. if (invertY === void 0) { invertY = false; }
  30879. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30880. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30881. };
  30882. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30883. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30884. if (invertY === void 0) { invertY = false; }
  30885. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30886. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30887. };
  30888. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30889. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30890. if (invertY === void 0) { invertY = false; }
  30891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30892. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  30893. };
  30894. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30895. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30896. if (invertY === void 0) { invertY = false; }
  30897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30898. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  30899. };
  30900. return RawTexture;
  30901. })(BABYLON.Texture);
  30902. BABYLON.RawTexture = RawTexture;
  30903. })(BABYLON || (BABYLON = {}));
  30904. var BABYLON;
  30905. (function (BABYLON) {
  30906. var IndexedVector2 = (function (_super) {
  30907. __extends(IndexedVector2, _super);
  30908. function IndexedVector2(original, index) {
  30909. _super.call(this, original.x, original.y);
  30910. this.index = index;
  30911. }
  30912. return IndexedVector2;
  30913. })(BABYLON.Vector2);
  30914. var PolygonPoints = (function () {
  30915. function PolygonPoints() {
  30916. this.elements = new Array();
  30917. }
  30918. PolygonPoints.prototype.add = function (originalPoints) {
  30919. var _this = this;
  30920. var result = new Array();
  30921. originalPoints.forEach(function (point) {
  30922. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  30923. var newPoint = new IndexedVector2(point, _this.elements.length);
  30924. result.push(newPoint);
  30925. _this.elements.push(newPoint);
  30926. }
  30927. });
  30928. return result;
  30929. };
  30930. PolygonPoints.prototype.computeBounds = function () {
  30931. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30932. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30933. this.elements.forEach(function (point) {
  30934. // x
  30935. if (point.x < lmin.x) {
  30936. lmin.x = point.x;
  30937. }
  30938. else if (point.x > lmax.x) {
  30939. lmax.x = point.x;
  30940. }
  30941. // y
  30942. if (point.y < lmin.y) {
  30943. lmin.y = point.y;
  30944. }
  30945. else if (point.y > lmax.y) {
  30946. lmax.y = point.y;
  30947. }
  30948. });
  30949. return {
  30950. min: lmin,
  30951. max: lmax,
  30952. width: lmax.x - lmin.x,
  30953. height: lmax.y - lmin.y
  30954. };
  30955. };
  30956. return PolygonPoints;
  30957. })();
  30958. var Polygon = (function () {
  30959. function Polygon() {
  30960. }
  30961. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  30962. return [
  30963. new BABYLON.Vector2(xmin, ymin),
  30964. new BABYLON.Vector2(xmax, ymin),
  30965. new BABYLON.Vector2(xmax, ymax),
  30966. new BABYLON.Vector2(xmin, ymax)
  30967. ];
  30968. };
  30969. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  30970. if (cx === void 0) { cx = 0; }
  30971. if (cy === void 0) { cy = 0; }
  30972. if (numberOfSides === void 0) { numberOfSides = 32; }
  30973. var result = new Array();
  30974. var angle = 0;
  30975. var increment = (Math.PI * 2) / numberOfSides;
  30976. for (var i = 0; i < numberOfSides; i++) {
  30977. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  30978. angle -= increment;
  30979. }
  30980. return result;
  30981. };
  30982. Polygon.Parse = function (input) {
  30983. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  30984. var i, result = [];
  30985. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  30986. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  30987. }
  30988. return result;
  30989. };
  30990. Polygon.StartingAt = function (x, y) {
  30991. return BABYLON.Path2.StartingAt(x, y);
  30992. };
  30993. return Polygon;
  30994. })();
  30995. BABYLON.Polygon = Polygon;
  30996. var PolygonMeshBuilder = (function () {
  30997. function PolygonMeshBuilder(name, contours, scene) {
  30998. this._points = new PolygonPoints();
  30999. this._outlinepoints = new PolygonPoints();
  31000. this._holes = [];
  31001. if (!("poly2tri" in window)) {
  31002. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31003. }
  31004. this._name = name;
  31005. this._scene = scene;
  31006. var points;
  31007. if (contours instanceof BABYLON.Path2) {
  31008. points = contours.getPoints();
  31009. }
  31010. else {
  31011. points = contours;
  31012. }
  31013. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31014. this._outlinepoints.add(points);
  31015. }
  31016. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31017. this._swctx.addHole(this._points.add(hole));
  31018. var holepoints = new PolygonPoints();
  31019. holepoints.add(hole);
  31020. this._holes.push(holepoints);
  31021. return this;
  31022. };
  31023. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31024. var _this = this;
  31025. if (updatable === void 0) { updatable = false; }
  31026. var result = new BABYLON.Mesh(this._name, this._scene);
  31027. var normals = [];
  31028. var positions = [];
  31029. var uvs = [];
  31030. var bounds = this._points.computeBounds();
  31031. this._points.elements.forEach(function (p) {
  31032. normals.push(0, 1.0, 0);
  31033. positions.push(p.x, 0, p.y);
  31034. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31035. });
  31036. var indices = [];
  31037. this._swctx.triangulate();
  31038. this._swctx.getTriangles().forEach(function (triangle) {
  31039. triangle.getPoints().forEach(function (point) {
  31040. indices.push(point.index);
  31041. });
  31042. });
  31043. if (depth > 0) {
  31044. var positionscount = (positions.length / 3); //get the current pointcount
  31045. this._points.elements.forEach(function (p) {
  31046. normals.push(0, -1.0, 0);
  31047. positions.push(p.x, -depth, p.y);
  31048. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31049. });
  31050. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31051. var p2;
  31052. var poscounter = 0;
  31053. this._swctx.getTriangles().forEach(function (triangle) {
  31054. triangle.getPoints().forEach(function (point) {
  31055. switch (poscounter) {
  31056. case 0:
  31057. p1 = point;
  31058. break;
  31059. case 1:
  31060. p2 = point;
  31061. break;
  31062. case 2:
  31063. indices.push(point.index + positionscount);
  31064. indices.push(p2.index + positionscount);
  31065. indices.push(p1.index + positionscount);
  31066. poscounter = -1;
  31067. break;
  31068. }
  31069. poscounter++;
  31070. //indices.push((<IndexedVector2>point).index + positionscount);
  31071. });
  31072. });
  31073. //Add the sides
  31074. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31075. this._holes.forEach(function (hole) {
  31076. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31077. });
  31078. }
  31079. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31080. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31081. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31082. result.setIndices(indices);
  31083. return result;
  31084. };
  31085. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31086. var StartIndex = positions.length / 3;
  31087. var ulength = 0;
  31088. for (var i = 0; i < points.elements.length; i++) {
  31089. var p = points.elements[i];
  31090. var p1;
  31091. if ((i + 1) > points.elements.length - 1) {
  31092. p1 = points.elements[0];
  31093. }
  31094. else {
  31095. p1 = points.elements[i + 1];
  31096. }
  31097. positions.push(p.x, 0, p.y);
  31098. positions.push(p.x, -depth, p.y);
  31099. positions.push(p1.x, 0, p1.y);
  31100. positions.push(p1.x, -depth, p1.y);
  31101. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31102. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31103. var v3 = v2.subtract(v1);
  31104. var v4 = new BABYLON.Vector3(0, 1, 0);
  31105. var vn = BABYLON.Vector3.Cross(v3, v4);
  31106. vn = vn.normalize();
  31107. uvs.push(ulength / bounds.width, 0);
  31108. uvs.push(ulength / bounds.width, 1);
  31109. ulength += v3.length();
  31110. uvs.push((ulength / bounds.width), 0);
  31111. uvs.push((ulength / bounds.width), 1);
  31112. if (!flip) {
  31113. normals.push(-vn.x, -vn.y, -vn.z);
  31114. normals.push(-vn.x, -vn.y, -vn.z);
  31115. normals.push(-vn.x, -vn.y, -vn.z);
  31116. normals.push(-vn.x, -vn.y, -vn.z);
  31117. indices.push(StartIndex);
  31118. indices.push(StartIndex + 1);
  31119. indices.push(StartIndex + 2);
  31120. indices.push(StartIndex + 1);
  31121. indices.push(StartIndex + 3);
  31122. indices.push(StartIndex + 2);
  31123. }
  31124. else {
  31125. normals.push(vn.x, vn.y, vn.z);
  31126. normals.push(vn.x, vn.y, vn.z);
  31127. normals.push(vn.x, vn.y, vn.z);
  31128. normals.push(vn.x, vn.y, vn.z);
  31129. indices.push(StartIndex);
  31130. indices.push(StartIndex + 2);
  31131. indices.push(StartIndex + 1);
  31132. indices.push(StartIndex + 1);
  31133. indices.push(StartIndex + 2);
  31134. indices.push(StartIndex + 3);
  31135. }
  31136. StartIndex += 4;
  31137. }
  31138. ;
  31139. };
  31140. return PolygonMeshBuilder;
  31141. })();
  31142. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31143. })(BABYLON || (BABYLON = {}));
  31144. var BABYLON;
  31145. (function (BABYLON) {
  31146. var SimplificationSettings = (function () {
  31147. function SimplificationSettings(quality, distance, optimizeMesh) {
  31148. this.quality = quality;
  31149. this.distance = distance;
  31150. this.optimizeMesh = optimizeMesh;
  31151. }
  31152. return SimplificationSettings;
  31153. })();
  31154. BABYLON.SimplificationSettings = SimplificationSettings;
  31155. var SimplificationQueue = (function () {
  31156. function SimplificationQueue() {
  31157. this.running = false;
  31158. this._simplificationArray = [];
  31159. }
  31160. SimplificationQueue.prototype.addTask = function (task) {
  31161. this._simplificationArray.push(task);
  31162. };
  31163. SimplificationQueue.prototype.executeNext = function () {
  31164. var task = this._simplificationArray.pop();
  31165. if (task) {
  31166. this.running = true;
  31167. this.runSimplification(task);
  31168. }
  31169. else {
  31170. this.running = false;
  31171. }
  31172. };
  31173. SimplificationQueue.prototype.runSimplification = function (task) {
  31174. var _this = this;
  31175. if (task.parallelProcessing) {
  31176. //parallel simplifier
  31177. task.settings.forEach(function (setting) {
  31178. var simplifier = _this.getSimplifier(task);
  31179. simplifier.simplify(setting, function (newMesh) {
  31180. task.mesh.addLODLevel(setting.distance, newMesh);
  31181. newMesh.isVisible = true;
  31182. //check if it is the last
  31183. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31184. //all done, run the success callback.
  31185. task.successCallback();
  31186. }
  31187. _this.executeNext();
  31188. });
  31189. });
  31190. }
  31191. else {
  31192. //single simplifier.
  31193. var simplifier = this.getSimplifier(task);
  31194. var runDecimation = function (setting, callback) {
  31195. simplifier.simplify(setting, function (newMesh) {
  31196. task.mesh.addLODLevel(setting.distance, newMesh);
  31197. newMesh.isVisible = true;
  31198. //run the next quality level
  31199. callback();
  31200. });
  31201. };
  31202. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31203. runDecimation(task.settings[loop.index], function () {
  31204. loop.executeNext();
  31205. });
  31206. }, function () {
  31207. //execution ended, run the success callback.
  31208. if (task.successCallback) {
  31209. task.successCallback();
  31210. }
  31211. _this.executeNext();
  31212. });
  31213. }
  31214. };
  31215. SimplificationQueue.prototype.getSimplifier = function (task) {
  31216. switch (task.simplificationType) {
  31217. case SimplificationType.QUADRATIC:
  31218. default:
  31219. return new QuadraticErrorSimplification(task.mesh);
  31220. }
  31221. };
  31222. return SimplificationQueue;
  31223. })();
  31224. BABYLON.SimplificationQueue = SimplificationQueue;
  31225. /**
  31226. * The implemented types of simplification.
  31227. * At the moment only Quadratic Error Decimation is implemented.
  31228. */
  31229. (function (SimplificationType) {
  31230. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31231. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31232. var SimplificationType = BABYLON.SimplificationType;
  31233. var DecimationTriangle = (function () {
  31234. function DecimationTriangle(vertices) {
  31235. this.vertices = vertices;
  31236. this.error = new Array(4);
  31237. this.deleted = false;
  31238. this.isDirty = false;
  31239. this.deletePending = false;
  31240. this.borderFactor = 0;
  31241. }
  31242. return DecimationTriangle;
  31243. })();
  31244. BABYLON.DecimationTriangle = DecimationTriangle;
  31245. var DecimationVertex = (function () {
  31246. function DecimationVertex(position, id) {
  31247. this.position = position;
  31248. this.id = id;
  31249. this.isBorder = true;
  31250. this.q = new QuadraticMatrix();
  31251. this.triangleCount = 0;
  31252. this.triangleStart = 0;
  31253. this.originalOffsets = [];
  31254. }
  31255. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31256. this.position.copyFrom(newPosition);
  31257. };
  31258. return DecimationVertex;
  31259. })();
  31260. BABYLON.DecimationVertex = DecimationVertex;
  31261. var QuadraticMatrix = (function () {
  31262. function QuadraticMatrix(data) {
  31263. this.data = new Array(10);
  31264. for (var i = 0; i < 10; ++i) {
  31265. if (data && data[i]) {
  31266. this.data[i] = data[i];
  31267. }
  31268. else {
  31269. this.data[i] = 0;
  31270. }
  31271. }
  31272. }
  31273. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31274. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31275. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31276. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31277. return det;
  31278. };
  31279. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31280. for (var i = 0; i < 10; ++i) {
  31281. this.data[i] += matrix.data[i];
  31282. }
  31283. };
  31284. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31285. for (var i = 0; i < 10; ++i) {
  31286. this.data[i] += data[i];
  31287. }
  31288. };
  31289. QuadraticMatrix.prototype.add = function (matrix) {
  31290. var m = new QuadraticMatrix();
  31291. for (var i = 0; i < 10; ++i) {
  31292. m.data[i] = this.data[i] + matrix.data[i];
  31293. }
  31294. return m;
  31295. };
  31296. QuadraticMatrix.FromData = function (a, b, c, d) {
  31297. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31298. };
  31299. //returning an array to avoid garbage collection
  31300. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31301. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31302. };
  31303. return QuadraticMatrix;
  31304. })();
  31305. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31306. var Reference = (function () {
  31307. function Reference(vertexId, triangleId) {
  31308. this.vertexId = vertexId;
  31309. this.triangleId = triangleId;
  31310. }
  31311. return Reference;
  31312. })();
  31313. BABYLON.Reference = Reference;
  31314. /**
  31315. * An implementation of the Quadratic Error simplification algorithm.
  31316. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31317. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31318. * @author RaananW
  31319. */
  31320. var QuadraticErrorSimplification = (function () {
  31321. function QuadraticErrorSimplification(_mesh) {
  31322. this._mesh = _mesh;
  31323. this.initialized = false;
  31324. this.syncIterations = 5000;
  31325. this.aggressiveness = 7;
  31326. this.decimationIterations = 100;
  31327. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31328. }
  31329. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31330. var _this = this;
  31331. this.initDecimatedMesh();
  31332. //iterating through the submeshes array, one after the other.
  31333. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31334. _this.initWithMesh(loop.index, function () {
  31335. _this.runDecimation(settings, loop.index, function () {
  31336. loop.executeNext();
  31337. });
  31338. }, settings.optimizeMesh);
  31339. }, function () {
  31340. setTimeout(function () {
  31341. successCallback(_this._reconstructedMesh);
  31342. }, 0);
  31343. });
  31344. };
  31345. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31346. var _this = this;
  31347. var gCount = 0;
  31348. triangle.vertices.forEach(function (vertex) {
  31349. var count = 0;
  31350. var vPos = vertex.position;
  31351. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31352. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31353. ++count;
  31354. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  31355. ++count;
  31356. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  31357. ++count;
  31358. if (count > 1) {
  31359. ++gCount;
  31360. }
  31361. ;
  31362. });
  31363. if (gCount > 1) {
  31364. console.log(triangle, gCount);
  31365. }
  31366. return gCount > 1;
  31367. };
  31368. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31369. var _this = this;
  31370. var targetCount = ~~(this.triangles.length * settings.quality);
  31371. var deletedTriangles = 0;
  31372. var triangleCount = this.triangles.length;
  31373. var iterationFunction = function (iteration, callback) {
  31374. setTimeout(function () {
  31375. if (iteration % 5 === 0) {
  31376. _this.updateMesh(iteration === 0);
  31377. }
  31378. for (var i = 0; i < _this.triangles.length; ++i) {
  31379. _this.triangles[i].isDirty = false;
  31380. }
  31381. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31382. var trianglesIterator = function (i) {
  31383. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31384. var t = _this.triangles[tIdx];
  31385. if (!t)
  31386. return;
  31387. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31388. return;
  31389. }
  31390. for (var j = 0; j < 3; ++j) {
  31391. if (t.error[j] < threshold) {
  31392. var deleted0 = [];
  31393. var deleted1 = [];
  31394. var v0 = t.vertices[j];
  31395. var v1 = t.vertices[(j + 1) % 3];
  31396. if (v0.isBorder !== v1.isBorder)
  31397. continue;
  31398. var p = BABYLON.Vector3.Zero();
  31399. var n = BABYLON.Vector3.Zero();
  31400. var uv = BABYLON.Vector2.Zero();
  31401. var color = new BABYLON.Color4(0, 0, 0, 1);
  31402. _this.calculateError(v0, v1, p, n, uv, color);
  31403. var delTr = [];
  31404. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31405. continue;
  31406. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31407. continue;
  31408. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31409. continue;
  31410. var uniqueArray = [];
  31411. delTr.forEach(function (deletedT) {
  31412. if (uniqueArray.indexOf(deletedT) === -1) {
  31413. deletedT.deletePending = true;
  31414. uniqueArray.push(deletedT);
  31415. }
  31416. });
  31417. if (uniqueArray.length % 2 != 0) {
  31418. continue;
  31419. }
  31420. v0.q = v1.q.add(v0.q);
  31421. v0.updatePosition(p);
  31422. var tStart = _this.references.length;
  31423. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31424. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31425. var tCount = _this.references.length - tStart;
  31426. if (tCount <= v0.triangleCount) {
  31427. if (tCount) {
  31428. for (var c = 0; c < tCount; c++) {
  31429. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31430. }
  31431. }
  31432. }
  31433. else {
  31434. v0.triangleStart = tStart;
  31435. }
  31436. v0.triangleCount = tCount;
  31437. break;
  31438. }
  31439. }
  31440. };
  31441. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31442. }, 0);
  31443. };
  31444. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31445. if (triangleCount - deletedTriangles <= targetCount)
  31446. loop.breakLoop();
  31447. else {
  31448. iterationFunction(loop.index, function () {
  31449. loop.executeNext();
  31450. });
  31451. }
  31452. }, function () {
  31453. setTimeout(function () {
  31454. //reconstruct this part of the mesh
  31455. _this.reconstructMesh(submeshIndex);
  31456. successCallback();
  31457. }, 0);
  31458. });
  31459. };
  31460. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31461. var _this = this;
  31462. this.vertices = [];
  31463. this.triangles = [];
  31464. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31465. var indices = this._mesh.getIndices();
  31466. var submesh = this._mesh.subMeshes[submeshIndex];
  31467. var findInVertices = function (positionToSearch) {
  31468. if (optimizeMesh) {
  31469. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31470. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31471. return _this.vertices[ii];
  31472. }
  31473. }
  31474. }
  31475. return null;
  31476. };
  31477. var vertexReferences = [];
  31478. var vertexInit = function (i) {
  31479. var offset = i + submesh.verticesStart;
  31480. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31481. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31482. vertex.originalOffsets.push(offset);
  31483. if (vertex.id == _this.vertices.length) {
  31484. _this.vertices.push(vertex);
  31485. }
  31486. vertexReferences.push(vertex.id);
  31487. };
  31488. //var totalVertices = mesh.getTotalVertices();
  31489. var totalVertices = submesh.verticesCount;
  31490. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31491. var indicesInit = function (i) {
  31492. var offset = (submesh.indexStart / 3) + i;
  31493. var pos = (offset * 3);
  31494. var i0 = indices[pos + 0];
  31495. var i1 = indices[pos + 1];
  31496. var i2 = indices[pos + 2];
  31497. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31498. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31499. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31500. var triangle = new DecimationTriangle([v0, v1, v2]);
  31501. triangle.originalOffset = pos;
  31502. _this.triangles.push(triangle);
  31503. };
  31504. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31505. _this.init(callback);
  31506. });
  31507. });
  31508. };
  31509. QuadraticErrorSimplification.prototype.init = function (callback) {
  31510. var _this = this;
  31511. var triangleInit1 = function (i) {
  31512. var t = _this.triangles[i];
  31513. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31514. for (var j = 0; j < 3; j++) {
  31515. 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))));
  31516. }
  31517. };
  31518. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31519. var triangleInit2 = function (i) {
  31520. var t = _this.triangles[i];
  31521. for (var j = 0; j < 3; ++j) {
  31522. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31523. }
  31524. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31525. };
  31526. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31527. _this.initialized = true;
  31528. callback();
  31529. });
  31530. });
  31531. };
  31532. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31533. var newTriangles = [];
  31534. var i;
  31535. for (i = 0; i < this.vertices.length; ++i) {
  31536. this.vertices[i].triangleCount = 0;
  31537. }
  31538. var t;
  31539. var j;
  31540. for (i = 0; i < this.triangles.length; ++i) {
  31541. if (!this.triangles[i].deleted) {
  31542. t = this.triangles[i];
  31543. for (j = 0; j < 3; ++j) {
  31544. t.vertices[j].triangleCount = 1;
  31545. }
  31546. newTriangles.push(t);
  31547. }
  31548. }
  31549. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  31550. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  31551. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  31552. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  31553. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31554. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31555. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31556. var vertexCount = 0;
  31557. for (i = 0; i < this.vertices.length; ++i) {
  31558. var vertex = this.vertices[i];
  31559. vertex.id = vertexCount;
  31560. if (vertex.triangleCount) {
  31561. vertex.originalOffsets.forEach(function (originalOffset) {
  31562. newPositionData.push(vertex.position.x);
  31563. newPositionData.push(vertex.position.y);
  31564. newPositionData.push(vertex.position.z);
  31565. newNormalData.push(normalData[originalOffset * 3]);
  31566. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31567. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31568. if (uvs && uvs.length) {
  31569. newUVsData.push(uvs[(originalOffset * 2)]);
  31570. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31571. }
  31572. else if (colorsData && colorsData.length) {
  31573. newColorsData.push(colorsData[(originalOffset * 4)]);
  31574. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31575. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31576. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31577. }
  31578. ++vertexCount;
  31579. });
  31580. }
  31581. }
  31582. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31583. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31584. var submeshesArray = this._reconstructedMesh.subMeshes;
  31585. this._reconstructedMesh.subMeshes = [];
  31586. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31587. var originalIndices = this._mesh.getIndices();
  31588. for (i = 0; i < newTriangles.length; ++i) {
  31589. var t = newTriangles[i];
  31590. //now get the new referencing point for each vertex
  31591. [0, 1, 2].forEach(function (idx) {
  31592. var id = originalIndices[t.originalOffset + idx];
  31593. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31594. if (offset < 0)
  31595. offset = 0;
  31596. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31597. });
  31598. }
  31599. //overwriting the old vertex buffers and indices.
  31600. this._reconstructedMesh.setIndices(newIndicesArray);
  31601. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31602. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31603. if (newUVsData.length > 0)
  31604. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31605. if (newColorsData.length > 0)
  31606. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31607. //create submesh
  31608. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31609. if (submeshIndex > 0) {
  31610. this._reconstructedMesh.subMeshes = [];
  31611. submeshesArray.forEach(function (submesh) {
  31612. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31613. });
  31614. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31615. }
  31616. };
  31617. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31618. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31619. this._reconstructedMesh.material = this._mesh.material;
  31620. this._reconstructedMesh.parent = this._mesh.parent;
  31621. this._reconstructedMesh.isVisible = false;
  31622. };
  31623. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31624. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31625. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31626. if (t.deleted)
  31627. continue;
  31628. var s = this.references[vertex1.triangleStart + i].vertexId;
  31629. var v1 = t.vertices[(s + 1) % 3];
  31630. var v2 = t.vertices[(s + 2) % 3];
  31631. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31632. deletedArray[i] = true;
  31633. delTr.push(t);
  31634. continue;
  31635. }
  31636. var d1 = v1.position.subtract(point);
  31637. d1 = d1.normalize();
  31638. var d2 = v2.position.subtract(point);
  31639. d2 = d2.normalize();
  31640. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31641. return true;
  31642. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31643. deletedArray[i] = false;
  31644. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31645. return true;
  31646. }
  31647. return false;
  31648. };
  31649. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31650. var newDeleted = deletedTriangles;
  31651. for (var i = 0; i < vertex.triangleCount; ++i) {
  31652. var ref = this.references[vertex.triangleStart + i];
  31653. var t = this.triangles[ref.triangleId];
  31654. if (t.deleted)
  31655. continue;
  31656. if (deletedArray[i] && t.deletePending) {
  31657. t.deleted = true;
  31658. newDeleted++;
  31659. continue;
  31660. }
  31661. t.vertices[ref.vertexId] = origVertex;
  31662. t.isDirty = true;
  31663. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31664. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31665. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31666. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31667. this.references.push(ref);
  31668. }
  31669. return newDeleted;
  31670. };
  31671. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31672. for (var i = 0; i < this.vertices.length; ++i) {
  31673. var vCount = [];
  31674. var vId = [];
  31675. var v = this.vertices[i];
  31676. var j;
  31677. for (j = 0; j < v.triangleCount; ++j) {
  31678. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31679. for (var ii = 0; ii < 3; ii++) {
  31680. var ofs = 0;
  31681. var vv = triangle.vertices[ii];
  31682. while (ofs < vCount.length) {
  31683. if (vId[ofs] === vv.id)
  31684. break;
  31685. ++ofs;
  31686. }
  31687. if (ofs === vCount.length) {
  31688. vCount.push(1);
  31689. vId.push(vv.id);
  31690. }
  31691. else {
  31692. vCount[ofs]++;
  31693. }
  31694. }
  31695. }
  31696. for (j = 0; j < vCount.length; ++j) {
  31697. if (vCount[j] === 1) {
  31698. this.vertices[vId[j]].isBorder = true;
  31699. }
  31700. else {
  31701. this.vertices[vId[j]].isBorder = false;
  31702. }
  31703. }
  31704. }
  31705. };
  31706. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31707. if (identifyBorders === void 0) { identifyBorders = false; }
  31708. var i;
  31709. if (!identifyBorders) {
  31710. var newTrianglesVector = [];
  31711. for (i = 0; i < this.triangles.length; ++i) {
  31712. if (!this.triangles[i].deleted) {
  31713. newTrianglesVector.push(this.triangles[i]);
  31714. }
  31715. }
  31716. this.triangles = newTrianglesVector;
  31717. }
  31718. for (i = 0; i < this.vertices.length; ++i) {
  31719. this.vertices[i].triangleCount = 0;
  31720. this.vertices[i].triangleStart = 0;
  31721. }
  31722. var t;
  31723. var j;
  31724. var v;
  31725. for (i = 0; i < this.triangles.length; ++i) {
  31726. t = this.triangles[i];
  31727. for (j = 0; j < 3; ++j) {
  31728. v = t.vertices[j];
  31729. v.triangleCount++;
  31730. }
  31731. }
  31732. var tStart = 0;
  31733. for (i = 0; i < this.vertices.length; ++i) {
  31734. this.vertices[i].triangleStart = tStart;
  31735. tStart += this.vertices[i].triangleCount;
  31736. this.vertices[i].triangleCount = 0;
  31737. }
  31738. var newReferences = new Array(this.triangles.length * 3);
  31739. for (i = 0; i < this.triangles.length; ++i) {
  31740. t = this.triangles[i];
  31741. for (j = 0; j < 3; ++j) {
  31742. v = t.vertices[j];
  31743. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31744. v.triangleCount++;
  31745. }
  31746. }
  31747. this.references = newReferences;
  31748. if (identifyBorders) {
  31749. this.identifyBorder();
  31750. }
  31751. };
  31752. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31753. var x = point.x;
  31754. var y = point.y;
  31755. var z = point.z;
  31756. 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
  31757. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31758. };
  31759. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31760. var q = vertex1.q.add(vertex2.q);
  31761. var border = vertex1.isBorder && vertex2.isBorder;
  31762. var error = 0;
  31763. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31764. if (qDet !== 0 && !border) {
  31765. if (!pointResult) {
  31766. pointResult = BABYLON.Vector3.Zero();
  31767. }
  31768. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31769. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31770. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31771. error = this.vertexError(q, pointResult);
  31772. }
  31773. else {
  31774. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31775. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31776. var error1 = this.vertexError(q, vertex1.position);
  31777. var error2 = this.vertexError(q, vertex2.position);
  31778. var error3 = this.vertexError(q, p3);
  31779. error = Math.min(error1, error2, error3);
  31780. if (error === error1) {
  31781. if (pointResult) {
  31782. pointResult.copyFrom(vertex1.position);
  31783. }
  31784. }
  31785. else if (error === error2) {
  31786. if (pointResult) {
  31787. pointResult.copyFrom(vertex2.position);
  31788. }
  31789. }
  31790. else {
  31791. if (pointResult) {
  31792. pointResult.copyFrom(p3);
  31793. }
  31794. }
  31795. }
  31796. return error;
  31797. };
  31798. return QuadraticErrorSimplification;
  31799. })();
  31800. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31801. })(BABYLON || (BABYLON = {}));
  31802. var BABYLON;
  31803. (function (BABYLON) {
  31804. var Analyser = (function () {
  31805. function Analyser(scene) {
  31806. this.SMOOTHING = 0.75;
  31807. this.FFT_SIZE = 512;
  31808. this.BARGRAPHAMPLITUDE = 256;
  31809. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  31810. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  31811. this._scene = scene;
  31812. this._audioEngine = BABYLON.Engine.audioEngine;
  31813. if (this._audioEngine.canUseWebAudio) {
  31814. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  31815. this._webAudioAnalyser.minDecibels = -140;
  31816. this._webAudioAnalyser.maxDecibels = 0;
  31817. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31818. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31819. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  31820. }
  31821. }
  31822. Analyser.prototype.getFrequencyBinCount = function () {
  31823. if (this._audioEngine.canUseWebAudio) {
  31824. return this._webAudioAnalyser.frequencyBinCount;
  31825. }
  31826. else {
  31827. return 0;
  31828. }
  31829. };
  31830. Analyser.prototype.getByteFrequencyData = function () {
  31831. if (this._audioEngine.canUseWebAudio) {
  31832. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31833. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31834. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  31835. }
  31836. return this._byteFreqs;
  31837. };
  31838. Analyser.prototype.getByteTimeDomainData = function () {
  31839. if (this._audioEngine.canUseWebAudio) {
  31840. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31841. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31842. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  31843. }
  31844. return this._byteTime;
  31845. };
  31846. Analyser.prototype.getFloatFrequencyData = function () {
  31847. if (this._audioEngine.canUseWebAudio) {
  31848. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31849. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31850. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  31851. }
  31852. return this._floatFreqs;
  31853. };
  31854. Analyser.prototype.drawDebugCanvas = function () {
  31855. var _this = this;
  31856. if (this._audioEngine.canUseWebAudio) {
  31857. if (!this._debugCanvas) {
  31858. this._debugCanvas = document.createElement("canvas");
  31859. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  31860. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  31861. this._debugCanvas.style.position = "absolute";
  31862. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  31863. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  31864. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  31865. document.body.appendChild(this._debugCanvas);
  31866. this._registerFunc = function () {
  31867. _this.drawDebugCanvas();
  31868. };
  31869. this._scene.registerBeforeRender(this._registerFunc);
  31870. }
  31871. if (this._registerFunc) {
  31872. var workingArray = this.getByteFrequencyData();
  31873. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  31874. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  31875. // Draw the frequency domain chart.
  31876. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  31877. var value = workingArray[i];
  31878. var percent = value / this.BARGRAPHAMPLITUDE;
  31879. var height = this.DEBUGCANVASSIZE.height * percent;
  31880. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  31881. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  31882. var hue = i / this.getFrequencyBinCount() * 360;
  31883. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  31884. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  31885. }
  31886. }
  31887. }
  31888. };
  31889. Analyser.prototype.stopDebugCanvas = function () {
  31890. if (this._debugCanvas) {
  31891. this._scene.unregisterBeforeRender(this._registerFunc);
  31892. this._registerFunc = null;
  31893. document.body.removeChild(this._debugCanvas);
  31894. this._debugCanvas = null;
  31895. this._debugCanvasContext = null;
  31896. }
  31897. };
  31898. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  31899. if (this._audioEngine.canUseWebAudio) {
  31900. inputAudioNode.connect(this._webAudioAnalyser);
  31901. this._webAudioAnalyser.connect(outputAudioNode);
  31902. }
  31903. };
  31904. Analyser.prototype.dispose = function () {
  31905. if (this._audioEngine.canUseWebAudio) {
  31906. this._webAudioAnalyser.disconnect();
  31907. }
  31908. };
  31909. return Analyser;
  31910. })();
  31911. BABYLON.Analyser = Analyser;
  31912. })(BABYLON || (BABYLON = {}));
  31913. var BABYLON;
  31914. (function (BABYLON) {
  31915. var DepthRenderer = (function () {
  31916. function DepthRenderer(scene, type) {
  31917. var _this = this;
  31918. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  31919. this._viewMatrix = BABYLON.Matrix.Zero();
  31920. this._projectionMatrix = BABYLON.Matrix.Zero();
  31921. this._transformMatrix = BABYLON.Matrix.Zero();
  31922. this._worldViewProjection = BABYLON.Matrix.Zero();
  31923. this._scene = scene;
  31924. var engine = scene.getEngine();
  31925. // Render target
  31926. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  31927. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31928. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31929. this._depthMap.refreshRate = 1;
  31930. this._depthMap.renderParticles = false;
  31931. this._depthMap.renderList = null;
  31932. // set default depth value to 1.0 (far away)
  31933. this._depthMap.onClear = function (engine) {
  31934. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  31935. };
  31936. // Custom render function
  31937. var renderSubMesh = function (subMesh) {
  31938. var mesh = subMesh.getRenderingMesh();
  31939. var scene = _this._scene;
  31940. var engine = scene.getEngine();
  31941. // Culling
  31942. engine.setState(subMesh.getMaterial().backFaceCulling);
  31943. // Managing instances
  31944. var batch = mesh._getInstancesRenderList(subMesh._id);
  31945. if (batch.mustReturn) {
  31946. return;
  31947. }
  31948. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31949. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31950. engine.enableEffect(_this._effect);
  31951. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  31952. var material = subMesh.getMaterial();
  31953. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31954. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  31955. // Alpha test
  31956. if (material && material.needAlphaTesting()) {
  31957. var alphaTexture = material.getAlphaTestTexture();
  31958. _this._effect.setTexture("diffuseSampler", alphaTexture);
  31959. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31960. }
  31961. // Bones
  31962. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31963. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31964. }
  31965. // Draw
  31966. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  31967. }
  31968. };
  31969. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  31970. var index;
  31971. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31972. renderSubMesh(opaqueSubMeshes.data[index]);
  31973. }
  31974. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31975. renderSubMesh(alphaTestSubMeshes.data[index]);
  31976. }
  31977. };
  31978. }
  31979. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  31980. var defines = [];
  31981. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31982. var mesh = subMesh.getMesh();
  31983. var scene = mesh.getScene();
  31984. var material = subMesh.getMaterial();
  31985. // Alpha test
  31986. if (material && material.needAlphaTesting()) {
  31987. defines.push("#define ALPHATEST");
  31988. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31989. attribs.push(BABYLON.VertexBuffer.UVKind);
  31990. defines.push("#define UV1");
  31991. }
  31992. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31993. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31994. defines.push("#define UV2");
  31995. }
  31996. }
  31997. // Bones
  31998. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  31999. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32000. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32001. defines.push("#define BONES");
  32002. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32003. }
  32004. // Instances
  32005. if (useInstances) {
  32006. defines.push("#define INSTANCES");
  32007. attribs.push("world0");
  32008. attribs.push("world1");
  32009. attribs.push("world2");
  32010. attribs.push("world3");
  32011. }
  32012. // Get correct effect
  32013. var join = defines.join("\n");
  32014. if (this._cachedDefines !== join) {
  32015. this._cachedDefines = join;
  32016. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32017. }
  32018. return this._effect.isReady();
  32019. };
  32020. DepthRenderer.prototype.getDepthMap = function () {
  32021. return this._depthMap;
  32022. };
  32023. // Methods
  32024. DepthRenderer.prototype.dispose = function () {
  32025. this._depthMap.dispose();
  32026. };
  32027. return DepthRenderer;
  32028. })();
  32029. BABYLON.DepthRenderer = DepthRenderer;
  32030. })(BABYLON || (BABYLON = {}));
  32031. var BABYLON;
  32032. (function (BABYLON) {
  32033. var SSAORenderingPipeline = (function (_super) {
  32034. __extends(SSAORenderingPipeline, _super);
  32035. /**
  32036. * @constructor
  32037. * @param {string} name - The rendering pipeline name
  32038. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32039. * @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 }
  32040. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32041. */
  32042. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32043. var _this = this;
  32044. _super.call(this, scene.getEngine(), name);
  32045. // Members
  32046. /**
  32047. * The PassPostProcess id in the pipeline that contains the original scene color
  32048. * @type {string}
  32049. */
  32050. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32051. /**
  32052. * The SSAO PostProcess id in the pipeline
  32053. * @type {string}
  32054. */
  32055. this.SSAORenderEffect = "SSAORenderEffect";
  32056. /**
  32057. * The horizontal blur PostProcess id in the pipeline
  32058. * @type {string}
  32059. */
  32060. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32061. /**
  32062. * The vertical blur PostProcess id in the pipeline
  32063. * @type {string}
  32064. */
  32065. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32066. /**
  32067. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32068. * @type {string}
  32069. */
  32070. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32071. /**
  32072. * The output strength of the SSAO post-process. Default value is 1.0.
  32073. * @type {number}
  32074. */
  32075. this.totalStrength = 1.0;
  32076. /**
  32077. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32078. * @type {number}
  32079. */
  32080. this.radius = 0.0002;
  32081. /**
  32082. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32083. * Must not be equal to fallOff and superior to fallOff.
  32084. * Default value is 0.0075
  32085. * @type {number}
  32086. */
  32087. this.area = 0.0075;
  32088. /**
  32089. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32090. * Must not be equal to area and inferior to area.
  32091. * Default value is 0.0002
  32092. * @type {number}
  32093. */
  32094. this.fallOff = 0.0002;
  32095. this._firstUpdate = true;
  32096. this._scene = scene;
  32097. // Set up assets
  32098. this._createRandomTexture();
  32099. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32100. var ssaoRatio = ratio.ssaoRatio || ratio;
  32101. var combineRatio = ratio.combineRatio || ratio;
  32102. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32103. this._createSSAOPostProcess(ssaoRatio);
  32104. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32105. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32106. this._createSSAOCombinePostProcess(combineRatio);
  32107. // Set up pipeline
  32108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32110. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32111. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32112. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32113. // Finish
  32114. scene.postProcessRenderPipelineManager.addPipeline(this);
  32115. if (cameras)
  32116. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32117. }
  32118. // Public Methods
  32119. /**
  32120. * Returns the horizontal blur PostProcess
  32121. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32122. */
  32123. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32124. return this._blurHPostProcess;
  32125. };
  32126. /**
  32127. * Returns the vertical blur PostProcess
  32128. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32129. */
  32130. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32131. return this._blurVPostProcess;
  32132. };
  32133. /**
  32134. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32135. */
  32136. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32137. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32138. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32139. this._originalColorPostProcess = undefined;
  32140. this._ssaoPostProcess = undefined;
  32141. this._blurHPostProcess = undefined;
  32142. this._blurVPostProcess = undefined;
  32143. this._ssaoCombinePostProcess = undefined;
  32144. this._randomTexture.dispose();
  32145. if (disableDepthRender)
  32146. this._scene.disableDepthRenderer();
  32147. };
  32148. // Private Methods
  32149. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32150. var _this = this;
  32151. var sampleSphere = [
  32152. 0.5381, 0.1856, -0.4319,
  32153. 0.1379, 0.2486, 0.4430,
  32154. 0.3371, 0.5679, -0.0057,
  32155. -0.6999, -0.0451, -0.0019,
  32156. 0.0689, -0.1598, -0.8547,
  32157. 0.0560, 0.0069, -0.1843,
  32158. -0.0146, 0.1402, 0.0762,
  32159. 0.0100, -0.1924, -0.0344,
  32160. -0.3577, -0.5301, -0.4358,
  32161. -0.3169, 0.1063, 0.0158,
  32162. 0.0103, -0.5869, 0.0046,
  32163. -0.0897, -0.4940, 0.3287,
  32164. 0.7119, -0.0154, -0.0918,
  32165. -0.0533, 0.0596, -0.5411,
  32166. 0.0352, -0.0631, 0.5460,
  32167. -0.4776, 0.2847, -0.0271
  32168. ];
  32169. var samplesFactor = 1.0 / 16.0;
  32170. 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);
  32171. this._ssaoPostProcess.onApply = function (effect) {
  32172. if (_this._firstUpdate) {
  32173. effect.setArray3("sampleSphere", sampleSphere);
  32174. effect.setFloat("samplesFactor", samplesFactor);
  32175. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32176. _this._firstUpdate = false;
  32177. }
  32178. effect.setFloat("totalStrength", _this.totalStrength);
  32179. effect.setFloat("radius", _this.radius);
  32180. effect.setFloat("area", _this.area);
  32181. effect.setFloat("fallOff", _this.fallOff);
  32182. effect.setTexture("textureSampler", _this._depthTexture);
  32183. effect.setTexture("randomSampler", _this._randomTexture);
  32184. };
  32185. };
  32186. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32187. var _this = this;
  32188. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32189. this._ssaoCombinePostProcess.onApply = function (effect) {
  32190. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32191. };
  32192. };
  32193. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32194. var size = 512;
  32195. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32196. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32197. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32198. var context = this._randomTexture.getContext();
  32199. var rand = function (min, max) {
  32200. return Math.random() * (max - min) + min;
  32201. };
  32202. for (var x = 0; x < size; x++) {
  32203. for (var y = 0; y < size; y++) {
  32204. var randVector = BABYLON.Vector3.Zero();
  32205. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32206. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32207. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32208. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32209. context.fillRect(x, y, 1, 1);
  32210. }
  32211. }
  32212. this._randomTexture.update(false);
  32213. };
  32214. return SSAORenderingPipeline;
  32215. })(BABYLON.PostProcessRenderPipeline);
  32216. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32217. })(BABYLON || (BABYLON = {}));
  32218. var BABYLON;
  32219. (function (BABYLON) {
  32220. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32221. var VolumetricLightScatteringPostProcess = (function (_super) {
  32222. __extends(VolumetricLightScatteringPostProcess, _super);
  32223. /**
  32224. * @constructor
  32225. * @param {string} name - The post-process name
  32226. * @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)
  32227. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32228. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32229. * @param {number} samples - The post-process quality, default 100
  32230. * @param {number} samplingMode - The post-process filtering mode
  32231. * @param {BABYLON.Engine} engine - The babylon engine
  32232. * @param {boolean} reusable - If the post-process is reusable
  32233. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  32234. */
  32235. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  32236. var _this = this;
  32237. if (samples === void 0) { samples = 100; }
  32238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32239. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  32240. this._screenCoordinates = BABYLON.Vector2.Zero();
  32241. /**
  32242. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  32243. * @type {boolean}
  32244. */
  32245. this.useCustomMeshPosition = false;
  32246. /**
  32247. * If the post-process should inverse the light scattering direction
  32248. * @type {boolean}
  32249. */
  32250. this.invert = true;
  32251. /**
  32252. * Set to true to use the diffuseColor instead of the diffuseTexture
  32253. * @type {boolean}
  32254. */
  32255. this.useDiffuseColor = false;
  32256. /**
  32257. * Array containing the excluded meshes not rendered in the internal pass
  32258. */
  32259. this.excludedMeshes = new Array();
  32260. /**
  32261. * Controls the overall intensity of the post-process
  32262. * @type {number}
  32263. */
  32264. this.exposure = 0.3;
  32265. /**
  32266. * Dissipates each sample's contribution in range [0, 1]
  32267. * @type {number}
  32268. */
  32269. this.decay = 0.96815;
  32270. /**
  32271. * Controls the overall intensity of each sample
  32272. * @type {number}
  32273. */
  32274. this.weight = 0.58767;
  32275. /**
  32276. * Controls the density of each sample
  32277. * @type {number}
  32278. */
  32279. this.density = 0.926;
  32280. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  32281. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  32282. // Configure mesh
  32283. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  32284. // Configure
  32285. this._createPass(scene, ratio.passRatio || ratio);
  32286. this.onApply = function (effect) {
  32287. _this._updateMeshScreenCoordinates(scene);
  32288. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  32289. effect.setFloat("exposure", _this.exposure);
  32290. effect.setFloat("decay", _this.decay);
  32291. effect.setFloat("weight", _this.weight);
  32292. effect.setFloat("density", _this.density);
  32293. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  32294. };
  32295. }
  32296. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  32297. var mesh = subMesh.getMesh();
  32298. var defines = [];
  32299. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32300. var material = subMesh.getMaterial();
  32301. var needUV = false;
  32302. // Render this.mesh as default
  32303. if (mesh === this.mesh) {
  32304. if (this.useDiffuseColor) {
  32305. defines.push("#define DIFFUSE_COLOR_RENDER");
  32306. }
  32307. else if (material) {
  32308. if (material.diffuseTexture !== undefined) {
  32309. defines.push("#define BASIC_RENDER");
  32310. }
  32311. else {
  32312. defines.push("#define DIFFUSE_COLOR_RENDER");
  32313. }
  32314. }
  32315. defines.push("#define NEED_UV");
  32316. needUV = true;
  32317. }
  32318. // Alpha test
  32319. if (material) {
  32320. if (material.needAlphaTesting()) {
  32321. defines.push("#define ALPHATEST");
  32322. }
  32323. if (material.opacityTexture !== undefined) {
  32324. defines.push("#define OPACITY");
  32325. if (material.opacityTexture.getAlphaFromRGB) {
  32326. defines.push("#define OPACITYRGB");
  32327. }
  32328. if (!needUV) {
  32329. defines.push("#define NEED_UV");
  32330. }
  32331. }
  32332. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32333. attribs.push(BABYLON.VertexBuffer.UVKind);
  32334. defines.push("#define UV1");
  32335. }
  32336. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32337. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32338. defines.push("#define UV2");
  32339. }
  32340. }
  32341. // Bones
  32342. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32343. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32344. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32345. defines.push("#define BONES");
  32346. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32347. }
  32348. // Instances
  32349. if (useInstances) {
  32350. defines.push("#define INSTANCES");
  32351. attribs.push("world0");
  32352. attribs.push("world1");
  32353. attribs.push("world2");
  32354. attribs.push("world3");
  32355. }
  32356. // Get correct effect
  32357. var join = defines.join("\n");
  32358. if (this._cachedDefines !== join) {
  32359. this._cachedDefines = join;
  32360. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  32361. }
  32362. return this._volumetricLightScatteringPass.isReady();
  32363. };
  32364. /**
  32365. * Sets the new light position for light scattering effect
  32366. * @param {BABYLON.Vector3} The new custom light position
  32367. */
  32368. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  32369. this._customMeshPosition = position;
  32370. };
  32371. /**
  32372. * Returns the light position for light scattering effect
  32373. * @return {BABYLON.Vector3} The custom light position
  32374. */
  32375. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  32376. return this._customMeshPosition;
  32377. };
  32378. /**
  32379. * Disposes the internal assets and detaches the post-process from the camera
  32380. */
  32381. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  32382. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  32383. if (rttIndex !== -1) {
  32384. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  32385. }
  32386. this._volumetricLightScatteringRTT.dispose();
  32387. _super.prototype.dispose.call(this, camera);
  32388. };
  32389. /**
  32390. * Returns the render target texture used by the post-process
  32391. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  32392. */
  32393. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  32394. return this._volumetricLightScatteringRTT;
  32395. };
  32396. // Private methods
  32397. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  32398. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  32399. return true;
  32400. }
  32401. return false;
  32402. };
  32403. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  32404. var _this = this;
  32405. var engine = scene.getEngine();
  32406. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  32407. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32408. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32409. this._volumetricLightScatteringRTT.renderList = null;
  32410. this._volumetricLightScatteringRTT.renderParticles = false;
  32411. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  32412. // Custom render function for submeshes
  32413. var renderSubMesh = function (subMesh) {
  32414. var mesh = subMesh.getRenderingMesh();
  32415. if (_this._meshExcluded(mesh)) {
  32416. return;
  32417. }
  32418. var scene = mesh.getScene();
  32419. var engine = scene.getEngine();
  32420. // Culling
  32421. engine.setState(subMesh.getMaterial().backFaceCulling);
  32422. // Managing instances
  32423. var batch = mesh._getInstancesRenderList(subMesh._id);
  32424. if (batch.mustReturn) {
  32425. return;
  32426. }
  32427. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32428. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32429. engine.enableEffect(_this._volumetricLightScatteringPass);
  32430. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  32431. var material = subMesh.getMaterial();
  32432. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  32433. // Alpha test
  32434. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  32435. var alphaTexture = material.getAlphaTestTexture();
  32436. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  32437. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  32438. }
  32439. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  32440. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  32441. if (alphaTexture) {
  32442. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32443. }
  32444. }
  32445. if (material.opacityTexture !== undefined) {
  32446. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  32447. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  32448. }
  32449. }
  32450. // Bones
  32451. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32452. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32453. }
  32454. // Draw
  32455. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  32456. }
  32457. };
  32458. // Render target texture callbacks
  32459. var savedSceneClearColor;
  32460. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  32461. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  32462. savedSceneClearColor = scene.clearColor;
  32463. scene.clearColor = sceneClearColor;
  32464. };
  32465. this._volumetricLightScatteringRTT.onAfterRender = function () {
  32466. scene.clearColor = savedSceneClearColor;
  32467. };
  32468. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  32469. var engine = scene.getEngine();
  32470. var index;
  32471. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32472. renderSubMesh(opaqueSubMeshes.data[index]);
  32473. }
  32474. engine.setAlphaTesting(true);
  32475. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32476. renderSubMesh(alphaTestSubMeshes.data[index]);
  32477. }
  32478. engine.setAlphaTesting(false);
  32479. if (transparentSubMeshes.length) {
  32480. // Sort sub meshes
  32481. for (index = 0; index < transparentSubMeshes.length; index++) {
  32482. var submesh = transparentSubMeshes.data[index];
  32483. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  32484. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  32485. }
  32486. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  32487. sortedArray.sort(function (a, b) {
  32488. // Alpha index first
  32489. if (a._alphaIndex > b._alphaIndex) {
  32490. return 1;
  32491. }
  32492. if (a._alphaIndex < b._alphaIndex) {
  32493. return -1;
  32494. }
  32495. // Then distance to camera
  32496. if (a._distanceToCamera < b._distanceToCamera) {
  32497. return 1;
  32498. }
  32499. if (a._distanceToCamera > b._distanceToCamera) {
  32500. return -1;
  32501. }
  32502. return 0;
  32503. });
  32504. // Render sub meshes
  32505. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32506. for (index = 0; index < sortedArray.length; index++) {
  32507. renderSubMesh(sortedArray[index]);
  32508. }
  32509. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32510. }
  32511. };
  32512. };
  32513. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  32514. var transform = scene.getTransformMatrix();
  32515. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  32516. this._screenCoordinates.x = pos.x / this._viewPort.width;
  32517. this._screenCoordinates.y = pos.y / this._viewPort.height;
  32518. if (this.invert)
  32519. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  32520. };
  32521. // Static methods
  32522. /**
  32523. * Creates a default mesh for the Volumeric Light Scattering post-process
  32524. * @param {string} The mesh name
  32525. * @param {BABYLON.Scene} The scene where to create the mesh
  32526. * @return {BABYLON.Mesh} the default mesh
  32527. */
  32528. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  32529. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  32530. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  32531. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  32532. return mesh;
  32533. };
  32534. return VolumetricLightScatteringPostProcess;
  32535. })(BABYLON.PostProcess);
  32536. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  32537. })(BABYLON || (BABYLON = {}));
  32538. var BABYLON;
  32539. (function (BABYLON) {
  32540. var LensRenderingPipeline = (function (_super) {
  32541. __extends(LensRenderingPipeline, _super);
  32542. /**
  32543. * @constructor
  32544. *
  32545. * Effect parameters are as follow:
  32546. * {
  32547. * chromatic_aberration: number; // from 0 to x (1 for realism)
  32548. * edge_blur: number; // from 0 to x (1 for realism)
  32549. * distortion: number; // from 0 to x (1 for realism)
  32550. * grain_amount: number; // from 0 to 1
  32551. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  32552. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  32553. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  32554. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  32555. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  32556. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  32557. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  32558. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  32559. * }
  32560. * Note: if an effect parameter is unset, effect is disabled
  32561. *
  32562. * @param {string} name - The rendering pipeline name
  32563. * @param {object} parameters - An object containing all parameters (see above)
  32564. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32565. * @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)
  32566. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32567. */
  32568. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  32569. var _this = this;
  32570. if (ratio === void 0) { ratio = 1.0; }
  32571. _super.call(this, scene.getEngine(), name);
  32572. // Lens effects can be of the following:
  32573. // - chromatic aberration (slight shift of RGB colors)
  32574. // - blur on the edge of the lens
  32575. // - lens distortion
  32576. // - depth-of-field blur & highlights enhancing
  32577. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  32578. // - grain effect (noise or custom texture)
  32579. // Two additional texture samplers are needed:
  32580. // - depth map (for depth-of-field)
  32581. // - grain texture
  32582. /**
  32583. * The chromatic aberration PostProcess id in the pipeline
  32584. * @type {string}
  32585. */
  32586. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  32587. /**
  32588. * The highlights enhancing PostProcess id in the pipeline
  32589. * @type {string}
  32590. */
  32591. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  32592. /**
  32593. * The depth-of-field PostProcess id in the pipeline
  32594. * @type {string}
  32595. */
  32596. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  32597. this._scene = scene;
  32598. // Fetch texture samplers
  32599. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32600. if (parameters.grain_texture) {
  32601. this._grainTexture = parameters.grain_texture;
  32602. }
  32603. else {
  32604. this._createGrainTexture();
  32605. }
  32606. // save parameters
  32607. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  32608. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  32609. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  32610. this._distortion = parameters.distortion ? parameters.distortion : 0;
  32611. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  32612. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  32613. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  32614. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  32615. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  32616. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  32617. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  32618. // Create effects
  32619. this._createChromaticAberrationPostProcess(ratio);
  32620. this._createHighlightsPostProcess(ratio);
  32621. this._createDepthOfFieldPostProcess(ratio / 4);
  32622. // Set up pipeline
  32623. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  32624. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  32625. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  32626. if (this._highlightsGain == -1) {
  32627. this._disableEffect(this.HighlightsEnhancingEffect, null);
  32628. }
  32629. // Finish
  32630. scene.postProcessRenderPipelineManager.addPipeline(this);
  32631. if (cameras) {
  32632. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32633. }
  32634. }
  32635. // public methods (self explanatory)
  32636. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  32637. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  32638. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  32639. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  32640. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  32641. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  32642. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  32643. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  32644. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  32645. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  32646. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  32647. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  32648. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  32649. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  32650. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  32651. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  32652. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  32653. this._highlightsGain = amount;
  32654. };
  32655. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  32656. if (this._highlightsGain == -1) {
  32657. this._highlightsGain = 1.0;
  32658. }
  32659. this._highlightsThreshold = amount;
  32660. };
  32661. LensRenderingPipeline.prototype.disableHighlights = function () {
  32662. this._highlightsGain = -1;
  32663. };
  32664. /**
  32665. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  32666. */
  32667. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32668. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32669. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32670. this._chromaticAberrationPostProcess = undefined;
  32671. this._highlightsPostProcess = undefined;
  32672. this._depthOfFieldPostProcess = undefined;
  32673. this._grainTexture.dispose();
  32674. if (disableDepthRender)
  32675. this._scene.disableDepthRenderer();
  32676. };
  32677. // colors shifting and distortion
  32678. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  32679. var _this = this;
  32680. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32681. this._chromaticAberrationPostProcess.onApply = function (effect) {
  32682. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  32683. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32684. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32685. };
  32686. };
  32687. // highlights enhancing
  32688. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  32689. var _this = this;
  32690. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32691. this._highlightsPostProcess.onApply = function (effect) {
  32692. effect.setFloat('gain', _this._highlightsGain);
  32693. effect.setFloat('threshold', _this._highlightsThreshold);
  32694. effect.setBool('pentagon', _this._dofPentagon);
  32695. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  32696. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32697. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32698. };
  32699. };
  32700. // colors shifting and distortion
  32701. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  32702. var _this = this;
  32703. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  32704. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  32705. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  32706. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32707. this._depthOfFieldPostProcess.onApply = function (effect) {
  32708. effect.setTexture("depthSampler", _this._depthTexture);
  32709. effect.setTexture("grainSampler", _this._grainTexture);
  32710. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  32711. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  32712. effect.setFloat('grain_amount', _this._grainAmount);
  32713. effect.setBool('blur_noise', _this._blurNoise);
  32714. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32715. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32716. effect.setFloat('distortion', _this._distortion);
  32717. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  32718. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  32719. effect.setFloat('aperture', _this._dofAperture);
  32720. effect.setFloat('darken', _this._dofDarken);
  32721. effect.setFloat('edge_blur', _this._edgeBlur);
  32722. effect.setBool('highlights', (_this._highlightsGain != -1));
  32723. effect.setFloat('near', _this._scene.activeCamera.minZ);
  32724. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  32725. };
  32726. };
  32727. // creates a black and white random noise texture, 512x512
  32728. LensRenderingPipeline.prototype._createGrainTexture = function () {
  32729. var size = 512;
  32730. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32731. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32732. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32733. var context = this._grainTexture.getContext();
  32734. var rand = function (min, max) {
  32735. return Math.random() * (max - min) + min;
  32736. };
  32737. var value;
  32738. for (var x = 0; x < size; x++) {
  32739. for (var y = 0; y < size; y++) {
  32740. value = Math.floor(rand(0.42, 0.58) * 255);
  32741. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  32742. context.fillRect(x, y, 1, 1);
  32743. }
  32744. }
  32745. this._grainTexture.update(false);
  32746. };
  32747. return LensRenderingPipeline;
  32748. })(BABYLON.PostProcessRenderPipeline);
  32749. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  32750. })(BABYLON || (BABYLON = {}));
  32751. //
  32752. // This post-process allows the modification of rendered colors by using
  32753. // a 'look-up table' (LUT). This effect is also called Color Grading.
  32754. //
  32755. // The object needs to be provided an url to a texture containing the color
  32756. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  32757. // Use an image editing software to tweak the LUT to match your needs.
  32758. //
  32759. // For an example of a color LUT, see here:
  32760. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  32761. // For explanations on color grading, see here:
  32762. // http://udn.epicgames.com/Three/ColorGrading.html
  32763. //
  32764. var BABYLON;
  32765. (function (BABYLON) {
  32766. var ColorCorrectionPostProcess = (function (_super) {
  32767. __extends(ColorCorrectionPostProcess, _super);
  32768. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  32769. var _this = this;
  32770. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  32771. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  32772. this._colorTableTexture.anisotropicFilteringLevel = 1;
  32773. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32774. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32775. this.onApply = function (effect) {
  32776. effect.setTexture("colorTable", _this._colorTableTexture);
  32777. };
  32778. }
  32779. return ColorCorrectionPostProcess;
  32780. })(BABYLON.PostProcess);
  32781. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  32782. })(BABYLON || (BABYLON = {}));
  32783. var BABYLON;
  32784. (function (BABYLON) {
  32785. var AnaglyphFreeCamera = (function (_super) {
  32786. __extends(AnaglyphFreeCamera, _super);
  32787. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  32788. _super.call(this, name, position, scene);
  32789. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32790. }
  32791. return AnaglyphFreeCamera;
  32792. })(BABYLON.FreeCamera);
  32793. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  32794. var AnaglyphArcRotateCamera = (function (_super) {
  32795. __extends(AnaglyphArcRotateCamera, _super);
  32796. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  32797. _super.call(this, name, alpha, beta, radius, target, scene);
  32798. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32799. }
  32800. return AnaglyphArcRotateCamera;
  32801. })(BABYLON.ArcRotateCamera);
  32802. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  32803. var AnaglyphGamepadCamera = (function (_super) {
  32804. __extends(AnaglyphGamepadCamera, _super);
  32805. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  32806. _super.call(this, name, position, scene);
  32807. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32808. }
  32809. return AnaglyphGamepadCamera;
  32810. })(BABYLON.GamepadCamera);
  32811. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  32812. var StereoscopicFreeCamera = (function (_super) {
  32813. __extends(StereoscopicFreeCamera, _super);
  32814. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  32815. _super.call(this, name, position, scene);
  32816. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32817. }
  32818. return StereoscopicFreeCamera;
  32819. })(BABYLON.FreeCamera);
  32820. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  32821. var StereoscopicArcRotateCamera = (function (_super) {
  32822. __extends(StereoscopicArcRotateCamera, _super);
  32823. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  32824. _super.call(this, name, alpha, beta, radius, target, scene);
  32825. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32826. }
  32827. return StereoscopicArcRotateCamera;
  32828. })(BABYLON.ArcRotateCamera);
  32829. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  32830. var StereoscopicGamepadCamera = (function (_super) {
  32831. __extends(StereoscopicGamepadCamera, _super);
  32832. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  32833. _super.call(this, name, position, scene);
  32834. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32835. }
  32836. return StereoscopicGamepadCamera;
  32837. })(BABYLON.GamepadCamera);
  32838. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  32839. })(BABYLON || (BABYLON = {}));
  32840. var BABYLON;
  32841. (function (BABYLON) {
  32842. var HDRRenderingPipeline = (function (_super) {
  32843. __extends(HDRRenderingPipeline, _super);
  32844. /**
  32845. * @constructor
  32846. * @param {string} name - The rendering pipeline name
  32847. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32848. * @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)
  32849. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  32850. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32851. */
  32852. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  32853. var _this = this;
  32854. if (originalPostProcess === void 0) { originalPostProcess = null; }
  32855. _super.call(this, scene.getEngine(), name);
  32856. /**
  32857. * Public members
  32858. */
  32859. // Gaussian Blur
  32860. /**
  32861. * Gaussian blur coefficient
  32862. * @type {number}
  32863. */
  32864. this.gaussCoeff = 0.3;
  32865. /**
  32866. * Gaussian blur mean
  32867. * @type {number}
  32868. */
  32869. this.gaussMean = 1.0;
  32870. /**
  32871. * Gaussian blur standard deviation
  32872. * @type {number}
  32873. */
  32874. this.gaussStandDev = 0.8;
  32875. // HDR
  32876. /**
  32877. * Exposure, controls the overall intensity of the pipeline
  32878. * @type {number}
  32879. */
  32880. this.exposure = 1.0;
  32881. /**
  32882. * Minimum luminance that the post-process can output. Luminance is >= 0
  32883. * @type {number}
  32884. */
  32885. this.minimumLuminance = 1.0;
  32886. /**
  32887. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  32888. * @type {number}
  32889. */
  32890. this.maximumLuminance = 1e20;
  32891. /**
  32892. * Increase rate for luminance: eye adaptation speed to dark
  32893. * @type {number}
  32894. */
  32895. this.luminanceIncreaserate = 0.5;
  32896. /**
  32897. * Decrease rate for luminance: eye adaptation speed to bright
  32898. * @type {number}
  32899. */
  32900. this.luminanceDecreaseRate = 0.5;
  32901. // Bright pass
  32902. /**
  32903. * Minimum luminance needed to compute HDR
  32904. * @type {number}
  32905. */
  32906. this.brightThreshold = 0.8;
  32907. this._needUpdate = true;
  32908. this._scene = scene;
  32909. // Bright pass
  32910. this._createBrightPassPostProcess(scene, ratio);
  32911. // Down sample X4
  32912. this._createDownSampleX4PostProcess(scene, ratio);
  32913. // Create gaussian blur post-processes
  32914. this._createGaussianBlurPostProcess(scene, ratio);
  32915. // Texture adder
  32916. this._createTextureAdderPostProcess(scene, ratio);
  32917. // Luminance generator
  32918. this._createLuminanceGeneratorPostProcess(scene);
  32919. // HDR
  32920. this._createHDRPostProcess(scene, ratio);
  32921. // Pass postprocess
  32922. if (originalPostProcess === null) {
  32923. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32924. }
  32925. else {
  32926. this._originalPostProcess = originalPostProcess;
  32927. }
  32928. // Configure pipeline
  32929. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  32930. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  32931. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  32932. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  32933. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  32934. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  32935. var addDownSamplerPostProcess = function (id) {
  32936. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  32937. };
  32938. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  32939. addDownSamplerPostProcess(i);
  32940. }
  32941. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  32942. // Finish
  32943. scene.postProcessRenderPipelineManager.addPipeline(this);
  32944. if (cameras !== null) {
  32945. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32946. }
  32947. this.update();
  32948. }
  32949. /**
  32950. * Tells the pipeline to update its post-processes
  32951. */
  32952. HDRRenderingPipeline.prototype.update = function () {
  32953. this._needUpdate = true;
  32954. };
  32955. /**
  32956. * Returns the current calculated luminance
  32957. */
  32958. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  32959. return this._hdrCurrentLuminance;
  32960. };
  32961. /**
  32962. * Returns the currently drawn luminance
  32963. */
  32964. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  32965. return this._hdrOutputLuminance;
  32966. };
  32967. /**
  32968. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  32969. */
  32970. HDRRenderingPipeline.prototype.dispose = function () {
  32971. this._originalPostProcess = undefined;
  32972. this._brightPassPostProcess = undefined;
  32973. this._downSampleX4PostProcess = undefined;
  32974. this._guassianBlurHPostProcess = undefined;
  32975. this._guassianBlurVPostProcess = undefined;
  32976. this._textureAdderPostProcess = undefined;
  32977. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  32978. this._downSamplePostProcesses[i] = undefined;
  32979. }
  32980. this._hdrPostProcess = undefined;
  32981. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32982. };
  32983. /**
  32984. * Creates the HDR post-process and computes the luminance adaptation
  32985. */
  32986. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  32987. var _this = this;
  32988. var hdrLastLuminance = 0.0;
  32989. this._hdrOutputLuminance = -1.0;
  32990. this._hdrCurrentLuminance = 1.0;
  32991. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  32992. this._hdrPostProcess.onApply = function (effect) {
  32993. if (_this._hdrOutputLuminance < 0.0) {
  32994. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  32995. }
  32996. else {
  32997. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  32998. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  32999. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33000. }
  33001. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33002. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33003. }
  33004. else {
  33005. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33006. }
  33007. }
  33008. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33009. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33010. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33011. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33012. effect.setFloat("exposure", _this.exposure);
  33013. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33014. _this._needUpdate = false;
  33015. };
  33016. };
  33017. /**
  33018. * Texture Adder post-process
  33019. */
  33020. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33021. var _this = this;
  33022. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33023. this._textureAdderPostProcess.onApply = function (effect) {
  33024. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33025. };
  33026. };
  33027. /**
  33028. * Down sample X4 post-process
  33029. */
  33030. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33031. var _this = this;
  33032. var downSampleX4Offsets = new Array(32);
  33033. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33034. this._downSampleX4PostProcess.onApply = function (effect) {
  33035. if (_this._needUpdate) {
  33036. var id = 0;
  33037. for (var i = -2; i < 2; i++) {
  33038. for (var j = -2; j < 2; j++) {
  33039. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33040. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33041. id += 2;
  33042. }
  33043. }
  33044. }
  33045. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33046. };
  33047. };
  33048. /**
  33049. * Bright pass post-process
  33050. */
  33051. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33052. var _this = this;
  33053. var brightOffsets = new Array(8);
  33054. var brightPassCallback = function (effect) {
  33055. if (_this._needUpdate) {
  33056. var sU = (1.0 / _this._brightPassPostProcess.width);
  33057. var sV = (1.0 / _this._brightPassPostProcess.height);
  33058. brightOffsets[0] = -0.5 * sU;
  33059. brightOffsets[1] = 0.5 * sV;
  33060. brightOffsets[2] = 0.5 * sU;
  33061. brightOffsets[3] = 0.5 * sV;
  33062. brightOffsets[4] = -0.5 * sU;
  33063. brightOffsets[5] = -0.5 * sV;
  33064. brightOffsets[6] = 0.5 * sU;
  33065. brightOffsets[7] = -0.5 * sV;
  33066. }
  33067. effect.setArray2("dsOffsets", brightOffsets);
  33068. effect.setFloat("brightThreshold", _this.brightThreshold);
  33069. };
  33070. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33071. this._brightPassPostProcess.onApply = brightPassCallback;
  33072. };
  33073. /**
  33074. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33075. */
  33076. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33077. var _this = this;
  33078. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33079. var luminanceOffsets = new Array(8);
  33080. var downSampleOffsets = new Array(18);
  33081. var halfDestPixelSize;
  33082. this._downSamplePostProcesses = new Array(lumSteps);
  33083. // Utils for luminance
  33084. var luminanceUpdateSourceOffsets = function (width, height) {
  33085. var sU = (1.0 / width);
  33086. var sV = (1.0 / height);
  33087. luminanceOffsets[0] = -0.5 * sU;
  33088. luminanceOffsets[1] = 0.5 * sV;
  33089. luminanceOffsets[2] = 0.5 * sU;
  33090. luminanceOffsets[3] = 0.5 * sV;
  33091. luminanceOffsets[4] = -0.5 * sU;
  33092. luminanceOffsets[5] = -0.5 * sV;
  33093. luminanceOffsets[6] = 0.5 * sU;
  33094. luminanceOffsets[7] = -0.5 * sV;
  33095. };
  33096. var luminanceUpdateDestOffsets = function (width, height) {
  33097. var id = 0;
  33098. for (var x = -1; x < 2; x++) {
  33099. for (var y = -1; y < 2; y++) {
  33100. downSampleOffsets[id] = (x) / width;
  33101. downSampleOffsets[id + 1] = (y) / height;
  33102. id += 2;
  33103. }
  33104. }
  33105. };
  33106. // Luminance callback
  33107. var luminanceCallback = function (effect) {
  33108. if (_this._needUpdate) {
  33109. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33110. }
  33111. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33112. effect.setArray2("lumOffsets", luminanceOffsets);
  33113. };
  33114. // Down sample callbacks
  33115. var downSampleCallback = function (indice) {
  33116. var i = indice;
  33117. return function (effect) {
  33118. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33119. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33120. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33121. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33122. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33123. effect.setArray2("dsOffsets", downSampleOffsets);
  33124. };
  33125. };
  33126. var downSampleAfterRenderCallback = function (effect) {
  33127. // Unpack result
  33128. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33129. 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);
  33130. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33131. };
  33132. // Create luminance post-process
  33133. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33134. 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);
  33135. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33136. // Create down sample post-processes
  33137. for (var i = lumSteps - 2; i >= 0; i--) {
  33138. var length = Math.pow(3, i);
  33139. ratio = { width: length, height: length };
  33140. var defines = "#define DOWN_SAMPLE\n";
  33141. if (i === 0) {
  33142. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33143. }
  33144. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33145. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33146. if (i === 0) {
  33147. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33148. }
  33149. }
  33150. };
  33151. /**
  33152. * Gaussian blur post-processes. Horizontal and Vertical
  33153. */
  33154. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33155. var _this = this;
  33156. var blurOffsetsW = new Array(9);
  33157. var blurOffsetsH = new Array(9);
  33158. var blurWeights = new Array(9);
  33159. var uniforms = ["blurOffsets", "blurWeights"];
  33160. // Utils for gaussian blur
  33161. var calculateBlurOffsets = function (height) {
  33162. var lastOutputDimensions = {
  33163. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33164. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33165. };
  33166. for (var i = 0; i < 9; i++) {
  33167. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33168. if (height) {
  33169. blurOffsetsH[i] = value;
  33170. }
  33171. else {
  33172. blurOffsetsW[i] = value;
  33173. }
  33174. }
  33175. };
  33176. var calculateWeights = function () {
  33177. var x = 0.0;
  33178. for (var i = 0; i < 9; i++) {
  33179. x = (i - 4.0) / 4.0;
  33180. 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));
  33181. }
  33182. };
  33183. // Callback
  33184. var gaussianBlurCallback = function (height) {
  33185. return function (effect) {
  33186. if (_this._needUpdate) {
  33187. calculateWeights();
  33188. calculateBlurOffsets(height);
  33189. }
  33190. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33191. effect.setArray("blurWeights", blurWeights);
  33192. };
  33193. };
  33194. // Create horizontal gaussian blur post-processes
  33195. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33196. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33197. // Create vertical gaussian blur post-process
  33198. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33199. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33200. };
  33201. // Luminance generator
  33202. HDRRenderingPipeline.LUM_STEPS = 6;
  33203. return HDRRenderingPipeline;
  33204. })(BABYLON.PostProcessRenderPipeline);
  33205. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33206. })(BABYLON || (BABYLON = {}));
  33207. 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}","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}"};
  33208. 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={}));";
  33209. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  33210. module.exports = BABYLON;
  33211. };