babylon.2.2.max.js 1.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.equalsFloats = function (r, g, b) {
  56. return this.r === r && this.g === g && this.b === b;
  57. };
  58. Color3.prototype.scale = function (scale) {
  59. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  60. };
  61. Color3.prototype.scaleToRef = function (scale, result) {
  62. result.r = this.r * scale;
  63. result.g = this.g * scale;
  64. result.b = this.b * scale;
  65. return this;
  66. };
  67. Color3.prototype.add = function (otherColor) {
  68. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  69. };
  70. Color3.prototype.addToRef = function (otherColor, result) {
  71. result.r = this.r + otherColor.r;
  72. result.g = this.g + otherColor.g;
  73. result.b = this.b + otherColor.b;
  74. return this;
  75. };
  76. Color3.prototype.subtract = function (otherColor) {
  77. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  78. };
  79. Color3.prototype.subtractToRef = function (otherColor, result) {
  80. result.r = this.r - otherColor.r;
  81. result.g = this.g - otherColor.g;
  82. result.b = this.b - otherColor.b;
  83. return this;
  84. };
  85. Color3.prototype.clone = function () {
  86. return new Color3(this.r, this.g, this.b);
  87. };
  88. Color3.prototype.copyFrom = function (source) {
  89. this.r = source.r;
  90. this.g = source.g;
  91. this.b = source.b;
  92. return this;
  93. };
  94. Color3.prototype.copyFromFloats = function (r, g, b) {
  95. this.r = r;
  96. this.g = g;
  97. this.b = b;
  98. return this;
  99. };
  100. Color3.prototype.toHexString = function () {
  101. var intR = (this.r * 255) | 0;
  102. var intG = (this.g * 255) | 0;
  103. var intB = (this.b * 255) | 0;
  104. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB);
  105. };
  106. // Statics
  107. Color3.FromHexString = function (hex) {
  108. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  109. BABYLON.Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  110. return new Color3(0, 0, 0);
  111. }
  112. var r = parseInt(hex.substring(1, 3), 16);
  113. var g = parseInt(hex.substring(3, 5), 16);
  114. var b = parseInt(hex.substring(5, 7), 16);
  115. return Color3.FromInts(r, g, b);
  116. };
  117. Color3.FromArray = function (array, offset) {
  118. if (offset === void 0) { offset = 0; }
  119. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  120. };
  121. Color3.FromInts = function (r, g, b) {
  122. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  123. };
  124. Color3.Lerp = function (start, end, amount) {
  125. var r = start.r + ((end.r - start.r) * amount);
  126. var g = start.g + ((end.g - start.g) * amount);
  127. var b = start.b + ((end.b - start.b) * amount);
  128. return new Color3(r, g, b);
  129. };
  130. Color3.Red = function () { return new Color3(1, 0, 0); };
  131. Color3.Green = function () { return new Color3(0, 1, 0); };
  132. Color3.Blue = function () { return new Color3(0, 0, 1); };
  133. Color3.Black = function () { return new Color3(0, 0, 0); };
  134. Color3.White = function () { return new Color3(1, 1, 1); };
  135. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  136. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  137. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  138. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  139. return Color3;
  140. })();
  141. BABYLON.Color3 = Color3;
  142. var Color4 = (function () {
  143. function Color4(r, g, b, a) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. this.a = a;
  148. }
  149. // Operators
  150. Color4.prototype.addInPlace = function (right) {
  151. this.r += right.r;
  152. this.g += right.g;
  153. this.b += right.b;
  154. this.a += right.a;
  155. return this;
  156. };
  157. Color4.prototype.asArray = function () {
  158. var result = [];
  159. this.toArray(result, 0);
  160. return result;
  161. };
  162. Color4.prototype.toArray = function (array, index) {
  163. if (index === undefined) {
  164. index = 0;
  165. }
  166. array[index] = this.r;
  167. array[index + 1] = this.g;
  168. array[index + 2] = this.b;
  169. array[index + 3] = this.a;
  170. return this;
  171. };
  172. Color4.prototype.add = function (right) {
  173. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  174. };
  175. Color4.prototype.subtract = function (right) {
  176. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  177. };
  178. Color4.prototype.subtractToRef = function (right, result) {
  179. result.r = this.r - right.r;
  180. result.g = this.g - right.g;
  181. result.b = this.b - right.b;
  182. result.a = this.a - right.a;
  183. return this;
  184. };
  185. Color4.prototype.scale = function (scale) {
  186. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  187. };
  188. Color4.prototype.scaleToRef = function (scale, result) {
  189. result.r = this.r * scale;
  190. result.g = this.g * scale;
  191. result.b = this.b * scale;
  192. result.a = this.a * scale;
  193. return this;
  194. };
  195. Color4.prototype.toString = function () {
  196. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  197. };
  198. Color4.prototype.clone = function () {
  199. return new Color4(this.r, this.g, this.b, this.a);
  200. };
  201. Color4.prototype.copyFrom = function (source) {
  202. this.r = source.r;
  203. this.g = source.g;
  204. this.b = source.b;
  205. this.a = source.a;
  206. return this;
  207. };
  208. Color4.prototype.toHexString = function () {
  209. var intR = (this.r * 255) | 0;
  210. var intG = (this.g * 255) | 0;
  211. var intB = (this.b * 255) | 0;
  212. var intA = (this.a * 255) | 0;
  213. return "#" + BABYLON.Tools.ToHex(intR) + BABYLON.Tools.ToHex(intG) + BABYLON.Tools.ToHex(intB) + BABYLON.Tools.ToHex(intA);
  214. };
  215. // Statics
  216. Color4.FromHexString = function (hex) {
  217. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  218. BABYLON.Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  219. return new Color4(0, 0, 0, 0);
  220. }
  221. var r = parseInt(hex.substring(1, 3), 16);
  222. var g = parseInt(hex.substring(3, 5), 16);
  223. var b = parseInt(hex.substring(5, 7), 16);
  224. var a = parseInt(hex.substring(7, 9), 16);
  225. return Color4.FromInts(r, g, b, a);
  226. };
  227. Color4.Lerp = function (left, right, amount) {
  228. var result = new Color4(0, 0, 0, 0);
  229. Color4.LerpToRef(left, right, amount, result);
  230. return result;
  231. };
  232. Color4.LerpToRef = function (left, right, amount, result) {
  233. result.r = left.r + (right.r - left.r) * amount;
  234. result.g = left.g + (right.g - left.g) * amount;
  235. result.b = left.b + (right.b - left.b) * amount;
  236. result.a = left.a + (right.a - left.a) * amount;
  237. };
  238. Color4.FromArray = function (array, offset) {
  239. if (offset === void 0) { offset = 0; }
  240. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  241. };
  242. Color4.FromInts = function (r, g, b, a) {
  243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  244. };
  245. return Color4;
  246. })();
  247. BABYLON.Color4 = Color4;
  248. var Vector2 = (function () {
  249. function Vector2(x, y) {
  250. this.x = x;
  251. this.y = y;
  252. }
  253. Vector2.prototype.toString = function () {
  254. return "{X: " + this.x + " Y:" + this.y + "}";
  255. };
  256. // Operators
  257. Vector2.prototype.toArray = function (array, index) {
  258. if (index === void 0) { index = 0; }
  259. array[index] = this.x;
  260. array[index + 1] = this.y;
  261. return this;
  262. };
  263. Vector2.prototype.asArray = function () {
  264. var result = [];
  265. this.toArray(result, 0);
  266. return result;
  267. };
  268. Vector2.prototype.copyFrom = function (source) {
  269. this.x = source.x;
  270. this.y = source.y;
  271. return this;
  272. };
  273. Vector2.prototype.copyFromFloats = function (x, y) {
  274. this.x = x;
  275. this.y = y;
  276. return this;
  277. };
  278. Vector2.prototype.add = function (otherVector) {
  279. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  280. };
  281. Vector2.prototype.addVector3 = function (otherVector) {
  282. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  283. };
  284. Vector2.prototype.subtract = function (otherVector) {
  285. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  286. };
  287. Vector2.prototype.subtractInPlace = function (otherVector) {
  288. this.x -= otherVector.x;
  289. this.y -= otherVector.y;
  290. return this;
  291. };
  292. Vector2.prototype.multiplyInPlace = function (otherVector) {
  293. this.x *= otherVector.x;
  294. this.y *= otherVector.y;
  295. return this;
  296. };
  297. Vector2.prototype.multiply = function (otherVector) {
  298. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  299. };
  300. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  301. result.x = this.x * otherVector.x;
  302. result.y = this.y * otherVector.y;
  303. return this;
  304. };
  305. Vector2.prototype.multiplyByFloats = function (x, y) {
  306. return new Vector2(this.x * x, this.y * y);
  307. };
  308. Vector2.prototype.divide = function (otherVector) {
  309. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  310. };
  311. Vector2.prototype.divideToRef = function (otherVector, result) {
  312. result.x = this.x / otherVector.x;
  313. result.y = this.y / otherVector.y;
  314. return this;
  315. };
  316. Vector2.prototype.negate = function () {
  317. return new Vector2(-this.x, -this.y);
  318. };
  319. Vector2.prototype.scaleInPlace = function (scale) {
  320. this.x *= scale;
  321. this.y *= scale;
  322. return this;
  323. };
  324. Vector2.prototype.scale = function (scale) {
  325. return new Vector2(this.x * scale, this.y * scale);
  326. };
  327. Vector2.prototype.equals = function (otherVector) {
  328. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  329. };
  330. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  331. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  332. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon);
  333. };
  334. // Properties
  335. Vector2.prototype.length = function () {
  336. return Math.sqrt(this.x * this.x + this.y * this.y);
  337. };
  338. Vector2.prototype.lengthSquared = function () {
  339. return (this.x * this.x + this.y * this.y);
  340. };
  341. // Methods
  342. Vector2.prototype.normalize = function () {
  343. var len = this.length();
  344. if (len === 0)
  345. return this;
  346. var num = 1.0 / len;
  347. this.x *= num;
  348. this.y *= num;
  349. return this;
  350. };
  351. Vector2.prototype.clone = function () {
  352. return new Vector2(this.x, this.y);
  353. };
  354. // Statics
  355. Vector2.Zero = function () {
  356. return new Vector2(0, 0);
  357. };
  358. Vector2.FromArray = function (array, offset) {
  359. if (offset === void 0) { offset = 0; }
  360. return new Vector2(array[offset], array[offset + 1]);
  361. };
  362. Vector2.FromArrayToRef = function (array, offset, result) {
  363. result.x = array[offset];
  364. result.y = array[offset + 1];
  365. };
  366. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  367. var squared = amount * amount;
  368. var cubed = amount * squared;
  369. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  370. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  371. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  372. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  373. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  374. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Clamp = function (value, min, max) {
  378. var x = value.x;
  379. x = (x > max.x) ? max.x : x;
  380. x = (x < min.x) ? min.x : x;
  381. var y = value.y;
  382. y = (y > max.y) ? max.y : y;
  383. y = (y < min.y) ? min.y : y;
  384. return new Vector2(x, y);
  385. };
  386. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  387. var squared = amount * amount;
  388. var cubed = amount * squared;
  389. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  390. var part2 = (-2.0 * cubed) + (3.0 * squared);
  391. var part3 = (cubed - (2.0 * squared)) + amount;
  392. var part4 = cubed - squared;
  393. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  394. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Lerp = function (start, end, amount) {
  398. var x = start.x + ((end.x - start.x) * amount);
  399. var y = start.y + ((end.y - start.y) * amount);
  400. return new Vector2(x, y);
  401. };
  402. Vector2.Dot = function (left, right) {
  403. return left.x * right.x + left.y * right.y;
  404. };
  405. Vector2.Normalize = function (vector) {
  406. var newVector = vector.clone();
  407. newVector.normalize();
  408. return newVector;
  409. };
  410. Vector2.Minimize = function (left, right) {
  411. var x = (left.x < right.x) ? left.x : right.x;
  412. var y = (left.y < right.y) ? left.y : right.y;
  413. return new Vector2(x, y);
  414. };
  415. Vector2.Maximize = function (left, right) {
  416. var x = (left.x > right.x) ? left.x : right.x;
  417. var y = (left.y > right.y) ? left.y : right.y;
  418. return new Vector2(x, y);
  419. };
  420. Vector2.Transform = function (vector, transformation) {
  421. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  422. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  423. return new Vector2(x, y);
  424. };
  425. Vector2.Distance = function (value1, value2) {
  426. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  427. };
  428. Vector2.DistanceSquared = function (value1, value2) {
  429. var x = value1.x - value2.x;
  430. var y = value1.y - value2.y;
  431. return (x * x) + (y * y);
  432. };
  433. return Vector2;
  434. })();
  435. BABYLON.Vector2 = Vector2;
  436. var Vector3 = (function () {
  437. function Vector3(x, y, z) {
  438. this.x = x;
  439. this.y = y;
  440. this.z = z;
  441. }
  442. Vector3.prototype.toString = function () {
  443. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  444. };
  445. // Operators
  446. Vector3.prototype.asArray = function () {
  447. var result = [];
  448. this.toArray(result, 0);
  449. return result;
  450. };
  451. Vector3.prototype.toArray = function (array, index) {
  452. if (index === void 0) { index = 0; }
  453. array[index] = this.x;
  454. array[index + 1] = this.y;
  455. array[index + 2] = this.z;
  456. return this;
  457. };
  458. Vector3.prototype.toQuaternion = function () {
  459. var result = new Quaternion(0, 0, 0, 1);
  460. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  461. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  462. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  463. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  464. var cosy = Math.cos(this.y * 0.5);
  465. var siny = Math.sin(this.y * 0.5);
  466. result.x = coszMinusx * siny;
  467. result.y = -sinzMinusx * siny;
  468. result.z = sinxPlusz * cosy;
  469. result.w = cosxPlusz * cosy;
  470. return result;
  471. };
  472. Vector3.prototype.addInPlace = function (otherVector) {
  473. this.x += otherVector.x;
  474. this.y += otherVector.y;
  475. this.z += otherVector.z;
  476. return this;
  477. };
  478. Vector3.prototype.add = function (otherVector) {
  479. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  480. };
  481. Vector3.prototype.addToRef = function (otherVector, result) {
  482. result.x = this.x + otherVector.x;
  483. result.y = this.y + otherVector.y;
  484. result.z = this.z + otherVector.z;
  485. return this;
  486. };
  487. Vector3.prototype.subtractInPlace = function (otherVector) {
  488. this.x -= otherVector.x;
  489. this.y -= otherVector.y;
  490. this.z -= otherVector.z;
  491. return this;
  492. };
  493. Vector3.prototype.subtract = function (otherVector) {
  494. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  495. };
  496. Vector3.prototype.subtractToRef = function (otherVector, result) {
  497. result.x = this.x - otherVector.x;
  498. result.y = this.y - otherVector.y;
  499. result.z = this.z - otherVector.z;
  500. return this;
  501. };
  502. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  503. return new Vector3(this.x - x, this.y - y, this.z - z);
  504. };
  505. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  506. result.x = this.x - x;
  507. result.y = this.y - y;
  508. result.z = this.z - z;
  509. return this;
  510. };
  511. Vector3.prototype.negate = function () {
  512. return new Vector3(-this.x, -this.y, -this.z);
  513. };
  514. Vector3.prototype.scaleInPlace = function (scale) {
  515. this.x *= scale;
  516. this.y *= scale;
  517. this.z *= scale;
  518. return this;
  519. };
  520. Vector3.prototype.scale = function (scale) {
  521. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  522. };
  523. Vector3.prototype.scaleToRef = function (scale, result) {
  524. result.x = this.x * scale;
  525. result.y = this.y * scale;
  526. result.z = this.z * scale;
  527. };
  528. Vector3.prototype.equals = function (otherVector) {
  529. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  530. };
  531. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  532. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  533. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon);
  534. };
  535. Vector3.prototype.equalsToFloats = function (x, y, z) {
  536. return this.x === x && this.y === y && this.z === z;
  537. };
  538. Vector3.prototype.multiplyInPlace = function (otherVector) {
  539. this.x *= otherVector.x;
  540. this.y *= otherVector.y;
  541. this.z *= otherVector.z;
  542. return this;
  543. };
  544. Vector3.prototype.multiply = function (otherVector) {
  545. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  546. };
  547. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  548. result.x = this.x * otherVector.x;
  549. result.y = this.y * otherVector.y;
  550. result.z = this.z * otherVector.z;
  551. return this;
  552. };
  553. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  554. return new Vector3(this.x * x, this.y * y, this.z * z);
  555. };
  556. Vector3.prototype.divide = function (otherVector) {
  557. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  558. };
  559. Vector3.prototype.divideToRef = function (otherVector, result) {
  560. result.x = this.x / otherVector.x;
  561. result.y = this.y / otherVector.y;
  562. result.z = this.z / otherVector.z;
  563. return this;
  564. };
  565. Vector3.prototype.MinimizeInPlace = function (other) {
  566. if (other.x < this.x)
  567. this.x = other.x;
  568. if (other.y < this.y)
  569. this.y = other.y;
  570. if (other.z < this.z)
  571. this.z = other.z;
  572. return this;
  573. };
  574. Vector3.prototype.MaximizeInPlace = function (other) {
  575. if (other.x > this.x)
  576. this.x = other.x;
  577. if (other.y > this.y)
  578. this.y = other.y;
  579. if (other.z > this.z)
  580. this.z = other.z;
  581. return this;
  582. };
  583. // Properties
  584. Vector3.prototype.length = function () {
  585. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  586. };
  587. Vector3.prototype.lengthSquared = function () {
  588. return (this.x * this.x + this.y * this.y + this.z * this.z);
  589. };
  590. // Methods
  591. Vector3.prototype.normalize = function () {
  592. var len = this.length();
  593. if (len === 0 || len === 1.0)
  594. return this;
  595. var num = 1.0 / len;
  596. this.x *= num;
  597. this.y *= num;
  598. this.z *= num;
  599. return this;
  600. };
  601. Vector3.prototype.clone = function () {
  602. return new Vector3(this.x, this.y, this.z);
  603. };
  604. Vector3.prototype.copyFrom = function (source) {
  605. this.x = source.x;
  606. this.y = source.y;
  607. this.z = source.z;
  608. return this;
  609. };
  610. Vector3.prototype.copyFromFloats = function (x, y, z) {
  611. this.x = x;
  612. this.y = y;
  613. this.z = z;
  614. return this;
  615. };
  616. // Statics
  617. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  618. var d0 = Vector3.Dot(vector0, axis) - size;
  619. var d1 = Vector3.Dot(vector1, axis) - size;
  620. var s = d0 / (d0 - d1);
  621. return s;
  622. };
  623. Vector3.FromArray = function (array, offset) {
  624. if (!offset) {
  625. offset = 0;
  626. }
  627. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  628. };
  629. Vector3.FromFloatArray = function (array, offset) {
  630. if (!offset) {
  631. offset = 0;
  632. }
  633. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  634. };
  635. Vector3.FromArrayToRef = function (array, offset, result) {
  636. result.x = array[offset];
  637. result.y = array[offset + 1];
  638. result.z = array[offset + 2];
  639. };
  640. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  641. result.x = array[offset];
  642. result.y = array[offset + 1];
  643. result.z = array[offset + 2];
  644. };
  645. Vector3.FromFloatsToRef = function (x, y, z, result) {
  646. result.x = x;
  647. result.y = y;
  648. result.z = z;
  649. };
  650. Vector3.Zero = function () {
  651. return new Vector3(0, 0, 0);
  652. };
  653. Vector3.Up = function () {
  654. return new Vector3(0, 1.0, 0);
  655. };
  656. Vector3.TransformCoordinates = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  662. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  663. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  664. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  665. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  666. result.x = x / w;
  667. result.y = y / w;
  668. result.z = z / w;
  669. };
  670. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  671. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  672. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  673. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  674. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  675. result.x = rx / rw;
  676. result.y = ry / rw;
  677. result.z = rz / rw;
  678. };
  679. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  680. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  681. var m0 = SIMD.float32x4.load(transformation.m, 0);
  682. var m1 = SIMD.float32x4.load(transformation.m, 4);
  683. var m2 = SIMD.float32x4.load(transformation.m, 8);
  684. var m3 = SIMD.float32x4.load(transformation.m, 12);
  685. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  686. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  687. SIMD.float32x4.storeXYZ(result._data, 0, r);
  688. };
  689. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  690. var v0 = SIMD.float32x4.splat(x);
  691. var v1 = SIMD.float32x4.splat(y);
  692. var v2 = SIMD.float32x4.splat(z);
  693. var m0 = SIMD.float32x4.load(transformation.m, 0);
  694. var m1 = SIMD.float32x4.load(transformation.m, 4);
  695. var m2 = SIMD.float32x4.load(transformation.m, 8);
  696. var m3 = SIMD.float32x4.load(transformation.m, 12);
  697. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  698. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  699. SIMD.float32x4.storeXYZ(result._data, 0, r);
  700. };
  701. Vector3.TransformNormal = function (vector, transformation) {
  702. var result = Vector3.Zero();
  703. Vector3.TransformNormalToRef(vector, transformation, result);
  704. return result;
  705. };
  706. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  707. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  708. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  709. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  710. };
  711. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  712. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  713. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  714. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  715. };
  716. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  717. var squared = amount * amount;
  718. var cubed = amount * squared;
  719. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  720. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  721. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  722. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  723. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  724. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  725. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  726. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  727. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  728. return new Vector3(x, y, z);
  729. };
  730. Vector3.Clamp = function (value, min, max) {
  731. var x = value.x;
  732. x = (x > max.x) ? max.x : x;
  733. x = (x < min.x) ? min.x : x;
  734. var y = value.y;
  735. y = (y > max.y) ? max.y : y;
  736. y = (y < min.y) ? min.y : y;
  737. var z = value.z;
  738. z = (z > max.z) ? max.z : z;
  739. z = (z < min.z) ? min.z : z;
  740. return new Vector3(x, y, z);
  741. };
  742. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  743. var squared = amount * amount;
  744. var cubed = amount * squared;
  745. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  746. var part2 = (-2.0 * cubed) + (3.0 * squared);
  747. var part3 = (cubed - (2.0 * squared)) + amount;
  748. var part4 = cubed - squared;
  749. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  750. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  751. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  752. return new Vector3(x, y, z);
  753. };
  754. Vector3.Lerp = function (start, end, amount) {
  755. var x = start.x + ((end.x - start.x) * amount);
  756. var y = start.y + ((end.y - start.y) * amount);
  757. var z = start.z + ((end.z - start.z) * amount);
  758. return new Vector3(x, y, z);
  759. };
  760. Vector3.Dot = function (left, right) {
  761. return (left.x * right.x + left.y * right.y + left.z * right.z);
  762. };
  763. Vector3.Cross = function (left, right) {
  764. var result = Vector3.Zero();
  765. Vector3.CrossToRef(left, right, result);
  766. return result;
  767. };
  768. Vector3.CrossToRef = function (left, right, result) {
  769. result.x = left.y * right.z - left.z * right.y;
  770. result.y = left.z * right.x - left.x * right.z;
  771. result.z = left.x * right.y - left.y * right.x;
  772. };
  773. Vector3.Normalize = function (vector) {
  774. var result = Vector3.Zero();
  775. Vector3.NormalizeToRef(vector, result);
  776. return result;
  777. };
  778. Vector3.NormalizeToRef = function (vector, result) {
  779. result.copyFrom(vector);
  780. result.normalize();
  781. };
  782. Vector3.Project = function (vector, world, transform, viewport) {
  783. var cw = viewport.width;
  784. var ch = viewport.height;
  785. var cx = viewport.x;
  786. var cy = viewport.y;
  787. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  788. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  789. return Vector3.TransformCoordinates(vector, finalMatrix);
  790. };
  791. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  792. var matrix = world.multiply(transform);
  793. matrix.invert();
  794. source.x = source.x / viewportWidth * 2 - 1;
  795. source.y = -(source.y / viewportHeight * 2 - 1);
  796. var vector = Vector3.TransformCoordinates(source, matrix);
  797. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  798. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  799. vector = vector.scale(1.0 / num);
  800. }
  801. return vector;
  802. };
  803. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  804. var matrix = world.multiply(view).multiply(projection);
  805. matrix.invert();
  806. source.x = source.x / viewportWidth * 2 - 1;
  807. source.y = -(source.y / viewportHeight * 2 - 1);
  808. var vector = Vector3.TransformCoordinates(source, matrix);
  809. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  810. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  811. vector = vector.scale(1.0 / num);
  812. }
  813. return vector;
  814. };
  815. Vector3.Minimize = function (left, right) {
  816. var min = left.clone();
  817. min.MinimizeInPlace(right);
  818. return min;
  819. };
  820. Vector3.Maximize = function (left, right) {
  821. var max = left.clone();
  822. max.MaximizeInPlace(right);
  823. return max;
  824. };
  825. Vector3.Distance = function (value1, value2) {
  826. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  827. };
  828. Vector3.DistanceSquared = function (value1, value2) {
  829. var x = value1.x - value2.x;
  830. var y = value1.y - value2.y;
  831. var z = value1.z - value2.z;
  832. return (x * x) + (y * y) + (z * z);
  833. };
  834. Vector3.Center = function (value1, value2) {
  835. var center = value1.add(value2);
  836. center.scaleInPlace(0.5);
  837. return center;
  838. };
  839. /**
  840. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  841. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  842. * to something in order to rotate it from its local system to the given target system.
  843. */
  844. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  845. var u = Vector3.Normalize(axis1);
  846. var w = Vector3.Normalize(axis3);
  847. // world axis
  848. var X = Axis.X;
  849. var Y = Axis.Y;
  850. // equation unknowns and vars
  851. var yaw = 0.0;
  852. var pitch = 0.0;
  853. var roll = 0.0;
  854. var x = 0.0;
  855. var y = 0.0;
  856. var z = 0.0;
  857. var t = 0.0;
  858. var sign = -1.0;
  859. var nbRevert = 0;
  860. var cross;
  861. var dot = 0.0;
  862. // step 1 : rotation around w
  863. // Rv3(u) = u1, and u1 belongs to plane xOz
  864. // Rv3(w) = w1 = w invariant
  865. var u1;
  866. var v1;
  867. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  868. z = 1.0;
  869. }
  870. else if (BABYLON.Tools.WithinEpsilon(w.x, 0, BABYLON.Engine.Epsilon)) {
  871. x = 1.0;
  872. }
  873. else {
  874. t = w.z / w.x;
  875. x = -t * Math.sqrt(1 / (1 + t * t));
  876. z = Math.sqrt(1 / (1 + t * t));
  877. }
  878. u1 = new Vector3(x, y, z);
  879. u1.normalize();
  880. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  881. v1.normalize();
  882. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  883. cross.normalize();
  884. if (Vector3.Dot(w, cross) < 0) {
  885. sign = 1.0;
  886. }
  887. dot = Vector3.Dot(u, u1);
  888. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  889. roll = Math.acos(dot) * sign;
  890. if (Vector3.Dot(u1, X) < 0) {
  891. roll = Math.PI + roll;
  892. u1 = u1.scaleInPlace(-1);
  893. v1 = v1.scaleInPlace(-1);
  894. nbRevert++;
  895. }
  896. // step 2 : rotate around u1
  897. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  898. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  899. var w2;
  900. var v2;
  901. x = 0.0;
  902. y = 0.0;
  903. z = 0.0;
  904. sign = -1;
  905. if (BABYLON.Tools.WithinEpsilon(w.z, 0, BABYLON.Engine.Epsilon)) {
  906. x = 1.0;
  907. }
  908. else {
  909. t = u1.z / u1.x;
  910. x = -t * Math.sqrt(1 / (1 + t * t));
  911. z = Math.sqrt(1 / (1 + t * t));
  912. }
  913. w2 = new Vector3(x, y, z);
  914. w2.normalize();
  915. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  916. v2.normalize();
  917. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  918. cross.normalize();
  919. if (Vector3.Dot(u1, cross) < 0) {
  920. sign = 1.0;
  921. }
  922. dot = Vector3.Dot(w, w2);
  923. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  924. pitch = Math.acos(dot) * sign;
  925. if (Vector3.Dot(v2, Y) < 0) {
  926. pitch = Math.PI + pitch;
  927. v2 = v2.scaleInPlace(-1);
  928. w2 = w2.scaleInPlace(-1);
  929. nbRevert++;
  930. }
  931. // step 3 : rotate around v2
  932. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  933. sign = -1;
  934. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  935. cross.normalize();
  936. if (Vector3.Dot(cross, Y) < 0) {
  937. sign = 1.0;
  938. }
  939. dot = Vector3.Dot(u1, X);
  940. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  941. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  942. if (dot < 0 && nbRevert < 2) {
  943. yaw = Math.PI + yaw;
  944. }
  945. return new Vector3(pitch, yaw, roll);
  946. };
  947. return Vector3;
  948. })();
  949. BABYLON.Vector3 = Vector3;
  950. //Vector4 class created for EulerAngle class conversion to Quaternion
  951. var Vector4 = (function () {
  952. function Vector4(x, y, z, w) {
  953. this.x = x;
  954. this.y = y;
  955. this.z = z;
  956. this.w = w;
  957. }
  958. Vector4.prototype.toString = function () {
  959. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  960. };
  961. // Operators
  962. Vector4.prototype.asArray = function () {
  963. var result = [];
  964. this.toArray(result, 0);
  965. return result;
  966. };
  967. Vector4.prototype.toArray = function (array, index) {
  968. if (index === undefined) {
  969. index = 0;
  970. }
  971. array[index] = this.x;
  972. array[index + 1] = this.y;
  973. array[index + 2] = this.z;
  974. array[index + 3] = this.w;
  975. return this;
  976. };
  977. Vector4.prototype.addInPlace = function (otherVector) {
  978. this.x += otherVector.x;
  979. this.y += otherVector.y;
  980. this.z += otherVector.z;
  981. this.w += otherVector.w;
  982. return this;
  983. };
  984. Vector4.prototype.add = function (otherVector) {
  985. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  986. };
  987. Vector4.prototype.addToRef = function (otherVector, result) {
  988. result.x = this.x + otherVector.x;
  989. result.y = this.y + otherVector.y;
  990. result.z = this.z + otherVector.z;
  991. result.w = this.w + otherVector.w;
  992. return this;
  993. };
  994. Vector4.prototype.subtractInPlace = function (otherVector) {
  995. this.x -= otherVector.x;
  996. this.y -= otherVector.y;
  997. this.z -= otherVector.z;
  998. this.w -= otherVector.w;
  999. return this;
  1000. };
  1001. Vector4.prototype.subtract = function (otherVector) {
  1002. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1003. };
  1004. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1005. result.x = this.x - otherVector.x;
  1006. result.y = this.y - otherVector.y;
  1007. result.z = this.z - otherVector.z;
  1008. result.w = this.w - otherVector.w;
  1009. return this;
  1010. };
  1011. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1012. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1013. };
  1014. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1015. result.x = this.x - x;
  1016. result.y = this.y - y;
  1017. result.z = this.z - z;
  1018. result.w = this.w - w;
  1019. return this;
  1020. };
  1021. Vector4.prototype.negate = function () {
  1022. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1023. };
  1024. Vector4.prototype.scaleInPlace = function (scale) {
  1025. this.x *= scale;
  1026. this.y *= scale;
  1027. this.z *= scale;
  1028. this.w *= scale;
  1029. return this;
  1030. };
  1031. Vector4.prototype.scale = function (scale) {
  1032. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1033. };
  1034. Vector4.prototype.scaleToRef = function (scale, result) {
  1035. result.x = this.x * scale;
  1036. result.y = this.y * scale;
  1037. result.z = this.z * scale;
  1038. result.w = this.w * scale;
  1039. };
  1040. Vector4.prototype.equals = function (otherVector) {
  1041. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1042. };
  1043. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1044. if (epsilon === void 0) { epsilon = BABYLON.Engine.Epsilon; }
  1045. return otherVector
  1046. && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1047. && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1048. && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1049. && BABYLON.Tools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1050. };
  1051. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1052. return this.x === x && this.y === y && this.z === z && this.w === w;
  1053. };
  1054. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1055. this.x *= otherVector.x;
  1056. this.y *= otherVector.y;
  1057. this.z *= otherVector.z;
  1058. this.w *= otherVector.w;
  1059. return this;
  1060. };
  1061. Vector4.prototype.multiply = function (otherVector) {
  1062. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1063. };
  1064. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1065. result.x = this.x * otherVector.x;
  1066. result.y = this.y * otherVector.y;
  1067. result.z = this.z * otherVector.z;
  1068. result.w = this.w * otherVector.w;
  1069. return this;
  1070. };
  1071. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1072. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1073. };
  1074. Vector4.prototype.divide = function (otherVector) {
  1075. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1076. };
  1077. Vector4.prototype.divideToRef = function (otherVector, result) {
  1078. result.x = this.x / otherVector.x;
  1079. result.y = this.y / otherVector.y;
  1080. result.z = this.z / otherVector.z;
  1081. result.w = this.w / otherVector.w;
  1082. return this;
  1083. };
  1084. Vector4.prototype.MinimizeInPlace = function (other) {
  1085. if (other.x < this.x)
  1086. this.x = other.x;
  1087. if (other.y < this.y)
  1088. this.y = other.y;
  1089. if (other.z < this.z)
  1090. this.z = other.z;
  1091. if (other.w < this.w)
  1092. this.w = other.w;
  1093. return this;
  1094. };
  1095. Vector4.prototype.MaximizeInPlace = function (other) {
  1096. if (other.x > this.x)
  1097. this.x = other.x;
  1098. if (other.y > this.y)
  1099. this.y = other.y;
  1100. if (other.z > this.z)
  1101. this.z = other.z;
  1102. if (other.w > this.w)
  1103. this.w = other.w;
  1104. return this;
  1105. };
  1106. // Properties
  1107. Vector4.prototype.length = function () {
  1108. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1109. };
  1110. Vector4.prototype.lengthSquared = function () {
  1111. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1112. };
  1113. // Methods
  1114. Vector4.prototype.normalize = function () {
  1115. var len = this.length();
  1116. if (len === 0)
  1117. return this;
  1118. var num = 1.0 / len;
  1119. this.x *= num;
  1120. this.y *= num;
  1121. this.z *= num;
  1122. this.w *= num;
  1123. return this;
  1124. };
  1125. Vector4.prototype.clone = function () {
  1126. return new Vector4(this.x, this.y, this.z, this.w);
  1127. };
  1128. Vector4.prototype.copyFrom = function (source) {
  1129. this.x = source.x;
  1130. this.y = source.y;
  1131. this.z = source.z;
  1132. this.w = source.w;
  1133. return this;
  1134. };
  1135. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1136. this.x = x;
  1137. this.y = y;
  1138. this.z = z;
  1139. this.w = w;
  1140. return this;
  1141. };
  1142. // Statics
  1143. Vector4.FromArray = function (array, offset) {
  1144. if (!offset) {
  1145. offset = 0;
  1146. }
  1147. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1148. };
  1149. Vector4.FromArrayToRef = function (array, offset, result) {
  1150. result.x = array[offset];
  1151. result.y = array[offset + 1];
  1152. result.z = array[offset + 2];
  1153. result.w = array[offset + 3];
  1154. };
  1155. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1156. result.x = array[offset];
  1157. result.y = array[offset + 1];
  1158. result.z = array[offset + 2];
  1159. result.w = array[offset + 3];
  1160. };
  1161. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1162. result.x = x;
  1163. result.y = y;
  1164. result.z = z;
  1165. result.w = w;
  1166. };
  1167. Vector4.Zero = function () {
  1168. return new Vector4(0, 0, 0, 0);
  1169. };
  1170. Vector4.Normalize = function (vector) {
  1171. var result = Vector4.Zero();
  1172. Vector4.NormalizeToRef(vector, result);
  1173. return result;
  1174. };
  1175. Vector4.NormalizeToRef = function (vector, result) {
  1176. result.copyFrom(vector);
  1177. result.normalize();
  1178. };
  1179. Vector4.Minimize = function (left, right) {
  1180. var min = left.clone();
  1181. min.MinimizeInPlace(right);
  1182. return min;
  1183. };
  1184. Vector4.Maximize = function (left, right) {
  1185. var max = left.clone();
  1186. max.MaximizeInPlace(right);
  1187. return max;
  1188. };
  1189. Vector4.Distance = function (value1, value2) {
  1190. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1191. };
  1192. Vector4.DistanceSquared = function (value1, value2) {
  1193. var x = value1.x - value2.x;
  1194. var y = value1.y - value2.y;
  1195. var z = value1.z - value2.z;
  1196. var w = value1.w - value2.w;
  1197. return (x * x) + (y * y) + (z * z) + (w * w);
  1198. };
  1199. Vector4.Center = function (value1, value2) {
  1200. var center = value1.add(value2);
  1201. center.scaleInPlace(0.5);
  1202. return center;
  1203. };
  1204. return Vector4;
  1205. })();
  1206. BABYLON.Vector4 = Vector4;
  1207. var Quaternion = (function () {
  1208. function Quaternion(x, y, z, w) {
  1209. if (x === void 0) { x = 0; }
  1210. if (y === void 0) { y = 0; }
  1211. if (z === void 0) { z = 0; }
  1212. if (w === void 0) { w = 1; }
  1213. this.x = x;
  1214. this.y = y;
  1215. this.z = z;
  1216. this.w = w;
  1217. }
  1218. Quaternion.prototype.toString = function () {
  1219. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1220. };
  1221. Quaternion.prototype.asArray = function () {
  1222. return [this.x, this.y, this.z, this.w];
  1223. };
  1224. Quaternion.prototype.equals = function (otherQuaternion) {
  1225. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1226. };
  1227. Quaternion.prototype.clone = function () {
  1228. return new Quaternion(this.x, this.y, this.z, this.w);
  1229. };
  1230. Quaternion.prototype.copyFrom = function (other) {
  1231. this.x = other.x;
  1232. this.y = other.y;
  1233. this.z = other.z;
  1234. this.w = other.w;
  1235. return this;
  1236. };
  1237. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1238. this.x = x;
  1239. this.y = y;
  1240. this.z = z;
  1241. this.w = w;
  1242. return this;
  1243. };
  1244. Quaternion.prototype.add = function (other) {
  1245. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1246. };
  1247. Quaternion.prototype.subtract = function (other) {
  1248. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1249. };
  1250. Quaternion.prototype.scale = function (value) {
  1251. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1252. };
  1253. Quaternion.prototype.multiply = function (q1) {
  1254. var result = new Quaternion(0, 0, 0, 1.0);
  1255. this.multiplyToRef(q1, result);
  1256. return result;
  1257. };
  1258. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1259. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1260. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1261. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1262. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1263. result.copyFromFloats(x, y, z, w);
  1264. return this;
  1265. };
  1266. Quaternion.prototype.length = function () {
  1267. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1268. };
  1269. Quaternion.prototype.normalize = function () {
  1270. var length = 1.0 / this.length();
  1271. this.x *= length;
  1272. this.y *= length;
  1273. this.z *= length;
  1274. this.w *= length;
  1275. return this;
  1276. };
  1277. Quaternion.prototype.toEulerAngles = function () {
  1278. var result = Vector3.Zero();
  1279. this.toEulerAnglesToRef(result);
  1280. return result;
  1281. };
  1282. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1283. //result is an EulerAngles in the in the z-x-z convention
  1284. var qx = this.x;
  1285. var qy = this.y;
  1286. var qz = this.z;
  1287. var qw = this.w;
  1288. var qxy = qx * qy;
  1289. var qxz = qx * qz;
  1290. var qwy = qw * qy;
  1291. var qwz = qw * qz;
  1292. var qwx = qw * qx;
  1293. var qyz = qy * qz;
  1294. var sqx = qx * qx;
  1295. var sqy = qy * qy;
  1296. var determinant = sqx + sqy;
  1297. if (determinant !== 0.000 && determinant !== 1.000) {
  1298. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1299. result.y = Math.acos(1 - 2 * determinant);
  1300. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1301. }
  1302. else {
  1303. if (determinant === 0.0) {
  1304. result.x = 0.0;
  1305. result.y = 0.0;
  1306. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1307. }
  1308. else {
  1309. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1310. result.y = Math.PI;
  1311. result.z = 0.0;
  1312. }
  1313. }
  1314. return this;
  1315. };
  1316. Quaternion.prototype.toRotationMatrix = function (result) {
  1317. var xx = this.x * this.x;
  1318. var yy = this.y * this.y;
  1319. var zz = this.z * this.z;
  1320. var xy = this.x * this.y;
  1321. var zw = this.z * this.w;
  1322. var zx = this.z * this.x;
  1323. var yw = this.y * this.w;
  1324. var yz = this.y * this.z;
  1325. var xw = this.x * this.w;
  1326. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1327. result.m[1] = 2.0 * (xy + zw);
  1328. result.m[2] = 2.0 * (zx - yw);
  1329. result.m[3] = 0;
  1330. result.m[4] = 2.0 * (xy - zw);
  1331. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1332. result.m[6] = 2.0 * (yz + xw);
  1333. result.m[7] = 0;
  1334. result.m[8] = 2.0 * (zx + yw);
  1335. result.m[9] = 2.0 * (yz - xw);
  1336. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1337. result.m[11] = 0;
  1338. result.m[12] = 0;
  1339. result.m[13] = 0;
  1340. result.m[14] = 0;
  1341. result.m[15] = 1.0;
  1342. return this;
  1343. };
  1344. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1345. Quaternion.FromRotationMatrixToRef(matrix, this);
  1346. return this;
  1347. };
  1348. // Statics
  1349. Quaternion.FromRotationMatrix = function (matrix) {
  1350. var result = new Quaternion();
  1351. Quaternion.FromRotationMatrixToRef(matrix, result);
  1352. return result;
  1353. };
  1354. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1355. var data = matrix.m;
  1356. var m11 = data[0], m12 = data[4], m13 = data[8];
  1357. var m21 = data[1], m22 = data[5], m23 = data[9];
  1358. var m31 = data[2], m32 = data[6], m33 = data[10];
  1359. var trace = m11 + m22 + m33;
  1360. var s;
  1361. if (trace > 0) {
  1362. s = 0.5 / Math.sqrt(trace + 1.0);
  1363. result.w = 0.25 / s;
  1364. result.x = (m32 - m23) * s;
  1365. result.y = (m13 - m31) * s;
  1366. result.z = (m21 - m12) * s;
  1367. }
  1368. else if (m11 > m22 && m11 > m33) {
  1369. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1370. result.w = (m32 - m23) / s;
  1371. result.x = 0.25 * s;
  1372. result.y = (m12 + m21) / s;
  1373. result.z = (m13 + m31) / s;
  1374. }
  1375. else if (m22 > m33) {
  1376. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1377. result.w = (m13 - m31) / s;
  1378. result.x = (m12 + m21) / s;
  1379. result.y = 0.25 * s;
  1380. result.z = (m23 + m32) / s;
  1381. }
  1382. else {
  1383. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1384. result.w = (m21 - m12) / s;
  1385. result.x = (m13 + m31) / s;
  1386. result.y = (m23 + m32) / s;
  1387. result.z = 0.25 * s;
  1388. }
  1389. };
  1390. Quaternion.Inverse = function (q) {
  1391. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1392. };
  1393. Quaternion.Identity = function () {
  1394. return new Quaternion(0, 0, 0, 1);
  1395. };
  1396. Quaternion.RotationAxis = function (axis, angle) {
  1397. var result = new Quaternion();
  1398. var sin = Math.sin(angle / 2);
  1399. result.w = Math.cos(angle / 2);
  1400. result.x = axis.x * sin;
  1401. result.y = axis.y * sin;
  1402. result.z = axis.z * sin;
  1403. return result;
  1404. };
  1405. Quaternion.FromArray = function (array, offset) {
  1406. if (!offset) {
  1407. offset = 0;
  1408. }
  1409. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1410. };
  1411. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1412. var result = new Quaternion();
  1413. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1414. return result;
  1415. };
  1416. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1417. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1418. var halfRoll = roll * 0.5;
  1419. var halfPitch = pitch * 0.5;
  1420. var halfYaw = yaw * 0.5;
  1421. var sinRoll = Math.sin(halfRoll);
  1422. var cosRoll = Math.cos(halfRoll);
  1423. var sinPitch = Math.sin(halfPitch);
  1424. var cosPitch = Math.cos(halfPitch);
  1425. var sinYaw = Math.sin(halfYaw);
  1426. var cosYaw = Math.cos(halfYaw);
  1427. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1428. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1429. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1430. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1431. };
  1432. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1433. var result = new Quaternion();
  1434. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1435. return result;
  1436. };
  1437. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1438. // Produces a quaternion from Euler angles in the z-x-z orientation
  1439. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1440. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1441. var halfBeta = beta * 0.5;
  1442. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1443. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1444. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1445. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1446. };
  1447. Quaternion.Slerp = function (left, right, amount) {
  1448. var num2;
  1449. var num3;
  1450. var num = amount;
  1451. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1452. var flag = false;
  1453. if (num4 < 0) {
  1454. flag = true;
  1455. num4 = -num4;
  1456. }
  1457. if (num4 > 0.999999) {
  1458. num3 = 1 - num;
  1459. num2 = flag ? -num : num;
  1460. }
  1461. else {
  1462. var num5 = Math.acos(num4);
  1463. var num6 = (1.0 / Math.sin(num5));
  1464. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1465. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1466. }
  1467. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1468. };
  1469. return Quaternion;
  1470. })();
  1471. BABYLON.Quaternion = Quaternion;
  1472. var Matrix = (function () {
  1473. function Matrix() {
  1474. this.m = new Float32Array(16);
  1475. }
  1476. // Properties
  1477. Matrix.prototype.isIdentity = function () {
  1478. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1479. return false;
  1480. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1481. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1482. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1483. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1484. return false;
  1485. return true;
  1486. };
  1487. Matrix.prototype.determinant = function () {
  1488. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1489. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1490. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1491. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1492. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1493. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1494. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1495. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1496. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1497. };
  1498. // Methods
  1499. Matrix.prototype.toArray = function () {
  1500. return this.m;
  1501. };
  1502. Matrix.prototype.asArray = function () {
  1503. return this.toArray();
  1504. };
  1505. Matrix.prototype.invert = function () {
  1506. this.invertToRef(this);
  1507. return this;
  1508. };
  1509. Matrix.prototype.reset = function () {
  1510. for (var index = 0; index < 16; index++) {
  1511. this.m[index] = 0;
  1512. }
  1513. return this;
  1514. };
  1515. Matrix.prototype.add = function (other) {
  1516. var result = new Matrix();
  1517. this.addToRef(other, result);
  1518. return result;
  1519. };
  1520. Matrix.prototype.addToRef = function (other, result) {
  1521. for (var index = 0; index < 16; index++) {
  1522. result.m[index] = this.m[index] + other.m[index];
  1523. }
  1524. return this;
  1525. };
  1526. Matrix.prototype.addToSelf = function (other) {
  1527. for (var index = 0; index < 16; index++) {
  1528. this.m[index] += other.m[index];
  1529. }
  1530. return this;
  1531. };
  1532. Matrix.prototype.invertToRef = function (other) {
  1533. var l1 = this.m[0];
  1534. var l2 = this.m[1];
  1535. var l3 = this.m[2];
  1536. var l4 = this.m[3];
  1537. var l5 = this.m[4];
  1538. var l6 = this.m[5];
  1539. var l7 = this.m[6];
  1540. var l8 = this.m[7];
  1541. var l9 = this.m[8];
  1542. var l10 = this.m[9];
  1543. var l11 = this.m[10];
  1544. var l12 = this.m[11];
  1545. var l13 = this.m[12];
  1546. var l14 = this.m[13];
  1547. var l15 = this.m[14];
  1548. var l16 = this.m[15];
  1549. var l17 = (l11 * l16) - (l12 * l15);
  1550. var l18 = (l10 * l16) - (l12 * l14);
  1551. var l19 = (l10 * l15) - (l11 * l14);
  1552. var l20 = (l9 * l16) - (l12 * l13);
  1553. var l21 = (l9 * l15) - (l11 * l13);
  1554. var l22 = (l9 * l14) - (l10 * l13);
  1555. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1556. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1557. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1558. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1559. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1560. var l28 = (l7 * l16) - (l8 * l15);
  1561. var l29 = (l6 * l16) - (l8 * l14);
  1562. var l30 = (l6 * l15) - (l7 * l14);
  1563. var l31 = (l5 * l16) - (l8 * l13);
  1564. var l32 = (l5 * l15) - (l7 * l13);
  1565. var l33 = (l5 * l14) - (l6 * l13);
  1566. var l34 = (l7 * l12) - (l8 * l11);
  1567. var l35 = (l6 * l12) - (l8 * l10);
  1568. var l36 = (l6 * l11) - (l7 * l10);
  1569. var l37 = (l5 * l12) - (l8 * l9);
  1570. var l38 = (l5 * l11) - (l7 * l9);
  1571. var l39 = (l5 * l10) - (l6 * l9);
  1572. other.m[0] = l23 * l27;
  1573. other.m[4] = l24 * l27;
  1574. other.m[8] = l25 * l27;
  1575. other.m[12] = l26 * l27;
  1576. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1577. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1578. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1579. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1580. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1581. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1582. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1583. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1584. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1585. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1586. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1587. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1588. return this;
  1589. };
  1590. Matrix.prototype.invertToRefSIMD = function (other) {
  1591. var src = this.m;
  1592. var dest = other.m;
  1593. var row0, row1, row2, row3;
  1594. var tmp1;
  1595. var minor0, minor1, minor2, minor3;
  1596. var det;
  1597. // Load the 4 rows
  1598. var src0 = SIMD.float32x4.load(src, 0);
  1599. var src1 = SIMD.float32x4.load(src, 4);
  1600. var src2 = SIMD.float32x4.load(src, 8);
  1601. var src3 = SIMD.float32x4.load(src, 12);
  1602. // Transpose the source matrix. Sort of. Not a true transpose operation
  1603. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1604. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1605. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1606. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1607. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1608. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1609. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1610. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1611. // This is a true transposition, but it will lead to an incorrect result
  1612. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1613. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1614. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1615. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1616. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1617. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1618. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1619. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1620. // ----
  1621. tmp1 = SIMD.float32x4.mul(row2, row3);
  1622. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1623. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1624. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1625. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1626. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1627. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1628. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1629. // ----
  1630. tmp1 = SIMD.float32x4.mul(row1, row2);
  1631. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1632. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1633. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1634. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1635. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1636. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1637. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1638. // ----
  1639. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1640. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1641. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1642. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1643. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1644. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1645. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1646. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1647. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1648. // ----
  1649. tmp1 = SIMD.float32x4.mul(row0, row1);
  1650. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1651. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1652. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1653. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1654. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1655. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1656. // ----
  1657. tmp1 = SIMD.float32x4.mul(row0, row3);
  1658. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1659. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1660. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1661. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1662. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1663. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1664. // ----
  1665. tmp1 = SIMD.float32x4.mul(row0, row2);
  1666. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1667. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1668. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1669. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1670. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1671. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1672. // Compute determinant
  1673. det = SIMD.float32x4.mul(row0, minor0);
  1674. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1675. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1676. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1677. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1678. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1679. // These shuffles aren't necessary if the faulty transposition is done
  1680. // up at the top of this function.
  1681. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1682. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1683. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1684. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1685. // Compute final values by multiplying with 1/det
  1686. minor0 = SIMD.float32x4.mul(det, minor0);
  1687. minor1 = SIMD.float32x4.mul(det, minor1);
  1688. minor2 = SIMD.float32x4.mul(det, minor2);
  1689. minor3 = SIMD.float32x4.mul(det, minor3);
  1690. SIMD.float32x4.store(dest, 0, minor0);
  1691. SIMD.float32x4.store(dest, 4, minor1);
  1692. SIMD.float32x4.store(dest, 8, minor2);
  1693. SIMD.float32x4.store(dest, 12, minor3);
  1694. return this;
  1695. };
  1696. Matrix.prototype.setTranslation = function (vector3) {
  1697. this.m[12] = vector3.x;
  1698. this.m[13] = vector3.y;
  1699. this.m[14] = vector3.z;
  1700. return this;
  1701. };
  1702. Matrix.prototype.multiply = function (other) {
  1703. var result = new Matrix();
  1704. this.multiplyToRef(other, result);
  1705. return result;
  1706. };
  1707. Matrix.prototype.copyFrom = function (other) {
  1708. for (var index = 0; index < 16; index++) {
  1709. this.m[index] = other.m[index];
  1710. }
  1711. return this;
  1712. };
  1713. Matrix.prototype.copyToArray = function (array, offset) {
  1714. if (offset === void 0) { offset = 0; }
  1715. for (var index = 0; index < 16; index++) {
  1716. array[offset + index] = this.m[index];
  1717. }
  1718. return this;
  1719. };
  1720. Matrix.prototype.multiplyToRef = function (other, result) {
  1721. this.multiplyToArray(other, result.m, 0);
  1722. return this;
  1723. };
  1724. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1725. var tm0 = this.m[0];
  1726. var tm1 = this.m[1];
  1727. var tm2 = this.m[2];
  1728. var tm3 = this.m[3];
  1729. var tm4 = this.m[4];
  1730. var tm5 = this.m[5];
  1731. var tm6 = this.m[6];
  1732. var tm7 = this.m[7];
  1733. var tm8 = this.m[8];
  1734. var tm9 = this.m[9];
  1735. var tm10 = this.m[10];
  1736. var tm11 = this.m[11];
  1737. var tm12 = this.m[12];
  1738. var tm13 = this.m[13];
  1739. var tm14 = this.m[14];
  1740. var tm15 = this.m[15];
  1741. var om0 = other.m[0];
  1742. var om1 = other.m[1];
  1743. var om2 = other.m[2];
  1744. var om3 = other.m[3];
  1745. var om4 = other.m[4];
  1746. var om5 = other.m[5];
  1747. var om6 = other.m[6];
  1748. var om7 = other.m[7];
  1749. var om8 = other.m[8];
  1750. var om9 = other.m[9];
  1751. var om10 = other.m[10];
  1752. var om11 = other.m[11];
  1753. var om12 = other.m[12];
  1754. var om13 = other.m[13];
  1755. var om14 = other.m[14];
  1756. var om15 = other.m[15];
  1757. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1758. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1759. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1760. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1761. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1762. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1763. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1764. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1765. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1766. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1767. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1768. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1769. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1770. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1771. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1772. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1773. return this;
  1774. };
  1775. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1776. if (offset === void 0) { offset = 0; }
  1777. var tm = this.m;
  1778. var om = other.m;
  1779. var om0 = SIMD.float32x4.load(om, 0);
  1780. var om1 = SIMD.float32x4.load(om, 4);
  1781. var om2 = SIMD.float32x4.load(om, 8);
  1782. var om3 = SIMD.float32x4.load(om, 12);
  1783. var tm0 = SIMD.float32x4.load(tm, 0);
  1784. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1785. var tm1 = SIMD.float32x4.load(tm, 4);
  1786. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1787. var tm2 = SIMD.float32x4.load(tm, 8);
  1788. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1789. var tm3 = SIMD.float32x4.load(tm, 12);
  1790. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1791. };
  1792. Matrix.prototype.equals = function (value) {
  1793. return value &&
  1794. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1795. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1796. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1797. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1798. };
  1799. Matrix.prototype.clone = function () {
  1800. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1801. };
  1802. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1803. translation.x = this.m[12];
  1804. translation.y = this.m[13];
  1805. translation.z = this.m[14];
  1806. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1807. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1808. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1809. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1810. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1811. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1812. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1813. rotation.x = 0;
  1814. rotation.y = 0;
  1815. rotation.z = 0;
  1816. rotation.w = 1;
  1817. return false;
  1818. }
  1819. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1820. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1821. return true;
  1822. };
  1823. // Statics
  1824. Matrix.FromArray = function (array, offset) {
  1825. var result = new Matrix();
  1826. if (!offset) {
  1827. offset = 0;
  1828. }
  1829. Matrix.FromArrayToRef(array, offset, result);
  1830. return result;
  1831. };
  1832. Matrix.FromArrayToRef = function (array, offset, result) {
  1833. for (var index = 0; index < 16; index++) {
  1834. result.m[index] = array[index + offset];
  1835. }
  1836. };
  1837. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1838. for (var index = 0; index < 16; index++) {
  1839. result.m[index] = array[index + offset] * scale;
  1840. }
  1841. };
  1842. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1843. result.m[0] = initialM11;
  1844. result.m[1] = initialM12;
  1845. result.m[2] = initialM13;
  1846. result.m[3] = initialM14;
  1847. result.m[4] = initialM21;
  1848. result.m[5] = initialM22;
  1849. result.m[6] = initialM23;
  1850. result.m[7] = initialM24;
  1851. result.m[8] = initialM31;
  1852. result.m[9] = initialM32;
  1853. result.m[10] = initialM33;
  1854. result.m[11] = initialM34;
  1855. result.m[12] = initialM41;
  1856. result.m[13] = initialM42;
  1857. result.m[14] = initialM43;
  1858. result.m[15] = initialM44;
  1859. };
  1860. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1861. var result = new Matrix();
  1862. result.m[0] = initialM11;
  1863. result.m[1] = initialM12;
  1864. result.m[2] = initialM13;
  1865. result.m[3] = initialM14;
  1866. result.m[4] = initialM21;
  1867. result.m[5] = initialM22;
  1868. result.m[6] = initialM23;
  1869. result.m[7] = initialM24;
  1870. result.m[8] = initialM31;
  1871. result.m[9] = initialM32;
  1872. result.m[10] = initialM33;
  1873. result.m[11] = initialM34;
  1874. result.m[12] = initialM41;
  1875. result.m[13] = initialM42;
  1876. result.m[14] = initialM43;
  1877. result.m[15] = initialM44;
  1878. return result;
  1879. };
  1880. Matrix.Compose = function (scale, rotation, translation) {
  1881. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1882. var rotationMatrix = Matrix.Identity();
  1883. rotation.toRotationMatrix(rotationMatrix);
  1884. result = result.multiply(rotationMatrix);
  1885. result.setTranslation(translation);
  1886. return result;
  1887. };
  1888. Matrix.Identity = function () {
  1889. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1890. };
  1891. Matrix.IdentityToRef = function (result) {
  1892. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1893. };
  1894. Matrix.Zero = function () {
  1895. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1896. };
  1897. Matrix.RotationX = function (angle) {
  1898. var result = new Matrix();
  1899. Matrix.RotationXToRef(angle, result);
  1900. return result;
  1901. };
  1902. Matrix.Invert = function (source) {
  1903. var result = new Matrix();
  1904. source.invertToRef(result);
  1905. return result;
  1906. };
  1907. Matrix.RotationXToRef = function (angle, result) {
  1908. var s = Math.sin(angle);
  1909. var c = Math.cos(angle);
  1910. result.m[0] = 1.0;
  1911. result.m[15] = 1.0;
  1912. result.m[5] = c;
  1913. result.m[10] = c;
  1914. result.m[9] = -s;
  1915. result.m[6] = s;
  1916. result.m[1] = 0;
  1917. result.m[2] = 0;
  1918. result.m[3] = 0;
  1919. result.m[4] = 0;
  1920. result.m[7] = 0;
  1921. result.m[8] = 0;
  1922. result.m[11] = 0;
  1923. result.m[12] = 0;
  1924. result.m[13] = 0;
  1925. result.m[14] = 0;
  1926. };
  1927. Matrix.RotationY = function (angle) {
  1928. var result = new Matrix();
  1929. Matrix.RotationYToRef(angle, result);
  1930. return result;
  1931. };
  1932. Matrix.RotationYToRef = function (angle, result) {
  1933. var s = Math.sin(angle);
  1934. var c = Math.cos(angle);
  1935. result.m[5] = 1.0;
  1936. result.m[15] = 1.0;
  1937. result.m[0] = c;
  1938. result.m[2] = -s;
  1939. result.m[8] = s;
  1940. result.m[10] = c;
  1941. result.m[1] = 0;
  1942. result.m[3] = 0;
  1943. result.m[4] = 0;
  1944. result.m[6] = 0;
  1945. result.m[7] = 0;
  1946. result.m[9] = 0;
  1947. result.m[11] = 0;
  1948. result.m[12] = 0;
  1949. result.m[13] = 0;
  1950. result.m[14] = 0;
  1951. };
  1952. Matrix.RotationZ = function (angle) {
  1953. var result = new Matrix();
  1954. Matrix.RotationZToRef(angle, result);
  1955. return result;
  1956. };
  1957. Matrix.RotationZToRef = function (angle, result) {
  1958. var s = Math.sin(angle);
  1959. var c = Math.cos(angle);
  1960. result.m[10] = 1.0;
  1961. result.m[15] = 1.0;
  1962. result.m[0] = c;
  1963. result.m[1] = s;
  1964. result.m[4] = -s;
  1965. result.m[5] = c;
  1966. result.m[2] = 0;
  1967. result.m[3] = 0;
  1968. result.m[6] = 0;
  1969. result.m[7] = 0;
  1970. result.m[8] = 0;
  1971. result.m[9] = 0;
  1972. result.m[11] = 0;
  1973. result.m[12] = 0;
  1974. result.m[13] = 0;
  1975. result.m[14] = 0;
  1976. };
  1977. Matrix.RotationAxis = function (axis, angle) {
  1978. var s = Math.sin(-angle);
  1979. var c = Math.cos(-angle);
  1980. var c1 = 1 - c;
  1981. axis.normalize();
  1982. var result = Matrix.Zero();
  1983. result.m[0] = (axis.x * axis.x) * c1 + c;
  1984. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1985. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1986. result.m[3] = 0.0;
  1987. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1988. result.m[5] = (axis.y * axis.y) * c1 + c;
  1989. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1990. result.m[7] = 0.0;
  1991. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1992. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1993. result.m[10] = (axis.z * axis.z) * c1 + c;
  1994. result.m[11] = 0.0;
  1995. result.m[15] = 1.0;
  1996. return result;
  1997. };
  1998. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1999. var result = new Matrix();
  2000. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2001. return result;
  2002. };
  2003. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2004. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2005. this._tempQuaternion.toRotationMatrix(result);
  2006. };
  2007. Matrix.Scaling = function (x, y, z) {
  2008. var result = Matrix.Zero();
  2009. Matrix.ScalingToRef(x, y, z, result);
  2010. return result;
  2011. };
  2012. Matrix.ScalingToRef = function (x, y, z, result) {
  2013. result.m[0] = x;
  2014. result.m[1] = 0;
  2015. result.m[2] = 0;
  2016. result.m[3] = 0;
  2017. result.m[4] = 0;
  2018. result.m[5] = y;
  2019. result.m[6] = 0;
  2020. result.m[7] = 0;
  2021. result.m[8] = 0;
  2022. result.m[9] = 0;
  2023. result.m[10] = z;
  2024. result.m[11] = 0;
  2025. result.m[12] = 0;
  2026. result.m[13] = 0;
  2027. result.m[14] = 0;
  2028. result.m[15] = 1.0;
  2029. };
  2030. Matrix.Translation = function (x, y, z) {
  2031. var result = Matrix.Identity();
  2032. Matrix.TranslationToRef(x, y, z, result);
  2033. return result;
  2034. };
  2035. Matrix.TranslationToRef = function (x, y, z, result) {
  2036. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2037. };
  2038. Matrix.LookAtLH = function (eye, target, up) {
  2039. var result = Matrix.Zero();
  2040. Matrix.LookAtLHToRef(eye, target, up, result);
  2041. return result;
  2042. };
  2043. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2044. // Z axis
  2045. target.subtractToRef(eye, this._zAxis);
  2046. this._zAxis.normalize();
  2047. // X axis
  2048. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2049. this._xAxis.normalize();
  2050. // Y axis
  2051. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2052. this._yAxis.normalize();
  2053. // Eye angles
  2054. var ex = -Vector3.Dot(this._xAxis, eye);
  2055. var ey = -Vector3.Dot(this._yAxis, eye);
  2056. var ez = -Vector3.Dot(this._zAxis, eye);
  2057. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2058. };
  2059. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  2060. var out = result.m;
  2061. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  2062. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  2063. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  2064. // cc.kmVec3Subtract(f, pCenter, pEye);
  2065. var f = SIMD.float32x4.sub(center, eye);
  2066. // cc.kmVec3Normalize(f, f);
  2067. var tmp = SIMD.float32x4.mul(f, f);
  2068. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2069. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2070. // cc.kmVec3Assign(up, pUp);
  2071. // cc.kmVec3Normalize(up, up);
  2072. tmp = SIMD.float32x4.mul(up, up);
  2073. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2074. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2075. // cc.kmVec3Cross(s, f, up);
  2076. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  2077. // cc.kmVec3Normalize(s, s);
  2078. tmp = SIMD.float32x4.mul(s, s);
  2079. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2080. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2081. // cc.kmVec3Cross(u, s, f);
  2082. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  2083. // cc.kmVec3Normalize(s, s);
  2084. tmp = SIMD.float32x4.mul(s, s);
  2085. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2086. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2087. var zero = SIMD.float32x4.splat(0.0);
  2088. s = SIMD.float32x4.neg(s);
  2089. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2090. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2091. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2092. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2093. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2094. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2095. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2096. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2097. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2098. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2099. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2100. var b3 = SIMD.float32x4.neg(eye);
  2101. b3 = SIMD.float32x4.withW(b3, 1.0);
  2102. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  2103. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  2104. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  2105. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  2106. };
  2107. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2108. var matrix = Matrix.Zero();
  2109. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2110. return matrix;
  2111. };
  2112. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2113. var hw = 2.0 / width;
  2114. var hh = 2.0 / height;
  2115. var id = 1.0 / (zfar - znear);
  2116. var nid = znear / (znear - zfar);
  2117. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2118. };
  2119. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2120. var matrix = Matrix.Zero();
  2121. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2122. return matrix;
  2123. };
  2124. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2125. result.m[0] = 2.0 / (right - left);
  2126. result.m[1] = result.m[2] = result.m[3] = 0;
  2127. result.m[5] = 2.0 / (top - bottom);
  2128. result.m[4] = result.m[6] = result.m[7] = 0;
  2129. result.m[10] = -1.0 / (znear - zfar);
  2130. result.m[8] = result.m[9] = result.m[11] = 0;
  2131. result.m[12] = (left + right) / (left - right);
  2132. result.m[13] = (top + bottom) / (bottom - top);
  2133. result.m[14] = znear / (znear - zfar);
  2134. result.m[15] = 1.0;
  2135. };
  2136. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2137. var matrix = Matrix.Zero();
  2138. matrix.m[0] = (2.0 * znear) / width;
  2139. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2140. matrix.m[5] = (2.0 * znear) / height;
  2141. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2142. matrix.m[10] = -zfar / (znear - zfar);
  2143. matrix.m[8] = matrix.m[9] = 0.0;
  2144. matrix.m[11] = 1.0;
  2145. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2146. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2147. return matrix;
  2148. };
  2149. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2150. var matrix = Matrix.Zero();
  2151. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2152. return matrix;
  2153. };
  2154. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2155. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2156. var tan = 1.0 / (Math.tan(fov * 0.5));
  2157. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2158. if (v_fixed) {
  2159. result.m[0] = tan / aspect;
  2160. }
  2161. else {
  2162. result.m[0] = tan;
  2163. }
  2164. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2165. if (v_fixed) {
  2166. result.m[5] = tan;
  2167. }
  2168. else {
  2169. result.m[5] = tan * aspect;
  2170. }
  2171. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2172. result.m[8] = result.m[9] = 0.0;
  2173. result.m[10] = -zfar / (znear - zfar);
  2174. result.m[11] = 1.0;
  2175. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2176. result.m[14] = (znear * zfar) / (znear - zfar);
  2177. };
  2178. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2179. var cw = viewport.width;
  2180. var ch = viewport.height;
  2181. var cx = viewport.x;
  2182. var cy = viewport.y;
  2183. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2184. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2185. };
  2186. Matrix.GetAsMatrix2x2 = function (matrix) {
  2187. return new Float32Array([
  2188. matrix.m[0], matrix.m[1],
  2189. matrix.m[4], matrix.m[5]
  2190. ]);
  2191. };
  2192. Matrix.GetAsMatrix3x3 = function (matrix) {
  2193. return new Float32Array([
  2194. matrix.m[0], matrix.m[1], matrix.m[2],
  2195. matrix.m[4], matrix.m[5], matrix.m[6],
  2196. matrix.m[8], matrix.m[9], matrix.m[10]
  2197. ]);
  2198. };
  2199. Matrix.Transpose = function (matrix) {
  2200. var result = new Matrix();
  2201. result.m[0] = matrix.m[0];
  2202. result.m[1] = matrix.m[4];
  2203. result.m[2] = matrix.m[8];
  2204. result.m[3] = matrix.m[12];
  2205. result.m[4] = matrix.m[1];
  2206. result.m[5] = matrix.m[5];
  2207. result.m[6] = matrix.m[9];
  2208. result.m[7] = matrix.m[13];
  2209. result.m[8] = matrix.m[2];
  2210. result.m[9] = matrix.m[6];
  2211. result.m[10] = matrix.m[10];
  2212. result.m[11] = matrix.m[14];
  2213. result.m[12] = matrix.m[3];
  2214. result.m[13] = matrix.m[7];
  2215. result.m[14] = matrix.m[11];
  2216. result.m[15] = matrix.m[15];
  2217. return result;
  2218. };
  2219. Matrix.Reflection = function (plane) {
  2220. var matrix = new Matrix();
  2221. Matrix.ReflectionToRef(plane, matrix);
  2222. return matrix;
  2223. };
  2224. Matrix.ReflectionToRef = function (plane, result) {
  2225. plane.normalize();
  2226. var x = plane.normal.x;
  2227. var y = plane.normal.y;
  2228. var z = plane.normal.z;
  2229. var temp = -2 * x;
  2230. var temp2 = -2 * y;
  2231. var temp3 = -2 * z;
  2232. result.m[0] = (temp * x) + 1;
  2233. result.m[1] = temp2 * x;
  2234. result.m[2] = temp3 * x;
  2235. result.m[3] = 0.0;
  2236. result.m[4] = temp * y;
  2237. result.m[5] = (temp2 * y) + 1;
  2238. result.m[6] = temp3 * y;
  2239. result.m[7] = 0.0;
  2240. result.m[8] = temp * z;
  2241. result.m[9] = temp2 * z;
  2242. result.m[10] = (temp3 * z) + 1;
  2243. result.m[11] = 0.0;
  2244. result.m[12] = temp * plane.d;
  2245. result.m[13] = temp2 * plane.d;
  2246. result.m[14] = temp3 * plane.d;
  2247. result.m[15] = 1.0;
  2248. };
  2249. Matrix._tempQuaternion = new Quaternion();
  2250. Matrix._xAxis = Vector3.Zero();
  2251. Matrix._yAxis = Vector3.Zero();
  2252. Matrix._zAxis = Vector3.Zero();
  2253. return Matrix;
  2254. })();
  2255. BABYLON.Matrix = Matrix;
  2256. var Plane = (function () {
  2257. function Plane(a, b, c, d) {
  2258. this.normal = new Vector3(a, b, c);
  2259. this.d = d;
  2260. }
  2261. Plane.prototype.asArray = function () {
  2262. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2263. };
  2264. // Methods
  2265. Plane.prototype.clone = function () {
  2266. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2267. };
  2268. Plane.prototype.normalize = function () {
  2269. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2270. var magnitude = 0;
  2271. if (norm !== 0) {
  2272. magnitude = 1.0 / norm;
  2273. }
  2274. this.normal.x *= magnitude;
  2275. this.normal.y *= magnitude;
  2276. this.normal.z *= magnitude;
  2277. this.d *= magnitude;
  2278. return this;
  2279. };
  2280. Plane.prototype.transform = function (transformation) {
  2281. var transposedMatrix = Matrix.Transpose(transformation);
  2282. var x = this.normal.x;
  2283. var y = this.normal.y;
  2284. var z = this.normal.z;
  2285. var d = this.d;
  2286. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2287. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2288. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2289. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2290. return new Plane(normalX, normalY, normalZ, finalD);
  2291. };
  2292. Plane.prototype.dotCoordinate = function (point) {
  2293. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2294. };
  2295. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2296. var x1 = point2.x - point1.x;
  2297. var y1 = point2.y - point1.y;
  2298. var z1 = point2.z - point1.z;
  2299. var x2 = point3.x - point1.x;
  2300. var y2 = point3.y - point1.y;
  2301. var z2 = point3.z - point1.z;
  2302. var yz = (y1 * z2) - (z1 * y2);
  2303. var xz = (z1 * x2) - (x1 * z2);
  2304. var xy = (x1 * y2) - (y1 * x2);
  2305. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2306. var invPyth;
  2307. if (pyth !== 0) {
  2308. invPyth = 1.0 / pyth;
  2309. }
  2310. else {
  2311. invPyth = 0;
  2312. }
  2313. this.normal.x = yz * invPyth;
  2314. this.normal.y = xz * invPyth;
  2315. this.normal.z = xy * invPyth;
  2316. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2317. return this;
  2318. };
  2319. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2320. var dot = Vector3.Dot(this.normal, direction);
  2321. return (dot <= epsilon);
  2322. };
  2323. Plane.prototype.signedDistanceTo = function (point) {
  2324. return Vector3.Dot(point, this.normal) + this.d;
  2325. };
  2326. // Statics
  2327. Plane.FromArray = function (array) {
  2328. return new Plane(array[0], array[1], array[2], array[3]);
  2329. };
  2330. Plane.FromPoints = function (point1, point2, point3) {
  2331. var result = new Plane(0, 0, 0, 0);
  2332. result.copyFromPoints(point1, point2, point3);
  2333. return result;
  2334. };
  2335. Plane.FromPositionAndNormal = function (origin, normal) {
  2336. var result = new Plane(0, 0, 0, 0);
  2337. normal.normalize();
  2338. result.normal = normal;
  2339. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2340. return result;
  2341. };
  2342. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2343. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2344. return Vector3.Dot(point, normal) + d;
  2345. };
  2346. return Plane;
  2347. })();
  2348. BABYLON.Plane = Plane;
  2349. var Viewport = (function () {
  2350. function Viewport(x, y, width, height) {
  2351. this.x = x;
  2352. this.y = y;
  2353. this.width = width;
  2354. this.height = height;
  2355. }
  2356. Viewport.prototype.toGlobal = function (engine) {
  2357. var width = engine.getRenderWidth();
  2358. var height = engine.getRenderHeight();
  2359. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2360. };
  2361. return Viewport;
  2362. })();
  2363. BABYLON.Viewport = Viewport;
  2364. var Frustum = (function () {
  2365. function Frustum() {
  2366. }
  2367. Frustum.GetPlanes = function (transform) {
  2368. var frustumPlanes = [];
  2369. for (var index = 0; index < 6; index++) {
  2370. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2371. }
  2372. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2373. return frustumPlanes;
  2374. };
  2375. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2376. // Near
  2377. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2378. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2379. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2380. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2381. frustumPlanes[0].normalize();
  2382. // Far
  2383. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2384. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2385. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2386. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2387. frustumPlanes[1].normalize();
  2388. // Left
  2389. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2390. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2391. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2392. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2393. frustumPlanes[2].normalize();
  2394. // Right
  2395. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2396. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2397. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2398. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2399. frustumPlanes[3].normalize();
  2400. // Top
  2401. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2402. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2403. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2404. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2405. frustumPlanes[4].normalize();
  2406. // Bottom
  2407. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2408. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2409. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2410. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2411. frustumPlanes[5].normalize();
  2412. };
  2413. return Frustum;
  2414. })();
  2415. BABYLON.Frustum = Frustum;
  2416. var Ray = (function () {
  2417. function Ray(origin, direction, length) {
  2418. if (length === void 0) { length = Number.MAX_VALUE; }
  2419. this.origin = origin;
  2420. this.direction = direction;
  2421. this.length = length;
  2422. }
  2423. // Methods
  2424. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2425. var d = 0.0;
  2426. var maxValue = Number.MAX_VALUE;
  2427. var inv;
  2428. var min;
  2429. var max;
  2430. var temp;
  2431. if (Math.abs(this.direction.x) < 0.0000001) {
  2432. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2433. return false;
  2434. }
  2435. }
  2436. else {
  2437. inv = 1.0 / this.direction.x;
  2438. min = (minimum.x - this.origin.x) * inv;
  2439. max = (maximum.x - this.origin.x) * inv;
  2440. if (max === -Infinity) {
  2441. max = Infinity;
  2442. }
  2443. if (min > max) {
  2444. temp = min;
  2445. min = max;
  2446. max = temp;
  2447. }
  2448. d = Math.max(min, d);
  2449. maxValue = Math.min(max, maxValue);
  2450. if (d > maxValue) {
  2451. return false;
  2452. }
  2453. }
  2454. if (Math.abs(this.direction.y) < 0.0000001) {
  2455. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2456. return false;
  2457. }
  2458. }
  2459. else {
  2460. inv = 1.0 / this.direction.y;
  2461. min = (minimum.y - this.origin.y) * inv;
  2462. max = (maximum.y - this.origin.y) * inv;
  2463. if (max === -Infinity) {
  2464. max = Infinity;
  2465. }
  2466. if (min > max) {
  2467. temp = min;
  2468. min = max;
  2469. max = temp;
  2470. }
  2471. d = Math.max(min, d);
  2472. maxValue = Math.min(max, maxValue);
  2473. if (d > maxValue) {
  2474. return false;
  2475. }
  2476. }
  2477. if (Math.abs(this.direction.z) < 0.0000001) {
  2478. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2479. return false;
  2480. }
  2481. }
  2482. else {
  2483. inv = 1.0 / this.direction.z;
  2484. min = (minimum.z - this.origin.z) * inv;
  2485. max = (maximum.z - this.origin.z) * inv;
  2486. if (max === -Infinity) {
  2487. max = Infinity;
  2488. }
  2489. if (min > max) {
  2490. temp = min;
  2491. min = max;
  2492. max = temp;
  2493. }
  2494. d = Math.max(min, d);
  2495. maxValue = Math.min(max, maxValue);
  2496. if (d > maxValue) {
  2497. return false;
  2498. }
  2499. }
  2500. return true;
  2501. };
  2502. Ray.prototype.intersectsBox = function (box) {
  2503. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2504. };
  2505. Ray.prototype.intersectsSphere = function (sphere) {
  2506. var x = sphere.center.x - this.origin.x;
  2507. var y = sphere.center.y - this.origin.y;
  2508. var z = sphere.center.z - this.origin.z;
  2509. var pyth = (x * x) + (y * y) + (z * z);
  2510. var rr = sphere.radius * sphere.radius;
  2511. if (pyth <= rr) {
  2512. return true;
  2513. }
  2514. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2515. if (dot < 0.0) {
  2516. return false;
  2517. }
  2518. var temp = pyth - (dot * dot);
  2519. return temp <= rr;
  2520. };
  2521. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2522. if (!this._edge1) {
  2523. this._edge1 = Vector3.Zero();
  2524. this._edge2 = Vector3.Zero();
  2525. this._pvec = Vector3.Zero();
  2526. this._tvec = Vector3.Zero();
  2527. this._qvec = Vector3.Zero();
  2528. }
  2529. vertex1.subtractToRef(vertex0, this._edge1);
  2530. vertex2.subtractToRef(vertex0, this._edge2);
  2531. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2532. var det = Vector3.Dot(this._edge1, this._pvec);
  2533. if (det === 0) {
  2534. return null;
  2535. }
  2536. var invdet = 1 / det;
  2537. this.origin.subtractToRef(vertex0, this._tvec);
  2538. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2539. if (bu < 0 || bu > 1.0) {
  2540. return null;
  2541. }
  2542. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2543. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2544. if (bv < 0 || bu + bv > 1.0) {
  2545. return null;
  2546. }
  2547. //check if the distance is longer than the predefined length.
  2548. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2549. if (distance > this.length) {
  2550. return null;
  2551. }
  2552. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2553. };
  2554. // Statics
  2555. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2556. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2557. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2558. var direction = end.subtract(start);
  2559. direction.normalize();
  2560. return new Ray(start, direction);
  2561. };
  2562. /**
  2563. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2564. * transformed to the given world matrix.
  2565. * @param origin The origin point
  2566. * @param end The end point
  2567. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2568. */
  2569. Ray.CreateNewFromTo = function (origin, end, world) {
  2570. if (world === void 0) { world = Matrix.Identity(); }
  2571. var direction = end.subtract(origin);
  2572. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2573. direction.normalize();
  2574. return Ray.Transform(new Ray(origin, direction, length), world);
  2575. };
  2576. Ray.Transform = function (ray, matrix) {
  2577. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2578. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2579. return new Ray(newOrigin, newDirection, ray.length);
  2580. };
  2581. return Ray;
  2582. })();
  2583. BABYLON.Ray = Ray;
  2584. (function (Space) {
  2585. Space[Space["LOCAL"] = 0] = "LOCAL";
  2586. Space[Space["WORLD"] = 1] = "WORLD";
  2587. })(BABYLON.Space || (BABYLON.Space = {}));
  2588. var Space = BABYLON.Space;
  2589. var Axis = (function () {
  2590. function Axis() {
  2591. }
  2592. Axis.X = new Vector3(1, 0, 0);
  2593. Axis.Y = new Vector3(0, 1, 0);
  2594. Axis.Z = new Vector3(0, 0, 1);
  2595. return Axis;
  2596. })();
  2597. BABYLON.Axis = Axis;
  2598. ;
  2599. var BezierCurve = (function () {
  2600. function BezierCurve() {
  2601. }
  2602. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2603. // Extract X (which is equal to time here)
  2604. var f0 = 1 - 3 * x2 + 3 * x1;
  2605. var f1 = 3 * x2 - 6 * x1;
  2606. var f2 = 3 * x1;
  2607. var refinedT = t;
  2608. for (var i = 0; i < 5; i++) {
  2609. var refinedT2 = refinedT * refinedT;
  2610. var refinedT3 = refinedT2 * refinedT;
  2611. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2612. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2613. refinedT -= (x - t) * slope;
  2614. refinedT = Math.min(1, Math.max(0, refinedT));
  2615. }
  2616. // Resolve cubic bezier for the given x
  2617. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2618. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2619. Math.pow(refinedT, 3);
  2620. };
  2621. return BezierCurve;
  2622. })();
  2623. BABYLON.BezierCurve = BezierCurve;
  2624. (function (Orientation) {
  2625. Orientation[Orientation["CW"] = 0] = "CW";
  2626. Orientation[Orientation["CCW"] = 1] = "CCW";
  2627. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2628. var Orientation = BABYLON.Orientation;
  2629. var Angle = (function () {
  2630. function Angle(radians) {
  2631. var _this = this;
  2632. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2633. this.radians = function () { return _this._radians; };
  2634. this._radians = radians;
  2635. if (this._radians < 0)
  2636. this._radians += (2 * Math.PI);
  2637. }
  2638. Angle.BetweenTwoPoints = function (a, b) {
  2639. var delta = b.subtract(a);
  2640. var theta = Math.atan2(delta.y, delta.x);
  2641. return new Angle(theta);
  2642. };
  2643. Angle.FromRadians = function (radians) {
  2644. return new Angle(radians);
  2645. };
  2646. Angle.FromDegrees = function (degrees) {
  2647. return new Angle(degrees * Math.PI / 180);
  2648. };
  2649. return Angle;
  2650. })();
  2651. BABYLON.Angle = Angle;
  2652. var Arc2 = (function () {
  2653. function Arc2(startPoint, midPoint, endPoint) {
  2654. this.startPoint = startPoint;
  2655. this.midPoint = midPoint;
  2656. this.endPoint = endPoint;
  2657. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2658. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2659. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2660. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2661. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2662. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2663. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2664. var a1 = this.startAngle.degrees();
  2665. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2666. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2667. // angles correction
  2668. if (a2 - a1 > +180.0)
  2669. a2 -= 360.0;
  2670. if (a2 - a1 < -180.0)
  2671. a2 += 360.0;
  2672. if (a3 - a2 > +180.0)
  2673. a3 -= 360.0;
  2674. if (a3 - a2 < -180.0)
  2675. a3 += 360.0;
  2676. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2677. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2678. }
  2679. return Arc2;
  2680. })();
  2681. BABYLON.Arc2 = Arc2;
  2682. var PathCursor = (function () {
  2683. function PathCursor(path) {
  2684. this.path = path;
  2685. this._onchange = new Array();
  2686. this.value = 0;
  2687. this.animations = new Array();
  2688. }
  2689. PathCursor.prototype.getPoint = function () {
  2690. var point = this.path.getPointAtLengthPosition(this.value);
  2691. return new Vector3(point.x, 0, point.y);
  2692. };
  2693. PathCursor.prototype.moveAhead = function (step) {
  2694. if (step === void 0) { step = 0.002; }
  2695. this.move(step);
  2696. return this;
  2697. };
  2698. PathCursor.prototype.moveBack = function (step) {
  2699. if (step === void 0) { step = 0.002; }
  2700. this.move(-step);
  2701. return this;
  2702. };
  2703. PathCursor.prototype.move = function (step) {
  2704. if (Math.abs(step) > 1) {
  2705. throw "step size should be less than 1.";
  2706. }
  2707. this.value += step;
  2708. this.ensureLimits();
  2709. this.raiseOnChange();
  2710. return this;
  2711. };
  2712. PathCursor.prototype.ensureLimits = function () {
  2713. while (this.value > 1) {
  2714. this.value -= 1;
  2715. }
  2716. while (this.value < 0) {
  2717. this.value += 1;
  2718. }
  2719. return this;
  2720. };
  2721. // used by animation engine
  2722. PathCursor.prototype.markAsDirty = function (propertyName) {
  2723. this.ensureLimits();
  2724. this.raiseOnChange();
  2725. return this;
  2726. };
  2727. PathCursor.prototype.raiseOnChange = function () {
  2728. var _this = this;
  2729. this._onchange.forEach(function (f) { return f(_this); });
  2730. return this;
  2731. };
  2732. PathCursor.prototype.onchange = function (f) {
  2733. this._onchange.push(f);
  2734. return this;
  2735. };
  2736. return PathCursor;
  2737. })();
  2738. BABYLON.PathCursor = PathCursor;
  2739. var Path2 = (function () {
  2740. function Path2(x, y) {
  2741. this._points = new Array();
  2742. this._length = 0;
  2743. this.closed = false;
  2744. this._points.push(new Vector2(x, y));
  2745. }
  2746. Path2.prototype.addLineTo = function (x, y) {
  2747. if (closed) {
  2748. BABYLON.Tools.Error("cannot add lines to closed paths");
  2749. return this;
  2750. }
  2751. var newPoint = new Vector2(x, y);
  2752. var previousPoint = this._points[this._points.length - 1];
  2753. this._points.push(newPoint);
  2754. this._length += newPoint.subtract(previousPoint).length();
  2755. return this;
  2756. };
  2757. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2758. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2759. if (closed) {
  2760. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2761. return this;
  2762. }
  2763. var startPoint = this._points[this._points.length - 1];
  2764. var midPoint = new Vector2(midX, midY);
  2765. var endPoint = new Vector2(endX, endY);
  2766. var arc = new Arc2(startPoint, midPoint, endPoint);
  2767. var increment = arc.angle.radians() / numberOfSegments;
  2768. if (arc.orientation === Orientation.CW)
  2769. increment *= -1;
  2770. var currentAngle = arc.startAngle.radians() + increment;
  2771. for (var i = 0; i < numberOfSegments; i++) {
  2772. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2773. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2774. this.addLineTo(x, y);
  2775. currentAngle += increment;
  2776. }
  2777. return this;
  2778. };
  2779. Path2.prototype.close = function () {
  2780. this.closed = true;
  2781. return this;
  2782. };
  2783. Path2.prototype.length = function () {
  2784. var result = this._length;
  2785. if (!this.closed) {
  2786. var lastPoint = this._points[this._points.length - 1];
  2787. var firstPoint = this._points[0];
  2788. result += (firstPoint.subtract(lastPoint).length());
  2789. }
  2790. return result;
  2791. };
  2792. Path2.prototype.getPoints = function () {
  2793. return this._points;
  2794. };
  2795. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2796. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2797. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2798. return Vector2.Zero();
  2799. }
  2800. var lengthPosition = normalizedLengthPosition * this.length();
  2801. var previousOffset = 0;
  2802. for (var i = 0; i < this._points.length; i++) {
  2803. var j = (i + 1) % this._points.length;
  2804. var a = this._points[i];
  2805. var b = this._points[j];
  2806. var bToA = b.subtract(a);
  2807. var nextOffset = (bToA.length() + previousOffset);
  2808. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2809. var dir = bToA.normalize();
  2810. var localOffset = lengthPosition - previousOffset;
  2811. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2812. }
  2813. previousOffset = nextOffset;
  2814. }
  2815. BABYLON.Tools.Error("internal error");
  2816. return Vector2.Zero();
  2817. };
  2818. Path2.StartingAt = function (x, y) {
  2819. return new Path2(x, y);
  2820. };
  2821. return Path2;
  2822. })();
  2823. BABYLON.Path2 = Path2;
  2824. var Path3D = (function () {
  2825. function Path3D(path, firstNormal) {
  2826. this.path = path;
  2827. this._curve = new Array();
  2828. this._distances = new Array();
  2829. this._tangents = new Array();
  2830. this._normals = new Array();
  2831. this._binormals = new Array();
  2832. for (var p = 0; p < path.length; p++) {
  2833. this._curve[p] = path[p].clone(); // hard copy
  2834. }
  2835. this._compute(firstNormal);
  2836. }
  2837. Path3D.prototype.getCurve = function () {
  2838. return this._curve;
  2839. };
  2840. Path3D.prototype.getTangents = function () {
  2841. return this._tangents;
  2842. };
  2843. Path3D.prototype.getNormals = function () {
  2844. return this._normals;
  2845. };
  2846. Path3D.prototype.getBinormals = function () {
  2847. return this._binormals;
  2848. };
  2849. Path3D.prototype.getDistances = function () {
  2850. return this._distances;
  2851. };
  2852. Path3D.prototype.update = function (path, firstNormal) {
  2853. for (var p = 0; p < path.length; p++) {
  2854. this._curve[p].x = path[p].x;
  2855. this._curve[p].y = path[p].y;
  2856. this._curve[p].z = path[p].z;
  2857. }
  2858. this._compute(firstNormal);
  2859. return this;
  2860. };
  2861. // private function compute() : computes tangents, normals and binormals
  2862. Path3D.prototype._compute = function (firstNormal) {
  2863. var l = this._curve.length;
  2864. // first and last tangents
  2865. this._tangents[0] = this._getFirstNonNullVector(0);
  2866. this._tangents[0].normalize();
  2867. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2868. this._tangents[l - 1].normalize();
  2869. // normals and binormals at first point : arbitrary vector with _normalVector()
  2870. var tg0 = this._tangents[0];
  2871. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2872. this._normals[0] = pp0;
  2873. this._normals[0].normalize();
  2874. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2875. this._binormals[0].normalize();
  2876. this._distances[0] = 0;
  2877. // normals and binormals : next points
  2878. var prev; // previous vector (segment)
  2879. var cur; // current vector (segment)
  2880. var curTang; // current tangent
  2881. // previous normal
  2882. var prevBinor; // previous binormal
  2883. for (var i = 1; i < l; i++) {
  2884. // tangents
  2885. prev = this._getLastNonNullVector(i);
  2886. if (i < l - 1) {
  2887. cur = this._getFirstNonNullVector(i);
  2888. this._tangents[i] = prev.add(cur);
  2889. this._tangents[i].normalize();
  2890. }
  2891. this._distances[i] = this._distances[i - 1] + prev.length();
  2892. // normals and binormals
  2893. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2894. curTang = this._tangents[i];
  2895. prevBinor = this._binormals[i - 1];
  2896. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2897. this._normals[i].normalize();
  2898. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2899. this._binormals[i].normalize();
  2900. }
  2901. };
  2902. // private function getFirstNonNullVector(index)
  2903. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2904. Path3D.prototype._getFirstNonNullVector = function (index) {
  2905. var i = 1;
  2906. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2907. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2908. i++;
  2909. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2910. }
  2911. return nNVector;
  2912. };
  2913. // private function getLastNonNullVector(index)
  2914. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2915. Path3D.prototype._getLastNonNullVector = function (index) {
  2916. var i = 1;
  2917. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2918. while (nLVector.length() === 0 && index > i + 1) {
  2919. i++;
  2920. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2921. }
  2922. return nLVector;
  2923. };
  2924. // private function normalVector(v0, vt, va) :
  2925. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2926. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2927. Path3D.prototype._normalVector = function (v0, vt, va) {
  2928. var normal0;
  2929. if (va === undefined || va === null) {
  2930. var point;
  2931. if (!BABYLON.Tools.WithinEpsilon(vt.y, 1, BABYLON.Engine.Epsilon)) {
  2932. point = new Vector3(0, -1, 0);
  2933. }
  2934. else if (!BABYLON.Tools.WithinEpsilon(vt.x, 1, BABYLON.Engine.Epsilon)) {
  2935. point = new Vector3(1, 0, 0);
  2936. }
  2937. else if (!BABYLON.Tools.WithinEpsilon(vt.z, 1, BABYLON.Engine.Epsilon)) {
  2938. point = new Vector3(0, 0, 1);
  2939. }
  2940. normal0 = Vector3.Cross(vt, point);
  2941. }
  2942. else {
  2943. normal0 = Vector3.Cross(vt, va);
  2944. Vector3.CrossToRef(normal0, vt, normal0);
  2945. }
  2946. normal0.normalize();
  2947. return normal0;
  2948. };
  2949. return Path3D;
  2950. })();
  2951. BABYLON.Path3D = Path3D;
  2952. var Curve3 = (function () {
  2953. function Curve3(points) {
  2954. this._length = 0;
  2955. this._points = points;
  2956. this._length = this._computeLength(points);
  2957. }
  2958. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2959. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2960. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2961. var bez = new Array();
  2962. var equation = function (t, val0, val1, val2) {
  2963. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2964. return res;
  2965. };
  2966. for (var i = 0; i <= nbPoints; i++) {
  2967. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2968. }
  2969. return new Curve3(bez);
  2970. };
  2971. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2972. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2973. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2974. var bez = new Array();
  2975. var equation = function (t, val0, val1, val2, val3) {
  2976. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2977. return res;
  2978. };
  2979. for (var i = 0; i <= nbPoints; i++) {
  2980. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2981. }
  2982. return new Curve3(bez);
  2983. };
  2984. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2985. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2986. var hermite = new Array();
  2987. var step = 1 / nbPoints;
  2988. for (var i = 0; i <= nbPoints; i++) {
  2989. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2990. }
  2991. return new Curve3(hermite);
  2992. };
  2993. Curve3.prototype.getPoints = function () {
  2994. return this._points;
  2995. };
  2996. Curve3.prototype.length = function () {
  2997. return this._length;
  2998. };
  2999. Curve3.prototype.continue = function (curve) {
  3000. var lastPoint = this._points[this._points.length - 1];
  3001. var continuedPoints = this._points.slice();
  3002. var curvePoints = curve.getPoints();
  3003. for (var i = 1; i < curvePoints.length; i++) {
  3004. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3005. }
  3006. var continuedCurve = new Curve3(continuedPoints);
  3007. return continuedCurve;
  3008. };
  3009. Curve3.prototype._computeLength = function (path) {
  3010. var l = 0;
  3011. for (var i = 1; i < path.length; i++) {
  3012. l += (path[i].subtract(path[i - 1])).length();
  3013. }
  3014. return l;
  3015. };
  3016. return Curve3;
  3017. })();
  3018. BABYLON.Curve3 = Curve3;
  3019. // Vertex formats
  3020. var PositionNormalVertex = (function () {
  3021. function PositionNormalVertex(position, normal) {
  3022. if (position === void 0) { position = Vector3.Zero(); }
  3023. if (normal === void 0) { normal = Vector3.Up(); }
  3024. this.position = position;
  3025. this.normal = normal;
  3026. }
  3027. PositionNormalVertex.prototype.clone = function () {
  3028. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3029. };
  3030. return PositionNormalVertex;
  3031. })();
  3032. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3033. var PositionNormalTextureVertex = (function () {
  3034. function PositionNormalTextureVertex(position, normal, uv) {
  3035. if (position === void 0) { position = Vector3.Zero(); }
  3036. if (normal === void 0) { normal = Vector3.Up(); }
  3037. if (uv === void 0) { uv = Vector2.Zero(); }
  3038. this.position = position;
  3039. this.normal = normal;
  3040. this.uv = uv;
  3041. }
  3042. PositionNormalTextureVertex.prototype.clone = function () {
  3043. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3044. };
  3045. return PositionNormalTextureVertex;
  3046. })();
  3047. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3048. // SIMD
  3049. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  3050. var previousInvertToRef = Matrix.prototype.invertToRef;
  3051. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  3052. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  3053. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  3054. var SIMDHelper = (function () {
  3055. function SIMDHelper() {
  3056. }
  3057. Object.defineProperty(SIMDHelper, "IsEnabled", {
  3058. get: function () {
  3059. return SIMDHelper._isEnabled;
  3060. },
  3061. enumerable: true,
  3062. configurable: true
  3063. });
  3064. SIMDHelper.DisableSIMD = function () {
  3065. // Replace functions
  3066. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  3067. Matrix.prototype.invertToRef = previousInvertToRef;
  3068. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  3069. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  3070. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  3071. SIMDHelper._isEnabled = false;
  3072. };
  3073. SIMDHelper.EnableSIMD = function () {
  3074. if (window.SIMD === undefined) {
  3075. return;
  3076. }
  3077. // Replace functions
  3078. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  3079. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  3080. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  3081. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  3082. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  3083. Object.defineProperty(Vector3.prototype, "x", {
  3084. get: function () { return this._data[0]; },
  3085. set: function (value) {
  3086. if (!this._data) {
  3087. this._data = new Float32Array(3);
  3088. }
  3089. this._data[0] = value;
  3090. }
  3091. });
  3092. Object.defineProperty(Vector3.prototype, "y", {
  3093. get: function () { return this._data[1]; },
  3094. set: function (value) {
  3095. this._data[1] = value;
  3096. }
  3097. });
  3098. Object.defineProperty(Vector3.prototype, "z", {
  3099. get: function () { return this._data[2]; },
  3100. set: function (value) {
  3101. this._data[2] = value;
  3102. }
  3103. });
  3104. SIMDHelper._isEnabled = true;
  3105. };
  3106. SIMDHelper._isEnabled = false;
  3107. return SIMDHelper;
  3108. })();
  3109. BABYLON.SIMDHelper = SIMDHelper;
  3110. })(BABYLON || (BABYLON = {}));
  3111. var BABYLON;
  3112. (function (BABYLON) {
  3113. var Database = (function () {
  3114. function Database(urlToScene, callbackManifestChecked) {
  3115. // Handling various flavors of prefixed version of IndexedDB
  3116. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3117. this.callbackManifestChecked = callbackManifestChecked;
  3118. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3119. this.db = null;
  3120. this.enableSceneOffline = false;
  3121. this.enableTexturesOffline = false;
  3122. this.manifestVersionFound = 0;
  3123. this.mustUpdateRessources = false;
  3124. this.hasReachedQuota = false;
  3125. if (!Database.IDBStorageEnabled) {
  3126. this.callbackManifestChecked(true);
  3127. }
  3128. else {
  3129. this.checkManifestFile();
  3130. }
  3131. }
  3132. Database.prototype.checkManifestFile = function () {
  3133. var _this = this;
  3134. function noManifestFile() {
  3135. that.enableSceneOffline = false;
  3136. that.enableTexturesOffline = false;
  3137. that.callbackManifestChecked(false);
  3138. }
  3139. var that = this;
  3140. var manifestURL = this.currentSceneUrl + ".manifest";
  3141. var xhr = new XMLHttpRequest();
  3142. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3143. xhr.open("GET", manifestURLTimeStamped, true);
  3144. xhr.addEventListener("load", function () {
  3145. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3146. try {
  3147. var manifestFile = JSON.parse(xhr.response);
  3148. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3149. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3150. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3151. _this.manifestVersionFound = manifestFile.version;
  3152. }
  3153. if (_this.callbackManifestChecked) {
  3154. _this.callbackManifestChecked(true);
  3155. }
  3156. }
  3157. catch (ex) {
  3158. noManifestFile();
  3159. }
  3160. }
  3161. else {
  3162. noManifestFile();
  3163. }
  3164. }, false);
  3165. xhr.addEventListener("error", function (event) {
  3166. noManifestFile();
  3167. }, false);
  3168. try {
  3169. xhr.send();
  3170. }
  3171. catch (ex) {
  3172. BABYLON.Tools.Error("Error on XHR send request.");
  3173. that.callbackManifestChecked(false);
  3174. }
  3175. };
  3176. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3177. var _this = this;
  3178. function handleError() {
  3179. that.isSupported = false;
  3180. if (errorCallback)
  3181. errorCallback();
  3182. }
  3183. var that = this;
  3184. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3185. // Your browser doesn't support IndexedDB
  3186. this.isSupported = false;
  3187. if (errorCallback)
  3188. errorCallback();
  3189. }
  3190. else {
  3191. // If the DB hasn't been opened or created yet
  3192. if (!this.db) {
  3193. this.hasReachedQuota = false;
  3194. this.isSupported = true;
  3195. var request = this.idbFactory.open("babylonjs", 1);
  3196. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3197. request.onerror = function (event) {
  3198. handleError();
  3199. };
  3200. // executes when a version change transaction cannot complete due to other active transactions
  3201. request.onblocked = function (event) {
  3202. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3203. handleError();
  3204. };
  3205. // DB has been opened successfully
  3206. request.onsuccess = function (event) {
  3207. _this.db = request.result;
  3208. successCallback();
  3209. };
  3210. // Initialization of the DB. Creating Scenes & Textures stores
  3211. request.onupgradeneeded = function (event) {
  3212. _this.db = (event.target).result;
  3213. try {
  3214. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3215. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3216. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3217. }
  3218. catch (ex) {
  3219. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3220. handleError();
  3221. }
  3222. };
  3223. }
  3224. else {
  3225. if (successCallback)
  3226. successCallback();
  3227. }
  3228. }
  3229. };
  3230. Database.prototype.loadImageFromDB = function (url, image) {
  3231. var _this = this;
  3232. var completeURL = Database.ReturnFullUrlLocation(url);
  3233. var saveAndLoadImage = function () {
  3234. if (!_this.hasReachedQuota && _this.db !== null) {
  3235. // the texture is not yet in the DB, let's try to save it
  3236. _this._saveImageIntoDBAsync(completeURL, image);
  3237. }
  3238. else {
  3239. image.src = url;
  3240. }
  3241. };
  3242. if (!this.mustUpdateRessources) {
  3243. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3244. }
  3245. else {
  3246. saveAndLoadImage();
  3247. }
  3248. };
  3249. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3250. if (this.isSupported && this.db !== null) {
  3251. var texture;
  3252. var transaction = this.db.transaction(["textures"]);
  3253. transaction.onabort = function (event) {
  3254. image.src = url;
  3255. };
  3256. transaction.oncomplete = function (event) {
  3257. var blobTextureURL;
  3258. if (texture) {
  3259. var URL = window.URL || window.webkitURL;
  3260. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3261. image.onerror = function () {
  3262. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3263. image.src = url;
  3264. };
  3265. image.src = blobTextureURL;
  3266. }
  3267. else {
  3268. notInDBCallback();
  3269. }
  3270. };
  3271. var getRequest = transaction.objectStore("textures").get(url);
  3272. getRequest.onsuccess = function (event) {
  3273. texture = (event.target).result;
  3274. };
  3275. getRequest.onerror = function (event) {
  3276. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3277. image.src = url;
  3278. };
  3279. }
  3280. else {
  3281. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3282. image.src = url;
  3283. }
  3284. };
  3285. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3286. var _this = this;
  3287. if (this.isSupported) {
  3288. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3289. var generateBlobUrl = function () {
  3290. var blobTextureURL;
  3291. if (blob) {
  3292. var URL = window.URL || window.webkitURL;
  3293. try {
  3294. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3295. }
  3296. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3297. catch (ex) {
  3298. blobTextureURL = URL.createObjectURL(blob);
  3299. }
  3300. }
  3301. image.src = blobTextureURL;
  3302. };
  3303. if (Database.IsUASupportingBlobStorage) {
  3304. var xhr = new XMLHttpRequest(), blob;
  3305. xhr.open("GET", url, true);
  3306. xhr.responseType = "blob";
  3307. xhr.addEventListener("load", function () {
  3308. if (xhr.status === 200) {
  3309. // Blob as response (XHR2)
  3310. blob = xhr.response;
  3311. var transaction = _this.db.transaction(["textures"], "readwrite");
  3312. // the transaction could abort because of a QuotaExceededError error
  3313. transaction.onabort = function (event) {
  3314. try {
  3315. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3316. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3317. this.hasReachedQuota = true;
  3318. }
  3319. }
  3320. catch (ex) { }
  3321. generateBlobUrl();
  3322. };
  3323. transaction.oncomplete = function (event) {
  3324. generateBlobUrl();
  3325. };
  3326. var newTexture = { textureUrl: url, data: blob };
  3327. try {
  3328. // Put the blob into the dabase
  3329. var addRequest = transaction.objectStore("textures").put(newTexture);
  3330. addRequest.onsuccess = function (event) {
  3331. };
  3332. addRequest.onerror = function (event) {
  3333. generateBlobUrl();
  3334. };
  3335. }
  3336. catch (ex) {
  3337. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3338. if (ex.code === 25) {
  3339. Database.IsUASupportingBlobStorage = false;
  3340. }
  3341. image.src = url;
  3342. }
  3343. }
  3344. else {
  3345. image.src = url;
  3346. }
  3347. }, false);
  3348. xhr.addEventListener("error", function (event) {
  3349. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3350. image.src = url;
  3351. }, false);
  3352. xhr.send();
  3353. }
  3354. else {
  3355. image.src = url;
  3356. }
  3357. }
  3358. else {
  3359. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3360. image.src = url;
  3361. }
  3362. };
  3363. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3364. var _this = this;
  3365. var updateVersion = function (event) {
  3366. // the version is not yet in the DB or we need to update it
  3367. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3368. };
  3369. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3370. };
  3371. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3372. var _this = this;
  3373. if (this.isSupported) {
  3374. var version;
  3375. try {
  3376. var transaction = this.db.transaction(["versions"]);
  3377. transaction.oncomplete = function (event) {
  3378. if (version) {
  3379. // If the version in the JSON file is > than the version in DB
  3380. if (_this.manifestVersionFound > version.data) {
  3381. _this.mustUpdateRessources = true;
  3382. updateInDBCallback();
  3383. }
  3384. else {
  3385. callback(version.data);
  3386. }
  3387. }
  3388. else {
  3389. _this.mustUpdateRessources = true;
  3390. updateInDBCallback();
  3391. }
  3392. };
  3393. transaction.onabort = function (event) {
  3394. callback(-1);
  3395. };
  3396. var getRequest = transaction.objectStore("versions").get(url);
  3397. getRequest.onsuccess = function (event) {
  3398. version = (event.target).result;
  3399. };
  3400. getRequest.onerror = function (event) {
  3401. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3402. callback(-1);
  3403. };
  3404. }
  3405. catch (ex) {
  3406. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3407. callback(-1);
  3408. }
  3409. }
  3410. else {
  3411. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3412. callback(-1);
  3413. }
  3414. };
  3415. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3416. var _this = this;
  3417. if (this.isSupported && !this.hasReachedQuota) {
  3418. try {
  3419. // Open a transaction to the database
  3420. var transaction = this.db.transaction(["versions"], "readwrite");
  3421. // the transaction could abort because of a QuotaExceededError error
  3422. transaction.onabort = function (event) {
  3423. try {
  3424. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3425. _this.hasReachedQuota = true;
  3426. }
  3427. }
  3428. catch (ex) { }
  3429. callback(-1);
  3430. };
  3431. transaction.oncomplete = function (event) {
  3432. callback(_this.manifestVersionFound);
  3433. };
  3434. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3435. // Put the scene into the database
  3436. var addRequest = transaction.objectStore("versions").put(newVersion);
  3437. addRequest.onsuccess = function (event) {
  3438. };
  3439. addRequest.onerror = function (event) {
  3440. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3441. };
  3442. }
  3443. catch (ex) {
  3444. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3445. callback(-1);
  3446. }
  3447. }
  3448. else {
  3449. callback(-1);
  3450. }
  3451. };
  3452. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3453. var _this = this;
  3454. var completeUrl = Database.ReturnFullUrlLocation(url);
  3455. var saveAndLoadFile = function (event) {
  3456. // the scene is not yet in the DB, let's try to save it
  3457. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3458. };
  3459. this._checkVersionFromDB(completeUrl, function (version) {
  3460. if (version !== -1) {
  3461. if (!_this.mustUpdateRessources) {
  3462. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3463. }
  3464. else {
  3465. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3466. }
  3467. }
  3468. else {
  3469. errorCallback();
  3470. }
  3471. });
  3472. };
  3473. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3474. if (this.isSupported) {
  3475. var targetStore;
  3476. if (url.indexOf(".babylon") !== -1) {
  3477. targetStore = "scenes";
  3478. }
  3479. else {
  3480. targetStore = "textures";
  3481. }
  3482. var file;
  3483. var transaction = this.db.transaction([targetStore]);
  3484. transaction.oncomplete = function (event) {
  3485. if (file) {
  3486. callback(file.data);
  3487. }
  3488. else {
  3489. notInDBCallback();
  3490. }
  3491. };
  3492. transaction.onabort = function (event) {
  3493. notInDBCallback();
  3494. };
  3495. var getRequest = transaction.objectStore(targetStore).get(url);
  3496. getRequest.onsuccess = function (event) {
  3497. file = (event.target).result;
  3498. };
  3499. getRequest.onerror = function (event) {
  3500. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3501. notInDBCallback();
  3502. };
  3503. }
  3504. else {
  3505. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3506. callback();
  3507. }
  3508. };
  3509. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3510. var _this = this;
  3511. if (this.isSupported) {
  3512. var targetStore;
  3513. if (url.indexOf(".babylon") !== -1) {
  3514. targetStore = "scenes";
  3515. }
  3516. else {
  3517. targetStore = "textures";
  3518. }
  3519. // Create XHR
  3520. var xhr = new XMLHttpRequest(), fileData;
  3521. xhr.open("GET", url, true);
  3522. if (useArrayBuffer) {
  3523. xhr.responseType = "arraybuffer";
  3524. }
  3525. xhr.onprogress = progressCallback;
  3526. xhr.addEventListener("load", function () {
  3527. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3528. // Blob as response (XHR2)
  3529. //fileData = xhr.responseText;
  3530. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3531. if (!_this.hasReachedQuota) {
  3532. // Open a transaction to the database
  3533. var transaction = _this.db.transaction([targetStore], "readwrite");
  3534. // the transaction could abort because of a QuotaExceededError error
  3535. transaction.onabort = function (event) {
  3536. try {
  3537. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3538. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3539. this.hasReachedQuota = true;
  3540. }
  3541. }
  3542. catch (ex) { }
  3543. callback(fileData);
  3544. };
  3545. transaction.oncomplete = function (event) {
  3546. callback(fileData);
  3547. };
  3548. var newFile;
  3549. if (targetStore === "scenes") {
  3550. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3551. }
  3552. else {
  3553. newFile = { textureUrl: url, data: fileData };
  3554. }
  3555. try {
  3556. // Put the scene into the database
  3557. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3558. addRequest.onsuccess = function (event) {
  3559. };
  3560. addRequest.onerror = function (event) {
  3561. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3562. };
  3563. }
  3564. catch (ex) {
  3565. callback(fileData);
  3566. }
  3567. }
  3568. else {
  3569. callback(fileData);
  3570. }
  3571. }
  3572. else {
  3573. callback();
  3574. }
  3575. }, false);
  3576. xhr.addEventListener("error", function (event) {
  3577. BABYLON.Tools.Error("error on XHR request.");
  3578. callback();
  3579. }, false);
  3580. xhr.send();
  3581. }
  3582. else {
  3583. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3584. callback();
  3585. }
  3586. };
  3587. Database.IsUASupportingBlobStorage = true;
  3588. Database.IDBStorageEnabled = true;
  3589. Database.parseURL = function (url) {
  3590. var a = document.createElement('a');
  3591. a.href = url;
  3592. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3593. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3594. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3595. return absLocation;
  3596. };
  3597. Database.ReturnFullUrlLocation = function (url) {
  3598. if (url.indexOf("http:/") === -1) {
  3599. return (Database.parseURL(window.location.href) + url);
  3600. }
  3601. else {
  3602. return url;
  3603. }
  3604. };
  3605. return Database;
  3606. })();
  3607. BABYLON.Database = Database;
  3608. })(BABYLON || (BABYLON = {}));
  3609. var BABYLON;
  3610. (function (BABYLON) {
  3611. var Internals;
  3612. (function (Internals) {
  3613. /*
  3614. * Based on jsTGALoader - Javascript loader for TGA file
  3615. * By Vincent Thibault
  3616. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3617. */
  3618. var TGATools = (function () {
  3619. function TGATools() {
  3620. }
  3621. TGATools.GetTGAHeader = function (data) {
  3622. var offset = 0;
  3623. var header = {
  3624. id_length: data[offset++],
  3625. colormap_type: data[offset++],
  3626. image_type: data[offset++],
  3627. colormap_index: data[offset++] | data[offset++] << 8,
  3628. colormap_length: data[offset++] | data[offset++] << 8,
  3629. colormap_size: data[offset++],
  3630. origin: [
  3631. data[offset++] | data[offset++] << 8,
  3632. data[offset++] | data[offset++] << 8
  3633. ],
  3634. width: data[offset++] | data[offset++] << 8,
  3635. height: data[offset++] | data[offset++] << 8,
  3636. pixel_size: data[offset++],
  3637. flags: data[offset++]
  3638. };
  3639. return header;
  3640. };
  3641. TGATools.UploadContent = function (gl, data) {
  3642. // Not enough data to contain header ?
  3643. if (data.length < 19) {
  3644. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3645. return;
  3646. }
  3647. // Read Header
  3648. var offset = 18;
  3649. var header = TGATools.GetTGAHeader(data);
  3650. // Assume it's a valid Targa file.
  3651. if (header.id_length + offset > data.length) {
  3652. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3653. return;
  3654. }
  3655. // Skip not needed data
  3656. offset += header.id_length;
  3657. var use_rle = false;
  3658. var use_pal = false;
  3659. var use_rgb = false;
  3660. var use_grey = false;
  3661. // Get some informations.
  3662. switch (header.image_type) {
  3663. case TGATools._TYPE_RLE_INDEXED:
  3664. use_rle = true;
  3665. case TGATools._TYPE_INDEXED:
  3666. use_pal = true;
  3667. break;
  3668. case TGATools._TYPE_RLE_RGB:
  3669. use_rle = true;
  3670. case TGATools._TYPE_RGB:
  3671. use_rgb = true;
  3672. break;
  3673. case TGATools._TYPE_RLE_GREY:
  3674. use_rle = true;
  3675. case TGATools._TYPE_GREY:
  3676. use_grey = true;
  3677. break;
  3678. }
  3679. var pixel_data;
  3680. var numAlphaBits = header.flags & 0xf;
  3681. var pixel_size = header.pixel_size >> 3;
  3682. var pixel_total = header.width * header.height * pixel_size;
  3683. // Read palettes
  3684. var palettes;
  3685. if (use_pal) {
  3686. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3687. }
  3688. // Read LRE
  3689. if (use_rle) {
  3690. pixel_data = new Uint8Array(pixel_total);
  3691. var c, count, i;
  3692. var localOffset = 0;
  3693. var pixels = new Uint8Array(pixel_size);
  3694. while (offset < pixel_total && localOffset < pixel_total) {
  3695. c = data[offset++];
  3696. count = (c & 0x7f) + 1;
  3697. // RLE pixels
  3698. if (c & 0x80) {
  3699. // Bind pixel tmp array
  3700. for (i = 0; i < pixel_size; ++i) {
  3701. pixels[i] = data[offset++];
  3702. }
  3703. // Copy pixel array
  3704. for (i = 0; i < count; ++i) {
  3705. pixel_data.set(pixels, localOffset + i * pixel_size);
  3706. }
  3707. localOffset += pixel_size * count;
  3708. }
  3709. else {
  3710. count *= pixel_size;
  3711. for (i = 0; i < count; ++i) {
  3712. pixel_data[localOffset + i] = data[offset++];
  3713. }
  3714. localOffset += count;
  3715. }
  3716. }
  3717. }
  3718. else {
  3719. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3720. }
  3721. // Load to texture
  3722. var x_start, y_start, x_step, y_step, y_end, x_end;
  3723. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3724. default:
  3725. case TGATools._ORIGIN_UL:
  3726. x_start = 0;
  3727. x_step = 1;
  3728. x_end = header.width;
  3729. y_start = 0;
  3730. y_step = 1;
  3731. y_end = header.height;
  3732. break;
  3733. case TGATools._ORIGIN_BL:
  3734. x_start = 0;
  3735. x_step = 1;
  3736. x_end = header.width;
  3737. y_start = header.height - 1;
  3738. y_step = -1;
  3739. y_end = -1;
  3740. break;
  3741. case TGATools._ORIGIN_UR:
  3742. x_start = header.width - 1;
  3743. x_step = -1;
  3744. x_end = -1;
  3745. y_start = 0;
  3746. y_step = 1;
  3747. y_end = header.height;
  3748. break;
  3749. case TGATools._ORIGIN_BR:
  3750. x_start = header.width - 1;
  3751. x_step = -1;
  3752. x_end = -1;
  3753. y_start = header.height - 1;
  3754. y_step = -1;
  3755. y_end = -1;
  3756. break;
  3757. }
  3758. // Load the specify method
  3759. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3760. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3761. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3762. };
  3763. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3764. var image = pixel_data, colormap = palettes;
  3765. var width = header.width, height = header.height;
  3766. var color, i = 0, x, y;
  3767. var imageData = new Uint8Array(width * height * 4);
  3768. for (y = y_start; y !== y_end; y += y_step) {
  3769. for (x = x_start; x !== x_end; x += x_step, i++) {
  3770. color = image[i];
  3771. imageData[(x + width * y) * 4 + 3] = 255;
  3772. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3773. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3774. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3775. }
  3776. }
  3777. return imageData;
  3778. };
  3779. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3780. var image = pixel_data;
  3781. var width = header.width, height = header.height;
  3782. var color, i = 0, x, y;
  3783. var imageData = new Uint8Array(width * height * 4);
  3784. for (y = y_start; y !== y_end; y += y_step) {
  3785. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3786. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3787. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3788. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3789. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3790. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3791. }
  3792. }
  3793. return imageData;
  3794. };
  3795. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3796. var image = pixel_data;
  3797. var width = header.width, height = header.height;
  3798. var i = 0, x, y;
  3799. var imageData = new Uint8Array(width * height * 4);
  3800. for (y = y_start; y !== y_end; y += y_step) {
  3801. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3802. imageData[(x + width * y) * 4 + 3] = 255;
  3803. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3804. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3805. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3806. }
  3807. }
  3808. return imageData;
  3809. };
  3810. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3811. var image = pixel_data;
  3812. var width = header.width, height = header.height;
  3813. var i = 0, x, y;
  3814. var imageData = new Uint8Array(width * height * 4);
  3815. for (y = y_start; y !== y_end; y += y_step) {
  3816. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3817. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3818. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3819. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3820. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3821. }
  3822. }
  3823. return imageData;
  3824. };
  3825. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3826. var image = pixel_data;
  3827. var width = header.width, height = header.height;
  3828. var color, i = 0, x, y;
  3829. var imageData = new Uint8Array(width * height * 4);
  3830. for (y = y_start; y !== y_end; y += y_step) {
  3831. for (x = x_start; x !== x_end; x += x_step, i++) {
  3832. color = image[i];
  3833. imageData[(x + width * y) * 4 + 0] = color;
  3834. imageData[(x + width * y) * 4 + 1] = color;
  3835. imageData[(x + width * y) * 4 + 2] = color;
  3836. imageData[(x + width * y) * 4 + 3] = 255;
  3837. }
  3838. }
  3839. return imageData;
  3840. };
  3841. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3842. var image = pixel_data;
  3843. var width = header.width, height = header.height;
  3844. var i = 0, x, y;
  3845. var imageData = new Uint8Array(width * height * 4);
  3846. for (y = y_start; y !== y_end; y += y_step) {
  3847. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3848. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3849. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3850. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3851. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3852. }
  3853. }
  3854. return imageData;
  3855. };
  3856. TGATools._TYPE_NO_DATA = 0;
  3857. TGATools._TYPE_INDEXED = 1;
  3858. TGATools._TYPE_RGB = 2;
  3859. TGATools._TYPE_GREY = 3;
  3860. TGATools._TYPE_RLE_INDEXED = 9;
  3861. TGATools._TYPE_RLE_RGB = 10;
  3862. TGATools._TYPE_RLE_GREY = 11;
  3863. TGATools._ORIGIN_MASK = 0x30;
  3864. TGATools._ORIGIN_SHIFT = 0x04;
  3865. TGATools._ORIGIN_BL = 0x00;
  3866. TGATools._ORIGIN_BR = 0x01;
  3867. TGATools._ORIGIN_UL = 0x02;
  3868. TGATools._ORIGIN_UR = 0x03;
  3869. return TGATools;
  3870. })();
  3871. Internals.TGATools = TGATools;
  3872. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3873. })(BABYLON || (BABYLON = {}));
  3874. var BABYLON;
  3875. (function (BABYLON) {
  3876. var Internals;
  3877. (function (Internals) {
  3878. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3879. // All values and structures referenced from:
  3880. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3881. var DDS_MAGIC = 0x20534444;
  3882. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  3883. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3884. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  3885. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3886. function FourCCToInt32(value) {
  3887. return value.charCodeAt(0) +
  3888. (value.charCodeAt(1) << 8) +
  3889. (value.charCodeAt(2) << 16) +
  3890. (value.charCodeAt(3) << 24);
  3891. }
  3892. function Int32ToFourCC(value) {
  3893. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3894. }
  3895. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3896. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3897. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3898. var headerLengthInt = 31; // The header length in 32 bit ints
  3899. // Offsets into the header array
  3900. var off_magic = 0;
  3901. var off_size = 1;
  3902. var off_flags = 2;
  3903. var off_height = 3;
  3904. var off_width = 4;
  3905. var off_mipmapCount = 7;
  3906. var off_pfFlags = 20;
  3907. var off_pfFourCC = 21;
  3908. var off_RGBbpp = 22;
  3909. var off_RMask = 23;
  3910. var off_GMask = 24;
  3911. var off_BMask = 25;
  3912. var off_AMask = 26;
  3913. var off_caps1 = 27;
  3914. var off_caps2 = 28;
  3915. ;
  3916. var DDSTools = (function () {
  3917. function DDSTools() {
  3918. }
  3919. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3920. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3921. var mipmapCount = 1;
  3922. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3923. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3924. }
  3925. return {
  3926. width: header[off_width],
  3927. height: header[off_height],
  3928. mipmapCount: mipmapCount,
  3929. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3930. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3931. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3932. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3933. };
  3934. };
  3935. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3936. var byteArray = new Uint8Array(dataLength);
  3937. var srcData = new Uint8Array(arrayBuffer);
  3938. var index = 0;
  3939. for (var y = height - 1; y >= 0; y--) {
  3940. for (var x = 0; x < width; x++) {
  3941. var srcPos = dataOffset + (x + y * width) * 4;
  3942. byteArray[index + 2] = srcData[srcPos];
  3943. byteArray[index + 1] = srcData[srcPos + 1];
  3944. byteArray[index] = srcData[srcPos + 2];
  3945. byteArray[index + 3] = srcData[srcPos + 3];
  3946. index += 4;
  3947. }
  3948. }
  3949. return byteArray;
  3950. };
  3951. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3952. var byteArray = new Uint8Array(dataLength);
  3953. var srcData = new Uint8Array(arrayBuffer);
  3954. var index = 0;
  3955. for (var y = height - 1; y >= 0; y--) {
  3956. for (var x = 0; x < width; x++) {
  3957. var srcPos = dataOffset + (x + y * width) * 3;
  3958. byteArray[index + 2] = srcData[srcPos];
  3959. byteArray[index + 1] = srcData[srcPos + 1];
  3960. byteArray[index] = srcData[srcPos + 2];
  3961. index += 3;
  3962. }
  3963. }
  3964. return byteArray;
  3965. };
  3966. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3967. var byteArray = new Uint8Array(dataLength);
  3968. var srcData = new Uint8Array(arrayBuffer);
  3969. var index = 0;
  3970. for (var y = height - 1; y >= 0; y--) {
  3971. for (var x = 0; x < width; x++) {
  3972. var srcPos = dataOffset + (x + y * width);
  3973. byteArray[index] = srcData[srcPos];
  3974. index++;
  3975. }
  3976. }
  3977. return byteArray;
  3978. };
  3979. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3980. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3981. if (header[off_magic] != DDS_MAGIC) {
  3982. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3983. return;
  3984. }
  3985. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3986. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3987. return;
  3988. }
  3989. if (info.isFourCC) {
  3990. fourCC = header[off_pfFourCC];
  3991. switch (fourCC) {
  3992. case FOURCC_DXT1:
  3993. blockBytes = 8;
  3994. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3995. break;
  3996. case FOURCC_DXT3:
  3997. blockBytes = 16;
  3998. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3999. break;
  4000. case FOURCC_DXT5:
  4001. blockBytes = 16;
  4002. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  4003. break;
  4004. default:
  4005. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  4006. return;
  4007. }
  4008. }
  4009. mipmapCount = 1;
  4010. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  4011. mipmapCount = Math.max(1, header[off_mipmapCount]);
  4012. }
  4013. var bpp = header[off_RGBbpp];
  4014. for (var face = 0; face < faces; face++) {
  4015. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  4016. width = header[off_width];
  4017. height = header[off_height];
  4018. dataOffset = header[off_size] + 4;
  4019. for (i = 0; i < mipmapCount; ++i) {
  4020. if (info.isRGB) {
  4021. if (bpp == 24) {
  4022. dataLength = width * height * 3;
  4023. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4024. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  4025. }
  4026. else {
  4027. dataLength = width * height * 4;
  4028. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4029. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  4030. }
  4031. }
  4032. else if (info.isLuminance) {
  4033. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  4034. var unpaddedRowSize = width;
  4035. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  4036. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  4037. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  4038. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  4039. }
  4040. else {
  4041. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  4042. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  4043. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  4044. }
  4045. dataOffset += dataLength;
  4046. width *= 0.5;
  4047. height *= 0.5;
  4048. width = Math.max(1.0, width);
  4049. height = Math.max(1.0, height);
  4050. }
  4051. }
  4052. };
  4053. return DDSTools;
  4054. })();
  4055. Internals.DDSTools = DDSTools;
  4056. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4057. })(BABYLON || (BABYLON = {}));
  4058. var BABYLON;
  4059. (function (BABYLON) {
  4060. var SmartArray = (function () {
  4061. function SmartArray(capacity) {
  4062. this.length = 0;
  4063. this._duplicateId = 0;
  4064. this.data = new Array(capacity);
  4065. this._id = SmartArray._GlobalId++;
  4066. }
  4067. SmartArray.prototype.push = function (value) {
  4068. this.data[this.length++] = value;
  4069. if (this.length > this.data.length) {
  4070. this.data.length *= 2;
  4071. }
  4072. if (!value.__smartArrayFlags) {
  4073. value.__smartArrayFlags = {};
  4074. }
  4075. value.__smartArrayFlags[this._id] = this._duplicateId;
  4076. };
  4077. SmartArray.prototype.pushNoDuplicate = function (value) {
  4078. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4079. return;
  4080. }
  4081. this.push(value);
  4082. };
  4083. SmartArray.prototype.sort = function (compareFn) {
  4084. this.data.sort(compareFn);
  4085. };
  4086. SmartArray.prototype.reset = function () {
  4087. this.length = 0;
  4088. this._duplicateId++;
  4089. };
  4090. SmartArray.prototype.concat = function (array) {
  4091. if (array.length === 0) {
  4092. return;
  4093. }
  4094. if (this.length + array.length > this.data.length) {
  4095. this.data.length = (this.length + array.length) * 2;
  4096. }
  4097. for (var index = 0; index < array.length; index++) {
  4098. this.data[this.length++] = (array.data || array)[index];
  4099. }
  4100. };
  4101. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4102. if (array.length === 0) {
  4103. return;
  4104. }
  4105. if (this.length + array.length > this.data.length) {
  4106. this.data.length = (this.length + array.length) * 2;
  4107. }
  4108. for (var index = 0; index < array.length; index++) {
  4109. var item = (array.data || array)[index];
  4110. this.pushNoDuplicate(item);
  4111. }
  4112. };
  4113. SmartArray.prototype.indexOf = function (value) {
  4114. var position = this.data.indexOf(value);
  4115. if (position >= this.length) {
  4116. return -1;
  4117. }
  4118. return position;
  4119. };
  4120. // Statics
  4121. SmartArray._GlobalId = 0;
  4122. return SmartArray;
  4123. })();
  4124. BABYLON.SmartArray = SmartArray;
  4125. })(BABYLON || (BABYLON = {}));
  4126. var BABYLON;
  4127. (function (BABYLON) {
  4128. var SmartCollection = (function () {
  4129. function SmartCollection(capacity) {
  4130. if (capacity === void 0) { capacity = 10; }
  4131. this.count = 0;
  4132. this._initialCapacity = capacity;
  4133. this.items = {};
  4134. this._keys = new Array(this._initialCapacity);
  4135. }
  4136. SmartCollection.prototype.add = function (key, item) {
  4137. if (this.items[key] != undefined) {
  4138. return -1;
  4139. }
  4140. this.items[key] = item;
  4141. //literal keys are always strings, but we keep source type of key in _keys array
  4142. this._keys[this.count++] = key;
  4143. if (this.count > this._keys.length) {
  4144. this._keys.length *= 2;
  4145. }
  4146. return this.count;
  4147. };
  4148. SmartCollection.prototype.remove = function (key) {
  4149. if (this.items[key] == undefined) {
  4150. return -1;
  4151. }
  4152. return this.removeItemOfIndex(this.indexOf(key));
  4153. };
  4154. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4155. if (index < this.count && index > -1) {
  4156. delete this.items[this._keys[index]];
  4157. //here, shifting by hand is better optimised than .splice
  4158. while (index < this.count) {
  4159. this._keys[index] = this._keys[index + 1];
  4160. index++;
  4161. }
  4162. }
  4163. else {
  4164. return -1;
  4165. }
  4166. return --this.count;
  4167. };
  4168. SmartCollection.prototype.indexOf = function (key) {
  4169. for (var i = 0; i !== this.count; i++) {
  4170. if (this._keys[i] === key) {
  4171. return i;
  4172. }
  4173. }
  4174. return -1;
  4175. };
  4176. SmartCollection.prototype.item = function (key) {
  4177. return this.items[key];
  4178. };
  4179. SmartCollection.prototype.getAllKeys = function () {
  4180. if (this.count > 0) {
  4181. var keys = new Array(this.count);
  4182. for (var i = 0; i < this.count; i++) {
  4183. keys[i] = this._keys[i];
  4184. }
  4185. return keys;
  4186. }
  4187. else {
  4188. return undefined;
  4189. }
  4190. };
  4191. SmartCollection.prototype.getKeyByIndex = function (index) {
  4192. if (index < this.count && index > -1) {
  4193. return this._keys[index];
  4194. }
  4195. else {
  4196. return undefined;
  4197. }
  4198. };
  4199. SmartCollection.prototype.getItemByIndex = function (index) {
  4200. if (index < this.count && index > -1) {
  4201. return this.items[this._keys[index]];
  4202. }
  4203. else {
  4204. return undefined;
  4205. }
  4206. };
  4207. SmartCollection.prototype.empty = function () {
  4208. if (this.count > 0) {
  4209. this.count = 0;
  4210. this.items = {};
  4211. this._keys = new Array(this._initialCapacity);
  4212. }
  4213. };
  4214. SmartCollection.prototype.forEach = function (block) {
  4215. var key;
  4216. for (key in this.items) {
  4217. if (this.items.hasOwnProperty(key)) {
  4218. block(this.items[key]);
  4219. }
  4220. }
  4221. };
  4222. return SmartCollection;
  4223. })();
  4224. BABYLON.SmartCollection = SmartCollection;
  4225. })(BABYLON || (BABYLON = {}));
  4226. var BABYLON;
  4227. (function (BABYLON) {
  4228. // Screenshots
  4229. var screenshotCanvas;
  4230. var cloneValue = function (source, destinationObject) {
  4231. if (!source)
  4232. return null;
  4233. if (source instanceof BABYLON.Mesh) {
  4234. return null;
  4235. }
  4236. if (source instanceof BABYLON.SubMesh) {
  4237. return source.clone(destinationObject);
  4238. }
  4239. else if (source.clone) {
  4240. return source.clone();
  4241. }
  4242. return null;
  4243. };
  4244. var Tools = (function () {
  4245. function Tools() {
  4246. }
  4247. Tools.ToHex = function (i) {
  4248. var str = i.toString(16);
  4249. if (i <= 15) {
  4250. return ("0" + str).toUpperCase();
  4251. }
  4252. return str.toUpperCase();
  4253. };
  4254. Tools.SetImmediate = function (action) {
  4255. if (window.setImmediate) {
  4256. window.setImmediate(action);
  4257. }
  4258. else {
  4259. setTimeout(action, 1);
  4260. }
  4261. };
  4262. Tools.IsExponantOfTwo = function (value) {
  4263. var count = 1;
  4264. do {
  4265. count *= 2;
  4266. } while (count < value);
  4267. return count === value;
  4268. };
  4269. Tools.GetExponantOfTwo = function (value, max) {
  4270. var count = 1;
  4271. do {
  4272. count *= 2;
  4273. } while (count < value);
  4274. if (count > max)
  4275. count = max;
  4276. return count;
  4277. };
  4278. Tools.GetFilename = function (path) {
  4279. var index = path.lastIndexOf("/");
  4280. if (index < 0)
  4281. return path;
  4282. return path.substring(index + 1);
  4283. };
  4284. Tools.GetDOMTextContent = function (element) {
  4285. var result = "";
  4286. var child = element.firstChild;
  4287. while (child) {
  4288. if (child.nodeType === 3) {
  4289. result += child.textContent;
  4290. }
  4291. child = child.nextSibling;
  4292. }
  4293. return result;
  4294. };
  4295. Tools.ToDegrees = function (angle) {
  4296. return angle * 180 / Math.PI;
  4297. };
  4298. Tools.ToRadians = function (angle) {
  4299. return angle * Math.PI / 180;
  4300. };
  4301. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4302. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4303. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4304. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4305. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4306. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4307. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4308. }
  4309. return {
  4310. minimum: minimum,
  4311. maximum: maximum
  4312. };
  4313. };
  4314. Tools.ExtractMinAndMax = function (positions, start, count) {
  4315. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4316. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4317. for (var index = start; index < start + count; index++) {
  4318. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4319. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4320. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4321. }
  4322. return {
  4323. minimum: minimum,
  4324. maximum: maximum
  4325. };
  4326. };
  4327. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4328. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4329. return undefined;
  4330. return Array.isArray(obj) ? obj : [obj];
  4331. };
  4332. // Misc.
  4333. Tools.GetPointerPrefix = function () {
  4334. var eventPrefix = "pointer";
  4335. // Check if hand.js is referenced or if the browser natively supports pointer events
  4336. if (!navigator.pointerEnabled) {
  4337. eventPrefix = "mouse";
  4338. }
  4339. return eventPrefix;
  4340. };
  4341. Tools.QueueNewFrame = function (func) {
  4342. if (window.requestAnimationFrame)
  4343. window.requestAnimationFrame(func);
  4344. else if (window.msRequestAnimationFrame)
  4345. window.msRequestAnimationFrame(func);
  4346. else if (window.webkitRequestAnimationFrame)
  4347. window.webkitRequestAnimationFrame(func);
  4348. else if (window.mozRequestAnimationFrame)
  4349. window.mozRequestAnimationFrame(func);
  4350. else if (window.oRequestAnimationFrame)
  4351. window.oRequestAnimationFrame(func);
  4352. else {
  4353. window.setTimeout(func, 16);
  4354. }
  4355. };
  4356. Tools.RequestFullscreen = function (element) {
  4357. if (element.requestFullscreen)
  4358. element.requestFullscreen();
  4359. else if (element.msRequestFullscreen)
  4360. element.msRequestFullscreen();
  4361. else if (element.webkitRequestFullscreen)
  4362. element.webkitRequestFullscreen();
  4363. else if (element.mozRequestFullScreen)
  4364. element.mozRequestFullScreen();
  4365. };
  4366. Tools.ExitFullscreen = function () {
  4367. if (document.exitFullscreen) {
  4368. document.exitFullscreen();
  4369. }
  4370. else if (document.mozCancelFullScreen) {
  4371. document.mozCancelFullScreen();
  4372. }
  4373. else if (document.webkitCancelFullScreen) {
  4374. document.webkitCancelFullScreen();
  4375. }
  4376. else if (document.msCancelFullScreen) {
  4377. document.msCancelFullScreen();
  4378. }
  4379. };
  4380. // External files
  4381. Tools.CleanUrl = function (url) {
  4382. url = url.replace(/#/mg, "%23");
  4383. return url;
  4384. };
  4385. Tools.LoadImage = function (url, onload, onerror, database) {
  4386. url = Tools.CleanUrl(url);
  4387. var img = new Image();
  4388. if (url.substr(0, 5) !== "data:")
  4389. img.crossOrigin = 'anonymous';
  4390. img.onload = function () {
  4391. onload(img);
  4392. };
  4393. img.onerror = function (err) {
  4394. Tools.Error("Error while trying to load texture: " + url);
  4395. img.src = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  4396. onload(img);
  4397. };
  4398. var noIndexedDB = function () {
  4399. img.src = url;
  4400. };
  4401. var loadFromIndexedDB = function () {
  4402. database.loadImageFromDB(url, img);
  4403. };
  4404. //ANY database to do!
  4405. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4406. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4407. }
  4408. else {
  4409. if (url.indexOf("file:") === -1) {
  4410. noIndexedDB();
  4411. }
  4412. else {
  4413. try {
  4414. var textureName = url.substring(5);
  4415. var blobURL;
  4416. try {
  4417. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4418. }
  4419. catch (ex) {
  4420. // Chrome doesn't support oneTimeOnly parameter
  4421. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4422. }
  4423. img.src = blobURL;
  4424. }
  4425. catch (e) {
  4426. img.src = null;
  4427. }
  4428. }
  4429. }
  4430. return img;
  4431. };
  4432. //ANY
  4433. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4434. url = Tools.CleanUrl(url);
  4435. var noIndexedDB = function () {
  4436. var request = new XMLHttpRequest();
  4437. var loadUrl = Tools.BaseUrl + url;
  4438. request.open('GET', loadUrl, true);
  4439. if (useArrayBuffer) {
  4440. request.responseType = "arraybuffer";
  4441. }
  4442. request.onprogress = progressCallBack;
  4443. request.onreadystatechange = function () {
  4444. if (request.readyState === 4) {
  4445. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4446. callback(!useArrayBuffer ? request.responseText : request.response);
  4447. }
  4448. else {
  4449. if (onError) {
  4450. onError();
  4451. }
  4452. else {
  4453. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4454. }
  4455. }
  4456. }
  4457. };
  4458. request.send(null);
  4459. };
  4460. var loadFromIndexedDB = function () {
  4461. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4462. };
  4463. if (url.indexOf("file:") !== -1) {
  4464. var fileName = url.substring(5);
  4465. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4466. }
  4467. else {
  4468. // Caching all files
  4469. if (database && database.enableSceneOffline) {
  4470. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4471. }
  4472. else {
  4473. noIndexedDB();
  4474. }
  4475. }
  4476. };
  4477. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4478. var reader = new FileReader();
  4479. reader.onload = function (e) {
  4480. //target doesn't have result from ts 1.3
  4481. callback(e.target['result']);
  4482. };
  4483. reader.onprogress = progressCallback;
  4484. reader.readAsDataURL(fileToLoad);
  4485. };
  4486. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4487. var reader = new FileReader();
  4488. reader.onerror = function (e) {
  4489. Tools.Log("Error while reading file: " + fileToLoad.name);
  4490. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4491. };
  4492. reader.onload = function (e) {
  4493. //target doesn't have result from ts 1.3
  4494. callback(e.target['result']);
  4495. };
  4496. reader.onprogress = progressCallBack;
  4497. if (!useArrayBuffer) {
  4498. // Asynchronous read
  4499. reader.readAsText(fileToLoad);
  4500. }
  4501. else {
  4502. reader.readAsArrayBuffer(fileToLoad);
  4503. }
  4504. };
  4505. // Misc.
  4506. Tools.Clamp = function (value, min, max) {
  4507. if (min === void 0) { min = 0; }
  4508. if (max === void 0) { max = 1; }
  4509. return Math.min(max, Math.max(min, value));
  4510. };
  4511. // Returns -1 when value is a negative number and
  4512. // +1 when value is a positive number.
  4513. Tools.Sign = function (value) {
  4514. value = +value; // convert to a number
  4515. if (value === 0 || isNaN(value))
  4516. return value;
  4517. return value > 0 ? 1 : -1;
  4518. };
  4519. Tools.Format = function (value, decimals) {
  4520. if (decimals === void 0) { decimals = 2; }
  4521. return value.toFixed(decimals);
  4522. };
  4523. Tools.CheckExtends = function (v, min, max) {
  4524. if (v.x < min.x)
  4525. min.x = v.x;
  4526. if (v.y < min.y)
  4527. min.y = v.y;
  4528. if (v.z < min.z)
  4529. min.z = v.z;
  4530. if (v.x > max.x)
  4531. max.x = v.x;
  4532. if (v.y > max.y)
  4533. max.y = v.y;
  4534. if (v.z > max.z)
  4535. max.z = v.z;
  4536. };
  4537. Tools.WithinEpsilon = function (a, b, epsilon) {
  4538. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4539. var num = a - b;
  4540. return -epsilon <= num && num <= epsilon;
  4541. };
  4542. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4543. for (var prop in source) {
  4544. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4545. continue;
  4546. }
  4547. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4548. continue;
  4549. }
  4550. var sourceValue = source[prop];
  4551. var typeOfSourceValue = typeof sourceValue;
  4552. if (typeOfSourceValue === "function") {
  4553. continue;
  4554. }
  4555. if (typeOfSourceValue === "object") {
  4556. if (sourceValue instanceof Array) {
  4557. destination[prop] = [];
  4558. if (sourceValue.length > 0) {
  4559. if (typeof sourceValue[0] == "object") {
  4560. for (var index = 0; index < sourceValue.length; index++) {
  4561. var clonedValue = cloneValue(sourceValue[index], destination);
  4562. if (destination[prop].indexOf(clonedValue) === -1) {
  4563. destination[prop].push(clonedValue);
  4564. }
  4565. }
  4566. }
  4567. else {
  4568. destination[prop] = sourceValue.slice(0);
  4569. }
  4570. }
  4571. }
  4572. else {
  4573. destination[prop] = cloneValue(sourceValue, destination);
  4574. }
  4575. }
  4576. else {
  4577. destination[prop] = sourceValue;
  4578. }
  4579. }
  4580. };
  4581. Tools.IsEmpty = function (obj) {
  4582. for (var i in obj) {
  4583. return false;
  4584. }
  4585. return true;
  4586. };
  4587. Tools.RegisterTopRootEvents = function (events) {
  4588. for (var index = 0; index < events.length; index++) {
  4589. var event = events[index];
  4590. window.addEventListener(event.name, event.handler, false);
  4591. try {
  4592. if (window.parent) {
  4593. window.parent.addEventListener(event.name, event.handler, false);
  4594. }
  4595. }
  4596. catch (e) {
  4597. }
  4598. }
  4599. };
  4600. Tools.UnregisterTopRootEvents = function (events) {
  4601. for (var index = 0; index < events.length; index++) {
  4602. var event = events[index];
  4603. window.removeEventListener(event.name, event.handler);
  4604. try {
  4605. if (window.parent) {
  4606. window.parent.removeEventListener(event.name, event.handler);
  4607. }
  4608. }
  4609. catch (e) {
  4610. }
  4611. }
  4612. };
  4613. Tools.DumpFramebuffer = function (width, height, engine) {
  4614. // Read the contents of the framebuffer
  4615. var numberOfChannelsByLine = width * 4;
  4616. var halfHeight = height / 2;
  4617. //Reading datas from WebGL
  4618. var data = engine.readPixels(0, 0, width, height);
  4619. //To flip image on Y axis.
  4620. for (var i = 0; i < halfHeight; i++) {
  4621. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4622. var currentCell = j + i * numberOfChannelsByLine;
  4623. var targetLine = height - i - 1;
  4624. var targetCell = j + targetLine * numberOfChannelsByLine;
  4625. var temp = data[currentCell];
  4626. data[currentCell] = data[targetCell];
  4627. data[targetCell] = temp;
  4628. }
  4629. }
  4630. // Create a 2D canvas to store the result
  4631. if (!screenshotCanvas) {
  4632. screenshotCanvas = document.createElement('canvas');
  4633. }
  4634. screenshotCanvas.width = width;
  4635. screenshotCanvas.height = height;
  4636. var context = screenshotCanvas.getContext('2d');
  4637. // Copy the pixels to a 2D canvas
  4638. var imageData = context.createImageData(width, height);
  4639. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4640. var castData = imageData.data;
  4641. castData.set(data);
  4642. context.putImageData(imageData, 0, 0);
  4643. var base64Image = screenshotCanvas.toDataURL();
  4644. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4645. if (("download" in document.createElement("a"))) {
  4646. var a = window.document.createElement("a");
  4647. a.href = base64Image;
  4648. var date = new Date();
  4649. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4650. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4651. window.document.body.appendChild(a);
  4652. a.addEventListener("click", function () {
  4653. a.parentElement.removeChild(a);
  4654. });
  4655. a.click();
  4656. }
  4657. else {
  4658. var newWindow = window.open("");
  4659. var img = newWindow.document.createElement("img");
  4660. img.src = base64Image;
  4661. newWindow.document.body.appendChild(img);
  4662. }
  4663. };
  4664. Tools.CreateScreenshot = function (engine, camera, size) {
  4665. var width;
  4666. var height;
  4667. var scene = camera.getScene();
  4668. var previousCamera = null;
  4669. if (scene.activeCamera !== camera) {
  4670. previousCamera = scene.activeCamera;
  4671. scene.activeCamera = camera;
  4672. }
  4673. //If a precision value is specified
  4674. if (size.precision) {
  4675. width = Math.round(engine.getRenderWidth() * size.precision);
  4676. height = Math.round(width / engine.getAspectRatio(camera));
  4677. size = { width: width, height: height };
  4678. }
  4679. else if (size.width && size.height) {
  4680. width = size.width;
  4681. height = size.height;
  4682. }
  4683. else if (size.width && !size.height) {
  4684. width = size.width;
  4685. height = Math.round(width / engine.getAspectRatio(camera));
  4686. size = { width: width, height: height };
  4687. }
  4688. else if (size.height && !size.width) {
  4689. height = size.height;
  4690. width = Math.round(height * engine.getAspectRatio(camera));
  4691. size = { width: width, height: height };
  4692. }
  4693. else if (!isNaN(size)) {
  4694. height = size;
  4695. width = size;
  4696. }
  4697. else {
  4698. Tools.Error("Invalid 'size' parameter !");
  4699. return;
  4700. }
  4701. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4702. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4703. texture.renderList = scene.meshes;
  4704. texture.onAfterRender = function () {
  4705. Tools.DumpFramebuffer(width, height, engine);
  4706. };
  4707. scene.incrementRenderId();
  4708. texture.render(true);
  4709. texture.dispose();
  4710. if (previousCamera) {
  4711. scene.activeCamera = previousCamera;
  4712. }
  4713. };
  4714. // XHR response validator for local file scenario
  4715. Tools.ValidateXHRData = function (xhr, dataType) {
  4716. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4717. if (dataType === void 0) { dataType = 7; }
  4718. try {
  4719. if (dataType & 1) {
  4720. if (xhr.responseText && xhr.responseText.length > 0) {
  4721. return true;
  4722. }
  4723. else if (dataType === 1) {
  4724. return false;
  4725. }
  4726. }
  4727. if (dataType & 2) {
  4728. // Check header width and height since there is no "TGA" magic number
  4729. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4730. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4731. return true;
  4732. }
  4733. else if (dataType === 2) {
  4734. return false;
  4735. }
  4736. }
  4737. if (dataType & 4) {
  4738. // Check for the "DDS" magic number
  4739. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4740. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4741. return true;
  4742. }
  4743. else {
  4744. return false;
  4745. }
  4746. }
  4747. }
  4748. catch (e) {
  4749. }
  4750. return false;
  4751. };
  4752. Object.defineProperty(Tools, "NoneLogLevel", {
  4753. get: function () {
  4754. return Tools._NoneLogLevel;
  4755. },
  4756. enumerable: true,
  4757. configurable: true
  4758. });
  4759. Object.defineProperty(Tools, "MessageLogLevel", {
  4760. get: function () {
  4761. return Tools._MessageLogLevel;
  4762. },
  4763. enumerable: true,
  4764. configurable: true
  4765. });
  4766. Object.defineProperty(Tools, "WarningLogLevel", {
  4767. get: function () {
  4768. return Tools._WarningLogLevel;
  4769. },
  4770. enumerable: true,
  4771. configurable: true
  4772. });
  4773. Object.defineProperty(Tools, "ErrorLogLevel", {
  4774. get: function () {
  4775. return Tools._ErrorLogLevel;
  4776. },
  4777. enumerable: true,
  4778. configurable: true
  4779. });
  4780. Object.defineProperty(Tools, "AllLogLevel", {
  4781. get: function () {
  4782. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4783. },
  4784. enumerable: true,
  4785. configurable: true
  4786. });
  4787. Tools._AddLogEntry = function (entry) {
  4788. Tools._LogCache = entry + Tools._LogCache;
  4789. if (Tools.OnNewCacheEntry) {
  4790. Tools.OnNewCacheEntry(entry);
  4791. }
  4792. };
  4793. Tools._FormatMessage = function (message) {
  4794. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4795. var date = new Date();
  4796. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4797. };
  4798. Tools._LogDisabled = function (message) {
  4799. // nothing to do
  4800. };
  4801. Tools._LogEnabled = function (message) {
  4802. var formattedMessage = Tools._FormatMessage(message);
  4803. console.log("BJS - " + formattedMessage);
  4804. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4805. Tools._AddLogEntry(entry);
  4806. };
  4807. Tools._WarnDisabled = function (message) {
  4808. // nothing to do
  4809. };
  4810. Tools._WarnEnabled = function (message) {
  4811. var formattedMessage = Tools._FormatMessage(message);
  4812. console.warn("BJS - " + formattedMessage);
  4813. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4814. Tools._AddLogEntry(entry);
  4815. };
  4816. Tools._ErrorDisabled = function (message) {
  4817. // nothing to do
  4818. };
  4819. Tools._ErrorEnabled = function (message) {
  4820. Tools.errorsCount++;
  4821. var formattedMessage = Tools._FormatMessage(message);
  4822. console.error("BJS - " + formattedMessage);
  4823. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4824. Tools._AddLogEntry(entry);
  4825. };
  4826. Object.defineProperty(Tools, "LogCache", {
  4827. get: function () {
  4828. return Tools._LogCache;
  4829. },
  4830. enumerable: true,
  4831. configurable: true
  4832. });
  4833. Tools.ClearLogCache = function () {
  4834. Tools._LogCache = "";
  4835. Tools.errorsCount = 0;
  4836. };
  4837. Object.defineProperty(Tools, "LogLevels", {
  4838. set: function (level) {
  4839. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4840. Tools.Log = Tools._LogEnabled;
  4841. }
  4842. else {
  4843. Tools.Log = Tools._LogDisabled;
  4844. }
  4845. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4846. Tools.Warn = Tools._WarnEnabled;
  4847. }
  4848. else {
  4849. Tools.Warn = Tools._WarnDisabled;
  4850. }
  4851. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4852. Tools.Error = Tools._ErrorEnabled;
  4853. }
  4854. else {
  4855. Tools.Error = Tools._ErrorDisabled;
  4856. }
  4857. },
  4858. enumerable: true,
  4859. configurable: true
  4860. });
  4861. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4862. get: function () {
  4863. return Tools._PerformanceNoneLogLevel;
  4864. },
  4865. enumerable: true,
  4866. configurable: true
  4867. });
  4868. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4869. get: function () {
  4870. return Tools._PerformanceUserMarkLogLevel;
  4871. },
  4872. enumerable: true,
  4873. configurable: true
  4874. });
  4875. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4876. get: function () {
  4877. return Tools._PerformanceConsoleLogLevel;
  4878. },
  4879. enumerable: true,
  4880. configurable: true
  4881. });
  4882. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4883. set: function (level) {
  4884. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4885. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4886. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4887. return;
  4888. }
  4889. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4890. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4891. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4892. return;
  4893. }
  4894. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4895. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4896. },
  4897. enumerable: true,
  4898. configurable: true
  4899. });
  4900. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4901. };
  4902. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4903. };
  4904. Tools._StartUserMark = function (counterName, condition) {
  4905. if (condition === void 0) { condition = true; }
  4906. if (!condition || !Tools._performance.mark) {
  4907. return;
  4908. }
  4909. Tools._performance.mark(counterName + "-Begin");
  4910. };
  4911. Tools._EndUserMark = function (counterName, condition) {
  4912. if (condition === void 0) { condition = true; }
  4913. if (!condition || !Tools._performance.mark) {
  4914. return;
  4915. }
  4916. Tools._performance.mark(counterName + "-End");
  4917. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4918. };
  4919. Tools._StartPerformanceConsole = function (counterName, condition) {
  4920. if (condition === void 0) { condition = true; }
  4921. if (!condition) {
  4922. return;
  4923. }
  4924. Tools._StartUserMark(counterName, condition);
  4925. if (console.time) {
  4926. console.time(counterName);
  4927. }
  4928. };
  4929. Tools._EndPerformanceConsole = function (counterName, condition) {
  4930. if (condition === void 0) { condition = true; }
  4931. if (!condition) {
  4932. return;
  4933. }
  4934. Tools._EndUserMark(counterName, condition);
  4935. if (console.time) {
  4936. console.timeEnd(counterName);
  4937. }
  4938. };
  4939. Object.defineProperty(Tools, "Now", {
  4940. get: function () {
  4941. if (window.performance && window.performance.now) {
  4942. return window.performance.now();
  4943. }
  4944. return new Date().getTime();
  4945. },
  4946. enumerable: true,
  4947. configurable: true
  4948. });
  4949. // Deprecated
  4950. Tools.GetFps = function () {
  4951. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4952. return 0;
  4953. };
  4954. Tools.BaseUrl = "";
  4955. // Logs
  4956. Tools._NoneLogLevel = 0;
  4957. Tools._MessageLogLevel = 1;
  4958. Tools._WarningLogLevel = 2;
  4959. Tools._ErrorLogLevel = 4;
  4960. Tools._LogCache = "";
  4961. Tools.errorsCount = 0;
  4962. Tools.Log = Tools._LogEnabled;
  4963. Tools.Warn = Tools._WarnEnabled;
  4964. Tools.Error = Tools._ErrorEnabled;
  4965. // Performances
  4966. Tools._PerformanceNoneLogLevel = 0;
  4967. Tools._PerformanceUserMarkLogLevel = 1;
  4968. Tools._PerformanceConsoleLogLevel = 2;
  4969. Tools._performance = window.performance;
  4970. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4971. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4972. return Tools;
  4973. })();
  4974. BABYLON.Tools = Tools;
  4975. /**
  4976. * An implementation of a loop for asynchronous functions.
  4977. */
  4978. var AsyncLoop = (function () {
  4979. /**
  4980. * Constroctor.
  4981. * @param iterations the number of iterations.
  4982. * @param _fn the function to run each iteration
  4983. * @param _successCallback the callback that will be called upon succesful execution
  4984. * @param offset starting offset.
  4985. */
  4986. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4987. if (offset === void 0) { offset = 0; }
  4988. this.iterations = iterations;
  4989. this._fn = _fn;
  4990. this._successCallback = _successCallback;
  4991. this.index = offset - 1;
  4992. this._done = false;
  4993. }
  4994. /**
  4995. * Execute the next iteration. Must be called after the last iteration was finished.
  4996. */
  4997. AsyncLoop.prototype.executeNext = function () {
  4998. if (!this._done) {
  4999. if (this.index + 1 < this.iterations) {
  5000. ++this.index;
  5001. this._fn(this);
  5002. }
  5003. else {
  5004. this.breakLoop();
  5005. }
  5006. }
  5007. };
  5008. /**
  5009. * Break the loop and run the success callback.
  5010. */
  5011. AsyncLoop.prototype.breakLoop = function () {
  5012. this._done = true;
  5013. this._successCallback();
  5014. };
  5015. /**
  5016. * Helper function
  5017. */
  5018. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5019. if (offset === void 0) { offset = 0; }
  5020. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5021. loop.executeNext();
  5022. return loop;
  5023. };
  5024. /**
  5025. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5026. * @param iterations total number of iterations
  5027. * @param syncedIterations number of synchronous iterations in each async iteration.
  5028. * @param fn the function to call each iteration.
  5029. * @param callback a success call back that will be called when iterating stops.
  5030. * @param breakFunction a break condition (optional)
  5031. * @param timeout timeout settings for the setTimeout function. default - 0.
  5032. * @constructor
  5033. */
  5034. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5035. if (timeout === void 0) { timeout = 0; }
  5036. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5037. if (breakFunction && breakFunction())
  5038. loop.breakLoop();
  5039. else {
  5040. setTimeout(function () {
  5041. for (var i = 0; i < syncedIterations; ++i) {
  5042. var iteration = (loop.index * syncedIterations) + i;
  5043. if (iteration >= iterations)
  5044. break;
  5045. fn(iteration);
  5046. if (breakFunction && breakFunction()) {
  5047. loop.breakLoop();
  5048. break;
  5049. }
  5050. }
  5051. loop.executeNext();
  5052. }, timeout);
  5053. }
  5054. }, callback);
  5055. };
  5056. return AsyncLoop;
  5057. })();
  5058. BABYLON.AsyncLoop = AsyncLoop;
  5059. })(BABYLON || (BABYLON = {}));
  5060. var BABYLON;
  5061. (function (BABYLON) {
  5062. var _DepthCullingState = (function () {
  5063. function _DepthCullingState() {
  5064. this._isDepthTestDirty = false;
  5065. this._isDepthMaskDirty = false;
  5066. this._isDepthFuncDirty = false;
  5067. this._isCullFaceDirty = false;
  5068. this._isCullDirty = false;
  5069. this._isZOffsetDirty = false;
  5070. }
  5071. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5072. get: function () {
  5073. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5074. },
  5075. enumerable: true,
  5076. configurable: true
  5077. });
  5078. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5079. get: function () {
  5080. return this._zOffset;
  5081. },
  5082. set: function (value) {
  5083. if (this._zOffset === value) {
  5084. return;
  5085. }
  5086. this._zOffset = value;
  5087. this._isZOffsetDirty = true;
  5088. },
  5089. enumerable: true,
  5090. configurable: true
  5091. });
  5092. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5093. get: function () {
  5094. return this._cullFace;
  5095. },
  5096. set: function (value) {
  5097. if (this._cullFace === value) {
  5098. return;
  5099. }
  5100. this._cullFace = value;
  5101. this._isCullFaceDirty = true;
  5102. },
  5103. enumerable: true,
  5104. configurable: true
  5105. });
  5106. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5107. get: function () {
  5108. return this._cull;
  5109. },
  5110. set: function (value) {
  5111. if (this._cull === value) {
  5112. return;
  5113. }
  5114. this._cull = value;
  5115. this._isCullDirty = true;
  5116. },
  5117. enumerable: true,
  5118. configurable: true
  5119. });
  5120. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5121. get: function () {
  5122. return this._depthFunc;
  5123. },
  5124. set: function (value) {
  5125. if (this._depthFunc === value) {
  5126. return;
  5127. }
  5128. this._depthFunc = value;
  5129. this._isDepthFuncDirty = true;
  5130. },
  5131. enumerable: true,
  5132. configurable: true
  5133. });
  5134. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5135. get: function () {
  5136. return this._depthMask;
  5137. },
  5138. set: function (value) {
  5139. if (this._depthMask === value) {
  5140. return;
  5141. }
  5142. this._depthMask = value;
  5143. this._isDepthMaskDirty = true;
  5144. },
  5145. enumerable: true,
  5146. configurable: true
  5147. });
  5148. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5149. get: function () {
  5150. return this._depthTest;
  5151. },
  5152. set: function (value) {
  5153. if (this._depthTest === value) {
  5154. return;
  5155. }
  5156. this._depthTest = value;
  5157. this._isDepthTestDirty = true;
  5158. },
  5159. enumerable: true,
  5160. configurable: true
  5161. });
  5162. _DepthCullingState.prototype.reset = function () {
  5163. this._depthMask = true;
  5164. this._depthTest = true;
  5165. this._depthFunc = null;
  5166. this._cull = null;
  5167. this._cullFace = null;
  5168. this._zOffset = 0;
  5169. this._isDepthTestDirty = true;
  5170. this._isDepthMaskDirty = true;
  5171. this._isDepthFuncDirty = false;
  5172. this._isCullFaceDirty = false;
  5173. this._isCullDirty = false;
  5174. this._isZOffsetDirty = false;
  5175. };
  5176. _DepthCullingState.prototype.apply = function (gl) {
  5177. if (!this.isDirty) {
  5178. return;
  5179. }
  5180. // Cull
  5181. if (this._isCullDirty) {
  5182. if (this.cull) {
  5183. gl.enable(gl.CULL_FACE);
  5184. }
  5185. else {
  5186. gl.disable(gl.CULL_FACE);
  5187. }
  5188. this._isCullDirty = false;
  5189. }
  5190. // Cull face
  5191. if (this._isCullFaceDirty) {
  5192. gl.cullFace(this.cullFace);
  5193. this._isCullFaceDirty = false;
  5194. }
  5195. // Depth mask
  5196. if (this._isDepthMaskDirty) {
  5197. gl.depthMask(this.depthMask);
  5198. this._isDepthMaskDirty = false;
  5199. }
  5200. // Depth test
  5201. if (this._isDepthTestDirty) {
  5202. if (this.depthTest) {
  5203. gl.enable(gl.DEPTH_TEST);
  5204. }
  5205. else {
  5206. gl.disable(gl.DEPTH_TEST);
  5207. }
  5208. this._isDepthTestDirty = false;
  5209. }
  5210. // Depth func
  5211. if (this._isDepthFuncDirty) {
  5212. gl.depthFunc(this.depthFunc);
  5213. this._isDepthFuncDirty = false;
  5214. }
  5215. // zOffset
  5216. if (this._isZOffsetDirty) {
  5217. if (this.zOffset) {
  5218. gl.enable(gl.POLYGON_OFFSET_FILL);
  5219. gl.polygonOffset(this.zOffset, 0);
  5220. }
  5221. else {
  5222. gl.disable(gl.POLYGON_OFFSET_FILL);
  5223. }
  5224. this._isZOffsetDirty = false;
  5225. }
  5226. };
  5227. return _DepthCullingState;
  5228. })();
  5229. BABYLON._DepthCullingState = _DepthCullingState;
  5230. var _AlphaState = (function () {
  5231. function _AlphaState() {
  5232. this._isAlphaBlendDirty = false;
  5233. this._isBlendFunctionParametersDirty = false;
  5234. this._alphaBlend = false;
  5235. this._blendFunctionParameters = new Array(4);
  5236. }
  5237. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5238. get: function () {
  5239. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5240. },
  5241. enumerable: true,
  5242. configurable: true
  5243. });
  5244. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5245. get: function () {
  5246. return this._alphaBlend;
  5247. },
  5248. set: function (value) {
  5249. if (this._alphaBlend === value) {
  5250. return;
  5251. }
  5252. this._alphaBlend = value;
  5253. this._isAlphaBlendDirty = true;
  5254. },
  5255. enumerable: true,
  5256. configurable: true
  5257. });
  5258. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5259. if (this._blendFunctionParameters[0] === value0 &&
  5260. this._blendFunctionParameters[1] === value1 &&
  5261. this._blendFunctionParameters[2] === value2 &&
  5262. this._blendFunctionParameters[3] === value3) {
  5263. return;
  5264. }
  5265. this._blendFunctionParameters[0] = value0;
  5266. this._blendFunctionParameters[1] = value1;
  5267. this._blendFunctionParameters[2] = value2;
  5268. this._blendFunctionParameters[3] = value3;
  5269. this._isBlendFunctionParametersDirty = true;
  5270. };
  5271. _AlphaState.prototype.reset = function () {
  5272. this._alphaBlend = false;
  5273. this._blendFunctionParameters[0] = null;
  5274. this._blendFunctionParameters[1] = null;
  5275. this._blendFunctionParameters[2] = null;
  5276. this._blendFunctionParameters[3] = null;
  5277. this._isAlphaBlendDirty = true;
  5278. this._isBlendFunctionParametersDirty = false;
  5279. };
  5280. _AlphaState.prototype.apply = function (gl) {
  5281. if (!this.isDirty) {
  5282. return;
  5283. }
  5284. // Alpha blend
  5285. if (this._isAlphaBlendDirty) {
  5286. if (this._alphaBlend) {
  5287. gl.enable(gl.BLEND);
  5288. }
  5289. else {
  5290. gl.disable(gl.BLEND);
  5291. }
  5292. this._isAlphaBlendDirty = false;
  5293. }
  5294. // Alpha function
  5295. if (this._isBlendFunctionParametersDirty) {
  5296. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5297. this._isBlendFunctionParametersDirty = false;
  5298. }
  5299. };
  5300. return _AlphaState;
  5301. })();
  5302. BABYLON._AlphaState = _AlphaState;
  5303. var compileShader = function (gl, source, type, defines) {
  5304. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5305. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5306. gl.compileShader(shader);
  5307. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5308. throw new Error(gl.getShaderInfoLog(shader));
  5309. }
  5310. return shader;
  5311. };
  5312. var getWebGLTextureType = function (gl, type) {
  5313. var textureType = gl.UNSIGNED_BYTE;
  5314. if (type === Engine.TEXTURETYPE_FLOAT)
  5315. textureType = gl.FLOAT;
  5316. return textureType;
  5317. };
  5318. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5319. var magFilter = gl.NEAREST;
  5320. var minFilter = gl.NEAREST;
  5321. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5322. magFilter = gl.LINEAR;
  5323. if (generateMipMaps) {
  5324. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5325. }
  5326. else {
  5327. minFilter = gl.LINEAR;
  5328. }
  5329. }
  5330. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5331. magFilter = gl.LINEAR;
  5332. if (generateMipMaps) {
  5333. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5334. }
  5335. else {
  5336. minFilter = gl.LINEAR;
  5337. }
  5338. }
  5339. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5340. magFilter = gl.NEAREST;
  5341. if (generateMipMaps) {
  5342. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5343. }
  5344. else {
  5345. minFilter = gl.NEAREST;
  5346. }
  5347. }
  5348. return {
  5349. min: minFilter,
  5350. mag: magFilter
  5351. };
  5352. };
  5353. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5355. var engine = scene.getEngine();
  5356. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5357. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5358. gl.bindTexture(gl.TEXTURE_2D, texture);
  5359. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5360. texture._baseWidth = width;
  5361. texture._baseHeight = height;
  5362. texture._width = potWidth;
  5363. texture._height = potHeight;
  5364. texture.isReady = true;
  5365. processFunction(potWidth, potHeight);
  5366. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5369. if (!noMipmap && !isCompressed) {
  5370. gl.generateMipmap(gl.TEXTURE_2D);
  5371. }
  5372. gl.bindTexture(gl.TEXTURE_2D, null);
  5373. engine._activeTexturesCache = [];
  5374. scene._removePendingData(texture);
  5375. };
  5376. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5377. var onload = function () {
  5378. loadedImages[index] = img;
  5379. loadedImages._internalCount++;
  5380. scene._removePendingData(img);
  5381. if (loadedImages._internalCount === 6) {
  5382. onfinish(loadedImages);
  5383. }
  5384. };
  5385. var onerror = function () {
  5386. scene._removePendingData(img);
  5387. };
  5388. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5389. scene._addPendingData(img);
  5390. };
  5391. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5392. var loadedImages = [];
  5393. loadedImages._internalCount = 0;
  5394. for (var index = 0; index < 6; index++) {
  5395. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5396. }
  5397. };
  5398. var EngineCapabilities = (function () {
  5399. function EngineCapabilities() {
  5400. }
  5401. return EngineCapabilities;
  5402. })();
  5403. BABYLON.EngineCapabilities = EngineCapabilities;
  5404. /**
  5405. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5406. */
  5407. var Engine = (function () {
  5408. /**
  5409. * @constructor
  5410. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5411. * @param {boolean} [antialias] - enable antialias
  5412. * @param options - further options to be sent to the getContext function
  5413. */
  5414. function Engine(canvas, antialias, options) {
  5415. var _this = this;
  5416. // Public members
  5417. this.isFullscreen = false;
  5418. this.isPointerLock = false;
  5419. this.cullBackFaces = true;
  5420. this.renderEvenInBackground = true;
  5421. // To enable/disable IDB support and avoid XHR on .manifest
  5422. this.enableOfflineSupport = true;
  5423. this.scenes = new Array();
  5424. this._windowIsBackground = false;
  5425. this._loadingDivBackgroundColor = "black";
  5426. this._drawCalls = 0;
  5427. this._renderingQueueLaunched = false;
  5428. this._activeRenderLoops = [];
  5429. // FPS
  5430. this.fpsRange = 60;
  5431. this.previousFramesDuration = [];
  5432. this.fps = 60;
  5433. this.deltaTime = 0;
  5434. // States
  5435. this._depthCullingState = new _DepthCullingState();
  5436. this._alphaState = new _AlphaState();
  5437. this._alphaMode = Engine.ALPHA_DISABLE;
  5438. // Cache
  5439. this._loadedTexturesCache = new Array();
  5440. this._activeTexturesCache = new Array();
  5441. this._compiledEffects = {};
  5442. this._uintIndicesCurrentlySet = false;
  5443. this._renderingCanvas = canvas;
  5444. options = options || {};
  5445. options.antialias = antialias;
  5446. if (options.preserveDrawingBuffer === undefined) {
  5447. options.preserveDrawingBuffer = false;
  5448. }
  5449. // GL
  5450. try {
  5451. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5452. }
  5453. catch (e) {
  5454. throw new Error("WebGL not supported");
  5455. }
  5456. if (!this._gl) {
  5457. throw new Error("WebGL not supported");
  5458. }
  5459. this._onBlur = function () {
  5460. _this._windowIsBackground = true;
  5461. };
  5462. this._onFocus = function () {
  5463. _this._windowIsBackground = false;
  5464. };
  5465. window.addEventListener("blur", this._onBlur);
  5466. window.addEventListener("focus", this._onFocus);
  5467. // Viewport
  5468. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5469. this.resize();
  5470. // Caps
  5471. this._caps = new EngineCapabilities();
  5472. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5473. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5474. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5475. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5476. // Infos
  5477. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5478. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5479. if (rendererInfo != null) {
  5480. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5481. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5482. }
  5483. if (!this._glVendor) {
  5484. this._glVendor = "Unknown vendor";
  5485. }
  5486. if (!this._glRenderer) {
  5487. this._glRenderer = "Unknown renderer";
  5488. }
  5489. // Extensions
  5490. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5491. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5492. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5493. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  5494. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5495. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5496. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5497. this._caps.highPrecisionShaderSupported = true;
  5498. if (this._gl.getShaderPrecisionFormat) {
  5499. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5500. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5501. }
  5502. // Depth buffer
  5503. this.setDepthBuffer(true);
  5504. this.setDepthFunctionToLessOrEqual();
  5505. this.setDepthWrite(true);
  5506. // Fullscreen
  5507. this._onFullscreenChange = function () {
  5508. if (document.fullscreen !== undefined) {
  5509. _this.isFullscreen = document.fullscreen;
  5510. }
  5511. else if (document.mozFullScreen !== undefined) {
  5512. _this.isFullscreen = document.mozFullScreen;
  5513. }
  5514. else if (document.webkitIsFullScreen !== undefined) {
  5515. _this.isFullscreen = document.webkitIsFullScreen;
  5516. }
  5517. else if (document.msIsFullScreen !== undefined) {
  5518. _this.isFullscreen = document.msIsFullScreen;
  5519. }
  5520. // Pointer lock
  5521. if (_this.isFullscreen && _this._pointerLockRequested) {
  5522. canvas.requestPointerLock = canvas.requestPointerLock ||
  5523. canvas.msRequestPointerLock ||
  5524. canvas.mozRequestPointerLock ||
  5525. canvas.webkitRequestPointerLock;
  5526. if (canvas.requestPointerLock) {
  5527. canvas.requestPointerLock();
  5528. }
  5529. }
  5530. };
  5531. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5532. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5533. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5534. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5535. // Pointer lock
  5536. this._onPointerLockChange = function () {
  5537. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5538. document.webkitPointerLockElement === canvas ||
  5539. document.msPointerLockElement === canvas ||
  5540. document.pointerLockElement === canvas);
  5541. };
  5542. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5543. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5544. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5545. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5546. if (!Engine.audioEngine) {
  5547. Engine.audioEngine = new BABYLON.AudioEngine();
  5548. }
  5549. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5550. }
  5551. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5552. get: function () {
  5553. return Engine._ALPHA_DISABLE;
  5554. },
  5555. enumerable: true,
  5556. configurable: true
  5557. });
  5558. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5559. get: function () {
  5560. return Engine._ALPHA_ONEONE;
  5561. },
  5562. enumerable: true,
  5563. configurable: true
  5564. });
  5565. Object.defineProperty(Engine, "ALPHA_ADD", {
  5566. get: function () {
  5567. return Engine._ALPHA_ADD;
  5568. },
  5569. enumerable: true,
  5570. configurable: true
  5571. });
  5572. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5573. get: function () {
  5574. return Engine._ALPHA_COMBINE;
  5575. },
  5576. enumerable: true,
  5577. configurable: true
  5578. });
  5579. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5580. get: function () {
  5581. return Engine._ALPHA_SUBTRACT;
  5582. },
  5583. enumerable: true,
  5584. configurable: true
  5585. });
  5586. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5587. get: function () {
  5588. return Engine._ALPHA_MULTIPLY;
  5589. },
  5590. enumerable: true,
  5591. configurable: true
  5592. });
  5593. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5594. get: function () {
  5595. return Engine._ALPHA_MAXIMIZED;
  5596. },
  5597. enumerable: true,
  5598. configurable: true
  5599. });
  5600. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5601. get: function () {
  5602. return Engine._DELAYLOADSTATE_NONE;
  5603. },
  5604. enumerable: true,
  5605. configurable: true
  5606. });
  5607. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5608. get: function () {
  5609. return Engine._DELAYLOADSTATE_LOADED;
  5610. },
  5611. enumerable: true,
  5612. configurable: true
  5613. });
  5614. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5615. get: function () {
  5616. return Engine._DELAYLOADSTATE_LOADING;
  5617. },
  5618. enumerable: true,
  5619. configurable: true
  5620. });
  5621. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5622. get: function () {
  5623. return Engine._DELAYLOADSTATE_NOTLOADED;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5629. get: function () {
  5630. return Engine._TEXTUREFORMAT_ALPHA;
  5631. },
  5632. enumerable: true,
  5633. configurable: true
  5634. });
  5635. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5636. get: function () {
  5637. return Engine._TEXTUREFORMAT_LUMINANCE;
  5638. },
  5639. enumerable: true,
  5640. configurable: true
  5641. });
  5642. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5643. get: function () {
  5644. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5645. },
  5646. enumerable: true,
  5647. configurable: true
  5648. });
  5649. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5650. get: function () {
  5651. return Engine._TEXTUREFORMAT_RGB;
  5652. },
  5653. enumerable: true,
  5654. configurable: true
  5655. });
  5656. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5657. get: function () {
  5658. return Engine._TEXTUREFORMAT_RGBA;
  5659. },
  5660. enumerable: true,
  5661. configurable: true
  5662. });
  5663. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5664. get: function () {
  5665. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5666. },
  5667. enumerable: true,
  5668. configurable: true
  5669. });
  5670. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5671. get: function () {
  5672. return Engine._TEXTURETYPE_FLOAT;
  5673. },
  5674. enumerable: true,
  5675. configurable: true
  5676. });
  5677. Object.defineProperty(Engine, "Version", {
  5678. get: function () {
  5679. return "2.2.0-beta";
  5680. },
  5681. enumerable: true,
  5682. configurable: true
  5683. });
  5684. Engine.prototype._prepareWorkingCanvas = function () {
  5685. if (this._workingCanvas) {
  5686. return;
  5687. }
  5688. this._workingCanvas = document.createElement("canvas");
  5689. this._workingContext = this._workingCanvas.getContext("2d");
  5690. };
  5691. Engine.prototype.getGlInfo = function () {
  5692. return {
  5693. vendor: this._glVendor,
  5694. renderer: this._glRenderer,
  5695. version: this._glVersion
  5696. };
  5697. };
  5698. Engine.prototype.getAspectRatio = function (camera) {
  5699. var viewport = camera.viewport;
  5700. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5701. };
  5702. Engine.prototype.getRenderWidth = function () {
  5703. if (this._currentRenderTarget) {
  5704. return this._currentRenderTarget._width;
  5705. }
  5706. return this._renderingCanvas.width;
  5707. };
  5708. Engine.prototype.getRenderHeight = function () {
  5709. if (this._currentRenderTarget) {
  5710. return this._currentRenderTarget._height;
  5711. }
  5712. return this._renderingCanvas.height;
  5713. };
  5714. Engine.prototype.getRenderingCanvas = function () {
  5715. return this._renderingCanvas;
  5716. };
  5717. Engine.prototype.getRenderingCanvasClientRect = function () {
  5718. return this._renderingCanvas.getBoundingClientRect();
  5719. };
  5720. Engine.prototype.setHardwareScalingLevel = function (level) {
  5721. this._hardwareScalingLevel = level;
  5722. this.resize();
  5723. };
  5724. Engine.prototype.getHardwareScalingLevel = function () {
  5725. return this._hardwareScalingLevel;
  5726. };
  5727. Engine.prototype.getLoadedTexturesCache = function () {
  5728. return this._loadedTexturesCache;
  5729. };
  5730. Engine.prototype.getCaps = function () {
  5731. return this._caps;
  5732. };
  5733. Object.defineProperty(Engine.prototype, "drawCalls", {
  5734. get: function () {
  5735. return this._drawCalls;
  5736. },
  5737. enumerable: true,
  5738. configurable: true
  5739. });
  5740. // Methods
  5741. Engine.prototype.resetDrawCalls = function () {
  5742. this._drawCalls = 0;
  5743. };
  5744. Engine.prototype.setDepthFunctionToGreater = function () {
  5745. this._depthCullingState.depthFunc = this._gl.GREATER;
  5746. };
  5747. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5748. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5749. };
  5750. Engine.prototype.setDepthFunctionToLess = function () {
  5751. this._depthCullingState.depthFunc = this._gl.LESS;
  5752. };
  5753. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5754. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5755. };
  5756. /**
  5757. * stop executing a render loop function and remove it from the execution array
  5758. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5759. */
  5760. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5761. if (!renderFunction) {
  5762. this._activeRenderLoops = [];
  5763. return;
  5764. }
  5765. var index = this._activeRenderLoops.indexOf(renderFunction);
  5766. if (index >= 0) {
  5767. this._activeRenderLoops.splice(index, 1);
  5768. }
  5769. };
  5770. Engine.prototype._renderLoop = function () {
  5771. var _this = this;
  5772. var shouldRender = true;
  5773. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5774. shouldRender = false;
  5775. }
  5776. if (shouldRender) {
  5777. // Start new frame
  5778. this.beginFrame();
  5779. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5780. var renderFunction = this._activeRenderLoops[index];
  5781. renderFunction();
  5782. }
  5783. // Present
  5784. this.endFrame();
  5785. }
  5786. if (this._activeRenderLoops.length > 0) {
  5787. // Register new frame
  5788. BABYLON.Tools.QueueNewFrame(function () {
  5789. _this._renderLoop();
  5790. });
  5791. }
  5792. else {
  5793. this._renderingQueueLaunched = false;
  5794. }
  5795. };
  5796. /**
  5797. * Register and execute a render loop. The engine can have more than one render function.
  5798. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5799. * @example
  5800. * engine.runRenderLoop(function () {
  5801. * scene.render()
  5802. * })
  5803. */
  5804. Engine.prototype.runRenderLoop = function (renderFunction) {
  5805. var _this = this;
  5806. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5807. return;
  5808. }
  5809. this._activeRenderLoops.push(renderFunction);
  5810. if (!this._renderingQueueLaunched) {
  5811. this._renderingQueueLaunched = true;
  5812. BABYLON.Tools.QueueNewFrame(function () {
  5813. _this._renderLoop();
  5814. });
  5815. }
  5816. };
  5817. /**
  5818. * Toggle full screen mode.
  5819. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5820. */
  5821. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5822. if (this.isFullscreen) {
  5823. BABYLON.Tools.ExitFullscreen();
  5824. }
  5825. else {
  5826. this._pointerLockRequested = requestPointerLock;
  5827. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5828. }
  5829. };
  5830. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5831. this.applyStates();
  5832. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5833. if (this._depthCullingState.depthMask) {
  5834. this._gl.clearDepth(1.0);
  5835. }
  5836. var mode = 0;
  5837. if (backBuffer)
  5838. mode |= this._gl.COLOR_BUFFER_BIT;
  5839. if (depthStencil && this._depthCullingState.depthMask)
  5840. mode |= this._gl.DEPTH_BUFFER_BIT;
  5841. this._gl.clear(mode);
  5842. };
  5843. /**
  5844. * Set the WebGL's viewport
  5845. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5846. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5847. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5848. */
  5849. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5850. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5851. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5852. var x = viewport.x || 0;
  5853. var y = viewport.y || 0;
  5854. this._cachedViewport = viewport;
  5855. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5856. };
  5857. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5858. this._cachedViewport = null;
  5859. this._gl.viewport(x, y, width, height);
  5860. };
  5861. Engine.prototype.beginFrame = function () {
  5862. this._measureFps();
  5863. };
  5864. Engine.prototype.endFrame = function () {
  5865. //this.flushFramebuffer();
  5866. };
  5867. /**
  5868. * resize the view according to the canvas' size.
  5869. * @example
  5870. * window.addEventListener("resize", function () {
  5871. * engine.resize();
  5872. * });
  5873. */
  5874. Engine.prototype.resize = function () {
  5875. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5876. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5877. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5878. };
  5879. /**
  5880. * force a specific size of the canvas
  5881. * @param {number} width - the new canvas' width
  5882. * @param {number} height - the new canvas' height
  5883. */
  5884. Engine.prototype.setSize = function (width, height) {
  5885. this._renderingCanvas.width = width;
  5886. this._renderingCanvas.height = height;
  5887. for (var index = 0; index < this.scenes.length; index++) {
  5888. var scene = this.scenes[index];
  5889. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5890. var cam = scene.cameras[camIndex];
  5891. cam._currentRenderId = 0;
  5892. }
  5893. }
  5894. };
  5895. Engine.prototype.bindFramebuffer = function (texture) {
  5896. this._currentRenderTarget = texture;
  5897. var gl = this._gl;
  5898. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5899. this._gl.viewport(0, 0, texture._width, texture._height);
  5900. this.wipeCaches();
  5901. };
  5902. Engine.prototype.unBindFramebuffer = function (texture) {
  5903. this._currentRenderTarget = null;
  5904. if (texture.generateMipMaps) {
  5905. var gl = this._gl;
  5906. gl.bindTexture(gl.TEXTURE_2D, texture);
  5907. gl.generateMipmap(gl.TEXTURE_2D);
  5908. gl.bindTexture(gl.TEXTURE_2D, null);
  5909. }
  5910. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5911. };
  5912. Engine.prototype.flushFramebuffer = function () {
  5913. this._gl.flush();
  5914. };
  5915. Engine.prototype.restoreDefaultFramebuffer = function () {
  5916. this._currentRenderTarget = null;
  5917. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5918. this.setViewport(this._cachedViewport);
  5919. this.wipeCaches();
  5920. };
  5921. // VBOs
  5922. Engine.prototype._resetVertexBufferBinding = function () {
  5923. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5924. this._cachedVertexBuffers = null;
  5925. };
  5926. Engine.prototype.createVertexBuffer = function (vertices) {
  5927. var vbo = this._gl.createBuffer();
  5928. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5929. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5930. this._resetVertexBufferBinding();
  5931. vbo.references = 1;
  5932. return vbo;
  5933. };
  5934. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5935. var vbo = this._gl.createBuffer();
  5936. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5937. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5938. this._resetVertexBufferBinding();
  5939. vbo.references = 1;
  5940. return vbo;
  5941. };
  5942. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5943. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5944. if (offset === undefined) {
  5945. offset = 0;
  5946. }
  5947. if (vertices instanceof Float32Array) {
  5948. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5949. }
  5950. else {
  5951. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5952. }
  5953. this._resetVertexBufferBinding();
  5954. };
  5955. Engine.prototype._resetIndexBufferBinding = function () {
  5956. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5957. this._cachedIndexBuffer = null;
  5958. };
  5959. Engine.prototype.createIndexBuffer = function (indices) {
  5960. var vbo = this._gl.createBuffer();
  5961. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5962. // Check for 32 bits indices
  5963. var arrayBuffer;
  5964. var need32Bits = false;
  5965. if (this._caps.uintIndices) {
  5966. for (var index = 0; index < indices.length; index++) {
  5967. if (indices[index] > 65535) {
  5968. need32Bits = true;
  5969. break;
  5970. }
  5971. }
  5972. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5973. }
  5974. else {
  5975. arrayBuffer = new Uint16Array(indices);
  5976. }
  5977. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5978. this._resetIndexBufferBinding();
  5979. vbo.references = 1;
  5980. vbo.is32Bits = need32Bits;
  5981. return vbo;
  5982. };
  5983. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5984. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5985. this._cachedVertexBuffers = vertexBuffer;
  5986. this._cachedEffectForVertexBuffers = effect;
  5987. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5988. var offset = 0;
  5989. for (var index = 0; index < vertexDeclaration.length; index++) {
  5990. var order = effect.getAttributeLocation(index);
  5991. if (order >= 0) {
  5992. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5993. }
  5994. offset += vertexDeclaration[index] * 4;
  5995. }
  5996. }
  5997. if (this._cachedIndexBuffer !== indexBuffer) {
  5998. this._cachedIndexBuffer = indexBuffer;
  5999. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6000. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6001. }
  6002. };
  6003. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6004. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6005. this._cachedVertexBuffers = vertexBuffers;
  6006. this._cachedEffectForVertexBuffers = effect;
  6007. var attributes = effect.getAttributesNames();
  6008. for (var index = 0; index < attributes.length; index++) {
  6009. var order = effect.getAttributeLocation(index);
  6010. if (order >= 0) {
  6011. var vertexBuffer = vertexBuffers[attributes[index]];
  6012. if (!vertexBuffer) {
  6013. continue;
  6014. }
  6015. var stride = vertexBuffer.getStrideSize();
  6016. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6017. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6018. }
  6019. }
  6020. }
  6021. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6022. this._cachedIndexBuffer = indexBuffer;
  6023. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6024. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6025. }
  6026. };
  6027. Engine.prototype._releaseBuffer = function (buffer) {
  6028. buffer.references--;
  6029. if (buffer.references === 0) {
  6030. this._gl.deleteBuffer(buffer);
  6031. return true;
  6032. }
  6033. return false;
  6034. };
  6035. Engine.prototype.createInstancesBuffer = function (capacity) {
  6036. var buffer = this._gl.createBuffer();
  6037. buffer.capacity = capacity;
  6038. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6039. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6040. return buffer;
  6041. };
  6042. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6043. this._gl.deleteBuffer(buffer);
  6044. };
  6045. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6046. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6047. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6048. for (var index = 0; index < 4; index++) {
  6049. var offsetLocation = offsetLocations[index];
  6050. this._gl.enableVertexAttribArray(offsetLocation);
  6051. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6052. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6053. }
  6054. };
  6055. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6056. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6057. for (var index = 0; index < 4; index++) {
  6058. var offsetLocation = offsetLocations[index];
  6059. this._gl.disableVertexAttribArray(offsetLocation);
  6060. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6061. }
  6062. };
  6063. Engine.prototype.applyStates = function () {
  6064. this._depthCullingState.apply(this._gl);
  6065. this._alphaState.apply(this._gl);
  6066. };
  6067. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6068. // Apply states
  6069. this.applyStates();
  6070. this._drawCalls++;
  6071. // Render
  6072. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6073. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6074. if (instancesCount) {
  6075. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6076. return;
  6077. }
  6078. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6079. };
  6080. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6081. // Apply states
  6082. this.applyStates();
  6083. this._drawCalls++;
  6084. if (instancesCount) {
  6085. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6086. return;
  6087. }
  6088. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6089. };
  6090. // Shaders
  6091. Engine.prototype._releaseEffect = function (effect) {
  6092. if (this._compiledEffects[effect._key]) {
  6093. delete this._compiledEffects[effect._key];
  6094. if (effect.getProgram()) {
  6095. this._gl.deleteProgram(effect.getProgram());
  6096. }
  6097. }
  6098. };
  6099. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6100. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6101. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6102. var name = vertex + "+" + fragment + "@" + defines;
  6103. if (this._compiledEffects[name]) {
  6104. return this._compiledEffects[name];
  6105. }
  6106. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6107. effect._key = name;
  6108. this._compiledEffects[name] = effect;
  6109. return effect;
  6110. };
  6111. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6112. if (uniformsNames === void 0) { uniformsNames = []; }
  6113. if (samplers === void 0) { samplers = []; }
  6114. if (defines === void 0) { defines = ""; }
  6115. return this.createEffect({
  6116. vertex: "particles",
  6117. fragmentElement: fragmentName
  6118. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6119. };
  6120. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6121. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6122. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6123. var shaderProgram = this._gl.createProgram();
  6124. this._gl.attachShader(shaderProgram, vertexShader);
  6125. this._gl.attachShader(shaderProgram, fragmentShader);
  6126. this._gl.linkProgram(shaderProgram);
  6127. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6128. if (!linked) {
  6129. var error = this._gl.getProgramInfoLog(shaderProgram);
  6130. if (error) {
  6131. throw new Error(error);
  6132. }
  6133. }
  6134. this._gl.deleteShader(vertexShader);
  6135. this._gl.deleteShader(fragmentShader);
  6136. return shaderProgram;
  6137. };
  6138. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6139. var results = [];
  6140. for (var index = 0; index < uniformsNames.length; index++) {
  6141. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6142. }
  6143. return results;
  6144. };
  6145. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6146. var results = [];
  6147. for (var index = 0; index < attributesNames.length; index++) {
  6148. try {
  6149. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6150. }
  6151. catch (e) {
  6152. results.push(-1);
  6153. }
  6154. }
  6155. return results;
  6156. };
  6157. Engine.prototype.enableEffect = function (effect) {
  6158. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6159. if (effect && effect.onBind) {
  6160. effect.onBind(effect);
  6161. }
  6162. return;
  6163. }
  6164. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6165. // Use program
  6166. this._gl.useProgram(effect.getProgram());
  6167. for (var i in this._vertexAttribArrays) {
  6168. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6169. continue;
  6170. }
  6171. this._vertexAttribArrays[i] = false;
  6172. this._gl.disableVertexAttribArray(i);
  6173. }
  6174. var attributesCount = effect.getAttributesCount();
  6175. for (var index = 0; index < attributesCount; index++) {
  6176. // Attributes
  6177. var order = effect.getAttributeLocation(index);
  6178. if (order >= 0) {
  6179. this._vertexAttribArrays[order] = true;
  6180. this._gl.enableVertexAttribArray(order);
  6181. }
  6182. }
  6183. this._currentEffect = effect;
  6184. if (effect.onBind) {
  6185. effect.onBind(effect);
  6186. }
  6187. };
  6188. Engine.prototype.setArray = function (uniform, array) {
  6189. if (!uniform)
  6190. return;
  6191. this._gl.uniform1fv(uniform, array);
  6192. };
  6193. Engine.prototype.setArray2 = function (uniform, array) {
  6194. if (!uniform || array.length % 2 !== 0)
  6195. return;
  6196. this._gl.uniform2fv(uniform, array);
  6197. };
  6198. Engine.prototype.setArray3 = function (uniform, array) {
  6199. if (!uniform || array.length % 3 !== 0)
  6200. return;
  6201. this._gl.uniform3fv(uniform, array);
  6202. };
  6203. Engine.prototype.setArray4 = function (uniform, array) {
  6204. if (!uniform || array.length % 4 !== 0)
  6205. return;
  6206. this._gl.uniform4fv(uniform, array);
  6207. };
  6208. Engine.prototype.setMatrices = function (uniform, matrices) {
  6209. if (!uniform)
  6210. return;
  6211. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6212. };
  6213. Engine.prototype.setMatrix = function (uniform, matrix) {
  6214. if (!uniform)
  6215. return;
  6216. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6217. };
  6218. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6219. if (!uniform)
  6220. return;
  6221. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6222. };
  6223. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6224. if (!uniform)
  6225. return;
  6226. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6227. };
  6228. Engine.prototype.setFloat = function (uniform, value) {
  6229. if (!uniform)
  6230. return;
  6231. this._gl.uniform1f(uniform, value);
  6232. };
  6233. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6234. if (!uniform)
  6235. return;
  6236. this._gl.uniform2f(uniform, x, y);
  6237. };
  6238. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6239. if (!uniform)
  6240. return;
  6241. this._gl.uniform3f(uniform, x, y, z);
  6242. };
  6243. Engine.prototype.setBool = function (uniform, bool) {
  6244. if (!uniform)
  6245. return;
  6246. this._gl.uniform1i(uniform, bool);
  6247. };
  6248. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6249. if (!uniform)
  6250. return;
  6251. this._gl.uniform4f(uniform, x, y, z, w);
  6252. };
  6253. Engine.prototype.setColor3 = function (uniform, color3) {
  6254. if (!uniform)
  6255. return;
  6256. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6257. };
  6258. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6259. if (!uniform)
  6260. return;
  6261. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6262. };
  6263. // States
  6264. Engine.prototype.setState = function (culling, zOffset, force) {
  6265. if (zOffset === void 0) { zOffset = 0; }
  6266. // Culling
  6267. if (this._depthCullingState.cull !== culling || force) {
  6268. if (culling) {
  6269. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6270. this._depthCullingState.cull = true;
  6271. }
  6272. else {
  6273. this._depthCullingState.cull = false;
  6274. }
  6275. }
  6276. // Z offset
  6277. this._depthCullingState.zOffset = zOffset;
  6278. };
  6279. Engine.prototype.setDepthBuffer = function (enable) {
  6280. this._depthCullingState.depthTest = enable;
  6281. };
  6282. Engine.prototype.getDepthWrite = function () {
  6283. return this._depthCullingState.depthMask;
  6284. };
  6285. Engine.prototype.setDepthWrite = function (enable) {
  6286. this._depthCullingState.depthMask = enable;
  6287. };
  6288. Engine.prototype.setColorWrite = function (enable) {
  6289. this._gl.colorMask(enable, enable, enable, enable);
  6290. };
  6291. Engine.prototype.setAlphaMode = function (mode) {
  6292. if (this._alphaMode == mode) {
  6293. return;
  6294. }
  6295. switch (mode) {
  6296. case Engine.ALPHA_DISABLE:
  6297. this.setDepthWrite(true);
  6298. this._alphaState.alphaBlend = false;
  6299. break;
  6300. case Engine.ALPHA_COMBINE:
  6301. this.setDepthWrite(false);
  6302. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6303. this._alphaState.alphaBlend = true;
  6304. break;
  6305. case Engine.ALPHA_ONEONE:
  6306. this.setDepthWrite(false);
  6307. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6308. this._alphaState.alphaBlend = true;
  6309. break;
  6310. case Engine.ALPHA_ADD:
  6311. this.setDepthWrite(false);
  6312. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6313. this._alphaState.alphaBlend = true;
  6314. break;
  6315. case Engine.ALPHA_SUBTRACT:
  6316. this.setDepthWrite(false);
  6317. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6318. this._alphaState.alphaBlend = true;
  6319. break;
  6320. case Engine.ALPHA_MULTIPLY:
  6321. this.setDepthWrite(false);
  6322. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6323. this._alphaState.alphaBlend = true;
  6324. break;
  6325. case Engine.ALPHA_MAXIMIZED:
  6326. this.setDepthWrite(false);
  6327. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6328. this._alphaState.alphaBlend = true;
  6329. break;
  6330. }
  6331. this._alphaMode = mode;
  6332. };
  6333. Engine.prototype.getAlphaMode = function () {
  6334. return this._alphaMode;
  6335. };
  6336. Engine.prototype.setAlphaTesting = function (enable) {
  6337. this._alphaTest = enable;
  6338. };
  6339. Engine.prototype.getAlphaTesting = function () {
  6340. return this._alphaTest;
  6341. };
  6342. // Textures
  6343. Engine.prototype.wipeCaches = function () {
  6344. this._activeTexturesCache = [];
  6345. this._currentEffect = null;
  6346. this._depthCullingState.reset();
  6347. this._alphaState.reset();
  6348. this._cachedVertexBuffers = null;
  6349. this._cachedIndexBuffer = null;
  6350. this._cachedEffectForVertexBuffers = null;
  6351. };
  6352. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6353. var gl = this._gl;
  6354. gl.bindTexture(gl.TEXTURE_2D, texture);
  6355. var magFilter = gl.NEAREST;
  6356. var minFilter = gl.NEAREST;
  6357. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6358. magFilter = gl.LINEAR;
  6359. minFilter = gl.LINEAR;
  6360. }
  6361. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6362. magFilter = gl.LINEAR;
  6363. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6364. }
  6365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6367. gl.bindTexture(gl.TEXTURE_2D, null);
  6368. texture.samplingMode = samplingMode;
  6369. };
  6370. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6371. var _this = this;
  6372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6373. if (onLoad === void 0) { onLoad = null; }
  6374. if (onError === void 0) { onError = null; }
  6375. if (buffer === void 0) { buffer = null; }
  6376. var texture = this._gl.createTexture();
  6377. var extension;
  6378. var fromData = false;
  6379. if (url.substr(0, 5) === "data:") {
  6380. fromData = true;
  6381. }
  6382. if (!fromData)
  6383. extension = url.substr(url.length - 4, 4).toLowerCase();
  6384. else {
  6385. var oldUrl = url;
  6386. fromData = oldUrl.split(':');
  6387. url = oldUrl;
  6388. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6389. }
  6390. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6391. var isTGA = (extension === ".tga");
  6392. scene._addPendingData(texture);
  6393. texture.url = url;
  6394. texture.noMipmap = noMipmap;
  6395. texture.references = 1;
  6396. texture.samplingMode = samplingMode;
  6397. this._loadedTexturesCache.push(texture);
  6398. var onerror = function () {
  6399. scene._removePendingData(texture);
  6400. if (onError) {
  6401. onError();
  6402. }
  6403. };
  6404. if (isTGA) {
  6405. var callback = function (arrayBuffer) {
  6406. var data = new Uint8Array(arrayBuffer);
  6407. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6408. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6409. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6410. if (onLoad) {
  6411. onLoad();
  6412. }
  6413. }, samplingMode);
  6414. };
  6415. if (!(fromData instanceof Array))
  6416. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6417. callback(arrayBuffer);
  6418. }, onerror, scene.database, true);
  6419. else
  6420. callback(buffer);
  6421. }
  6422. else if (isDDS) {
  6423. callback = function (data) {
  6424. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6425. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6426. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6427. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6428. if (onLoad) {
  6429. onLoad();
  6430. }
  6431. }, samplingMode);
  6432. };
  6433. if (!(fromData instanceof Array))
  6434. BABYLON.Tools.LoadFile(url, function (data) {
  6435. callback(data);
  6436. }, onerror, scene.database, true);
  6437. else
  6438. callback(buffer);
  6439. }
  6440. else {
  6441. var onload = function (img) {
  6442. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6443. var isPot = (img.width === potWidth && img.height === potHeight);
  6444. if (!isPot) {
  6445. _this._prepareWorkingCanvas();
  6446. _this._workingCanvas.width = potWidth;
  6447. _this._workingCanvas.height = potHeight;
  6448. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6449. _this._workingContext.imageSmoothingEnabled = false;
  6450. _this._workingContext.mozImageSmoothingEnabled = false;
  6451. _this._workingContext.oImageSmoothingEnabled = false;
  6452. _this._workingContext.webkitImageSmoothingEnabled = false;
  6453. _this._workingContext.msImageSmoothingEnabled = false;
  6454. }
  6455. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6456. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6457. _this._workingContext.imageSmoothingEnabled = true;
  6458. _this._workingContext.mozImageSmoothingEnabled = true;
  6459. _this._workingContext.oImageSmoothingEnabled = true;
  6460. _this._workingContext.webkitImageSmoothingEnabled = true;
  6461. _this._workingContext.msImageSmoothingEnabled = true;
  6462. }
  6463. }
  6464. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6465. if (onLoad) {
  6466. onLoad();
  6467. }
  6468. }, samplingMode);
  6469. };
  6470. if (!(fromData instanceof Array))
  6471. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6472. else
  6473. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6474. }
  6475. return texture;
  6476. };
  6477. Engine.prototype.updateRawTexture = function (texture, data, format, invertY) {
  6478. var internalFormat = this._gl.RGBA;
  6479. switch (format) {
  6480. case Engine.TEXTUREFORMAT_ALPHA:
  6481. internalFormat = this._gl.ALPHA;
  6482. break;
  6483. case Engine.TEXTUREFORMAT_LUMINANCE:
  6484. internalFormat = this._gl.LUMINANCE;
  6485. break;
  6486. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6487. internalFormat = this._gl.LUMINANCE_ALPHA;
  6488. break;
  6489. case Engine.TEXTUREFORMAT_RGB:
  6490. internalFormat = this._gl.RGB;
  6491. break;
  6492. case Engine.TEXTUREFORMAT_RGBA:
  6493. internalFormat = this._gl.RGBA;
  6494. break;
  6495. }
  6496. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6497. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6498. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6499. if (texture.generateMipMaps) {
  6500. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6501. }
  6502. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6503. this._activeTexturesCache = [];
  6504. texture.isReady = true;
  6505. };
  6506. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6507. var texture = this._gl.createTexture();
  6508. texture._baseWidth = width;
  6509. texture._baseHeight = height;
  6510. texture._width = width;
  6511. texture._height = height;
  6512. texture.references = 1;
  6513. this.updateRawTexture(texture, data, format, invertY);
  6514. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6515. // Filters
  6516. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6517. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6518. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6519. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6520. texture.samplingMode = samplingMode;
  6521. this._loadedTexturesCache.push(texture);
  6522. return texture;
  6523. };
  6524. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6525. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6526. var texture = this._gl.createTexture();
  6527. texture._baseWidth = width;
  6528. texture._baseHeight = height;
  6529. if (forceExponantOfTwo) {
  6530. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6531. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6532. }
  6533. this._activeTexturesCache = [];
  6534. texture._width = width;
  6535. texture._height = height;
  6536. texture.isReady = false;
  6537. texture.generateMipMaps = generateMipMaps;
  6538. texture.references = 1;
  6539. texture.samplingMode = samplingMode;
  6540. this.updateTextureSamplingMode(samplingMode, texture);
  6541. this._loadedTexturesCache.push(texture);
  6542. return texture;
  6543. };
  6544. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6545. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6546. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6547. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6548. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6549. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6550. };
  6551. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6552. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6553. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6554. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6555. if (texture.generateMipMaps) {
  6556. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6557. }
  6558. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6559. this._activeTexturesCache = [];
  6560. texture.isReady = true;
  6561. };
  6562. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6563. if (texture._isDisabled) {
  6564. return;
  6565. }
  6566. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6567. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6568. try {
  6569. // Testing video texture support
  6570. if (this._videoTextureSupported === undefined) {
  6571. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6572. if (this._gl.getError() !== 0) {
  6573. this._videoTextureSupported = false;
  6574. }
  6575. else {
  6576. this._videoTextureSupported = true;
  6577. }
  6578. }
  6579. // Copy video through the current working canvas if video texture is not supported
  6580. if (!this._videoTextureSupported) {
  6581. if (!texture._workingCanvas) {
  6582. texture._workingCanvas = document.createElement("canvas");
  6583. texture._workingContext = texture._workingCanvas.getContext("2d");
  6584. texture._workingCanvas.width = texture._width;
  6585. texture._workingCanvas.height = texture._height;
  6586. }
  6587. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6588. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6589. }
  6590. else {
  6591. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6592. }
  6593. if (texture.generateMipMaps) {
  6594. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6595. }
  6596. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6597. this._activeTexturesCache = [];
  6598. texture.isReady = true;
  6599. }
  6600. catch (ex) {
  6601. // Something unexpected
  6602. // Let's disable the texture
  6603. texture._isDisabled = true;
  6604. }
  6605. };
  6606. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6607. // old version had a "generateMipMaps" arg instead of options.
  6608. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6609. // in the same way, generateDepthBuffer is defaulted to true
  6610. var generateMipMaps = false;
  6611. var generateDepthBuffer = true;
  6612. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6613. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6614. if (options !== undefined) {
  6615. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6616. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6617. type = options.type === undefined ? type : options.type;
  6618. if (options.samplingMode !== undefined) {
  6619. samplingMode = options.samplingMode;
  6620. }
  6621. if (type === Engine.TEXTURETYPE_FLOAT) {
  6622. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6623. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6624. }
  6625. }
  6626. var gl = this._gl;
  6627. var texture = gl.createTexture();
  6628. gl.bindTexture(gl.TEXTURE_2D, texture);
  6629. var width = size.width || size;
  6630. var height = size.height || size;
  6631. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6632. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6633. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6634. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6635. }
  6636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6637. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6638. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6639. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6640. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6641. var depthBuffer;
  6642. // Create the depth buffer
  6643. if (generateDepthBuffer) {
  6644. depthBuffer = gl.createRenderbuffer();
  6645. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6646. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6647. }
  6648. // Create the framebuffer
  6649. var framebuffer = gl.createFramebuffer();
  6650. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6651. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6652. if (generateDepthBuffer) {
  6653. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6654. }
  6655. if (generateMipMaps) {
  6656. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6657. }
  6658. // Unbind
  6659. gl.bindTexture(gl.TEXTURE_2D, null);
  6660. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6661. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6662. texture._framebuffer = framebuffer;
  6663. if (generateDepthBuffer) {
  6664. texture._depthBuffer = depthBuffer;
  6665. }
  6666. texture._width = width;
  6667. texture._height = height;
  6668. texture.isReady = true;
  6669. texture.generateMipMaps = generateMipMaps;
  6670. texture.references = 1;
  6671. texture.samplingMode = samplingMode;
  6672. this._activeTexturesCache = [];
  6673. this._loadedTexturesCache.push(texture);
  6674. return texture;
  6675. };
  6676. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6677. var _this = this;
  6678. var gl = this._gl;
  6679. var texture = gl.createTexture();
  6680. texture.isCube = true;
  6681. texture.url = rootUrl;
  6682. texture.references = 1;
  6683. this._loadedTexturesCache.push(texture);
  6684. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6685. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6686. if (isDDS) {
  6687. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6688. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6689. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6690. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6691. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6692. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6693. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6694. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6695. }
  6696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6698. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6700. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6701. _this._activeTexturesCache = [];
  6702. texture._width = info.width;
  6703. texture._height = info.height;
  6704. texture.isReady = true;
  6705. }, null, null, true);
  6706. }
  6707. else {
  6708. cascadeLoad(rootUrl, scene, function (imgs) {
  6709. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6710. var height = width;
  6711. _this._prepareWorkingCanvas();
  6712. _this._workingCanvas.width = width;
  6713. _this._workingCanvas.height = height;
  6714. var faces = [
  6715. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6716. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6717. ];
  6718. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6719. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6720. for (var index = 0; index < faces.length; index++) {
  6721. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6722. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6723. }
  6724. if (!noMipmap) {
  6725. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6726. }
  6727. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6728. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6729. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6731. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6732. _this._activeTexturesCache = [];
  6733. texture._width = width;
  6734. texture._height = height;
  6735. texture.isReady = true;
  6736. }, extensions);
  6737. }
  6738. return texture;
  6739. };
  6740. Engine.prototype._releaseTexture = function (texture) {
  6741. var gl = this._gl;
  6742. if (texture._framebuffer) {
  6743. gl.deleteFramebuffer(texture._framebuffer);
  6744. }
  6745. if (texture._depthBuffer) {
  6746. gl.deleteRenderbuffer(texture._depthBuffer);
  6747. }
  6748. gl.deleteTexture(texture);
  6749. // Unbind channels
  6750. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6751. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6752. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6753. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6754. this._activeTexturesCache[channel] = null;
  6755. }
  6756. var index = this._loadedTexturesCache.indexOf(texture);
  6757. if (index !== -1) {
  6758. this._loadedTexturesCache.splice(index, 1);
  6759. }
  6760. };
  6761. Engine.prototype.bindSamplers = function (effect) {
  6762. this._gl.useProgram(effect.getProgram());
  6763. var samplers = effect.getSamplers();
  6764. for (var index = 0; index < samplers.length; index++) {
  6765. var uniform = effect.getUniform(samplers[index]);
  6766. this._gl.uniform1i(uniform, index);
  6767. }
  6768. this._currentEffect = null;
  6769. };
  6770. Engine.prototype._bindTexture = function (channel, texture) {
  6771. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6772. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6773. this._activeTexturesCache[channel] = null;
  6774. };
  6775. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6776. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6777. };
  6778. Engine.prototype.setTexture = function (channel, texture) {
  6779. if (channel < 0) {
  6780. return;
  6781. }
  6782. // Not ready?
  6783. if (!texture || !texture.isReady()) {
  6784. if (this._activeTexturesCache[channel] != null) {
  6785. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6786. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6787. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6788. this._activeTexturesCache[channel] = null;
  6789. }
  6790. return;
  6791. }
  6792. // Video
  6793. if (texture instanceof BABYLON.VideoTexture) {
  6794. if (texture.update()) {
  6795. this._activeTexturesCache[channel] = null;
  6796. }
  6797. }
  6798. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6799. texture.delayLoad();
  6800. return;
  6801. }
  6802. if (this._activeTexturesCache[channel] === texture) {
  6803. return;
  6804. }
  6805. this._activeTexturesCache[channel] = texture;
  6806. var internalTexture = texture.getInternalTexture();
  6807. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6808. if (internalTexture.isCube) {
  6809. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6810. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6811. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6812. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6813. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6814. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6815. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6816. }
  6817. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6818. }
  6819. else {
  6820. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6821. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6822. internalTexture._cachedWrapU = texture.wrapU;
  6823. switch (texture.wrapU) {
  6824. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6825. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6826. break;
  6827. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6828. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6829. break;
  6830. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6831. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6832. break;
  6833. }
  6834. }
  6835. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6836. internalTexture._cachedWrapV = texture.wrapV;
  6837. switch (texture.wrapV) {
  6838. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6839. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6840. break;
  6841. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6842. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6843. break;
  6844. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6845. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6846. break;
  6847. }
  6848. }
  6849. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6850. }
  6851. };
  6852. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6853. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6854. var value = texture.anisotropicFilteringLevel;
  6855. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6856. value = 1;
  6857. }
  6858. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6859. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6860. texture._cachedAnisotropicFilteringLevel = value;
  6861. }
  6862. };
  6863. Engine.prototype.readPixels = function (x, y, width, height) {
  6864. var data = new Uint8Array(height * width * 4);
  6865. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6866. return data;
  6867. };
  6868. // Dispose
  6869. Engine.prototype.dispose = function () {
  6870. this.hideLoadingUI();
  6871. this.stopRenderLoop();
  6872. // Release scenes
  6873. while (this.scenes.length) {
  6874. this.scenes[0].dispose();
  6875. }
  6876. // Release audio engine
  6877. Engine.audioEngine.dispose();
  6878. // Release effects
  6879. for (var name in this._compiledEffects) {
  6880. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6881. }
  6882. // Unbind
  6883. for (var i in this._vertexAttribArrays) {
  6884. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6885. continue;
  6886. }
  6887. this._gl.disableVertexAttribArray(i);
  6888. }
  6889. this._gl = null;
  6890. // Events
  6891. window.removeEventListener("blur", this._onBlur);
  6892. window.removeEventListener("focus", this._onFocus);
  6893. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6894. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6895. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6896. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6897. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6898. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6899. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6900. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6901. };
  6902. // Loading screen
  6903. Engine.prototype.displayLoadingUI = function () {
  6904. var _this = this;
  6905. this._loadingDiv = document.createElement("div");
  6906. this._loadingDiv.style.opacity = "0";
  6907. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6908. // Loading text
  6909. this._loadingTextDiv = document.createElement("div");
  6910. this._loadingTextDiv.style.position = "absolute";
  6911. this._loadingTextDiv.style.left = "0";
  6912. this._loadingTextDiv.style.top = "50%";
  6913. this._loadingTextDiv.style.marginTop = "80px";
  6914. this._loadingTextDiv.style.width = "100%";
  6915. this._loadingTextDiv.style.height = "20px";
  6916. this._loadingTextDiv.style.fontFamily = "Arial";
  6917. this._loadingTextDiv.style.fontSize = "14px";
  6918. this._loadingTextDiv.style.color = "white";
  6919. this._loadingTextDiv.style.textAlign = "center";
  6920. this._loadingTextDiv.innerHTML = "Loading";
  6921. this._loadingDiv.appendChild(this._loadingTextDiv);
  6922. // Loading img
  6923. var imgBack = new Image();
  6924. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  6925. imgBack.style.position = "absolute";
  6926. imgBack.style.left = "50%";
  6927. imgBack.style.top = "50%";
  6928. imgBack.style.marginLeft = "-50px";
  6929. imgBack.style.marginTop = "-50px";
  6930. imgBack.style.transition = "transform 1.0s ease";
  6931. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6932. var deg = 360;
  6933. var onTransitionEnd = function () {
  6934. deg += 360;
  6935. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6936. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6937. };
  6938. imgBack.addEventListener("transitionend", onTransitionEnd);
  6939. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6940. this._loadingDiv.appendChild(imgBack);
  6941. // front image
  6942. var imgFront = new Image();
  6943. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  6944. imgFront.style.position = "absolute";
  6945. imgFront.style.left = "50%";
  6946. imgFront.style.top = "50%";
  6947. imgFront.style.marginLeft = "-50px";
  6948. imgFront.style.marginTop = "-50px";
  6949. this._loadingDiv.appendChild(imgFront);
  6950. // Resize
  6951. this._resizeLoadingUI = function () {
  6952. var canvasRect = _this.getRenderingCanvasClientRect();
  6953. _this._loadingDiv.style.position = "absolute";
  6954. _this._loadingDiv.style.left = canvasRect.left + "px";
  6955. _this._loadingDiv.style.top = canvasRect.top + "px";
  6956. _this._loadingDiv.style.width = canvasRect.width + "px";
  6957. _this._loadingDiv.style.height = canvasRect.height + "px";
  6958. };
  6959. this._resizeLoadingUI();
  6960. window.addEventListener("resize", this._resizeLoadingUI);
  6961. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6962. document.body.appendChild(this._loadingDiv);
  6963. setTimeout(function () {
  6964. _this._loadingDiv.style.opacity = "1";
  6965. imgBack.style.transform = "rotateZ(360deg)";
  6966. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6967. }, 0);
  6968. };
  6969. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6970. set: function (text) {
  6971. if (!this._loadingDiv) {
  6972. return;
  6973. }
  6974. this._loadingTextDiv.innerHTML = text;
  6975. },
  6976. enumerable: true,
  6977. configurable: true
  6978. });
  6979. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6980. get: function () {
  6981. return this._loadingDivBackgroundColor;
  6982. },
  6983. set: function (color) {
  6984. this._loadingDivBackgroundColor = color;
  6985. if (!this._loadingDiv) {
  6986. return;
  6987. }
  6988. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6989. },
  6990. enumerable: true,
  6991. configurable: true
  6992. });
  6993. Engine.prototype.hideLoadingUI = function () {
  6994. var _this = this;
  6995. if (!this._loadingDiv) {
  6996. return;
  6997. }
  6998. var onTransitionEnd = function () {
  6999. if (!_this._loadingDiv) {
  7000. return;
  7001. }
  7002. document.body.removeChild(_this._loadingDiv);
  7003. window.removeEventListener("resize", _this._resizeLoadingUI);
  7004. _this._loadingDiv = null;
  7005. };
  7006. this._loadingDiv.style.opacity = "0";
  7007. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  7008. };
  7009. // FPS
  7010. Engine.prototype.getFps = function () {
  7011. return this.fps;
  7012. };
  7013. Engine.prototype.getDeltaTime = function () {
  7014. return this.deltaTime;
  7015. };
  7016. Engine.prototype._measureFps = function () {
  7017. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7018. var length = this.previousFramesDuration.length;
  7019. if (length >= 2) {
  7020. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7021. }
  7022. if (length >= this.fpsRange) {
  7023. if (length > this.fpsRange) {
  7024. this.previousFramesDuration.splice(0, 1);
  7025. length = this.previousFramesDuration.length;
  7026. }
  7027. var sum = 0;
  7028. for (var id = 0; id < length - 1; id++) {
  7029. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7030. }
  7031. this.fps = 1000.0 / (sum / (length - 1));
  7032. }
  7033. };
  7034. // Statics
  7035. Engine.isSupported = function () {
  7036. try {
  7037. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7038. if (navigator.isCocoonJS) {
  7039. return true;
  7040. }
  7041. var tempcanvas = document.createElement("canvas");
  7042. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7043. return gl != null && !!window.WebGLRenderingContext;
  7044. }
  7045. catch (e) {
  7046. return false;
  7047. }
  7048. };
  7049. // Const statics
  7050. Engine._ALPHA_DISABLE = 0;
  7051. Engine._ALPHA_ADD = 1;
  7052. Engine._ALPHA_COMBINE = 2;
  7053. Engine._ALPHA_SUBTRACT = 3;
  7054. Engine._ALPHA_MULTIPLY = 4;
  7055. Engine._ALPHA_MAXIMIZED = 5;
  7056. Engine._ALPHA_ONEONE = 6;
  7057. Engine._DELAYLOADSTATE_NONE = 0;
  7058. Engine._DELAYLOADSTATE_LOADED = 1;
  7059. Engine._DELAYLOADSTATE_LOADING = 2;
  7060. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7061. Engine._TEXTUREFORMAT_ALPHA = 0;
  7062. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7063. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7064. Engine._TEXTUREFORMAT_RGB = 4;
  7065. Engine._TEXTUREFORMAT_RGBA = 5;
  7066. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7067. Engine._TEXTURETYPE_FLOAT = 1;
  7068. // Updatable statics so stick with vars here
  7069. Engine.Epsilon = 0.001;
  7070. Engine.CollisionsEpsilon = 0.001;
  7071. Engine.CodeRepository = "src/";
  7072. Engine.ShadersRepository = "src/Shaders/";
  7073. return Engine;
  7074. })();
  7075. BABYLON.Engine = Engine;
  7076. })(BABYLON || (BABYLON = {}));
  7077. var BABYLON;
  7078. (function (BABYLON) {
  7079. /**
  7080. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7081. */
  7082. var Node = (function () {
  7083. /**
  7084. * @constructor
  7085. * @param {string} name - the name and id to be given to this node
  7086. * @param {BABYLON.Scene} the scene this node will be added to
  7087. */
  7088. function Node(name, scene) {
  7089. this.state = "";
  7090. this.animations = new Array();
  7091. this._childrenFlag = -1;
  7092. this._isEnabled = true;
  7093. this._isReady = true;
  7094. this._currentRenderId = -1;
  7095. this._parentRenderId = -1;
  7096. this.name = name;
  7097. this.id = name;
  7098. this._scene = scene;
  7099. this._initCache();
  7100. }
  7101. Node.prototype.getScene = function () {
  7102. return this._scene;
  7103. };
  7104. Node.prototype.getEngine = function () {
  7105. return this._scene.getEngine();
  7106. };
  7107. // override it in derived class
  7108. Node.prototype.getWorldMatrix = function () {
  7109. return BABYLON.Matrix.Identity();
  7110. };
  7111. // override it in derived class if you add new variables to the cache
  7112. // and call the parent class method
  7113. Node.prototype._initCache = function () {
  7114. this._cache = {};
  7115. this._cache.parent = undefined;
  7116. };
  7117. Node.prototype.updateCache = function (force) {
  7118. if (!force && this.isSynchronized())
  7119. return;
  7120. this._cache.parent = this.parent;
  7121. this._updateCache();
  7122. };
  7123. // override it in derived class if you add new variables to the cache
  7124. // and call the parent class method if !ignoreParentClass
  7125. Node.prototype._updateCache = function (ignoreParentClass) {
  7126. };
  7127. // override it in derived class if you add new variables to the cache
  7128. Node.prototype._isSynchronized = function () {
  7129. return true;
  7130. };
  7131. Node.prototype._markSyncedWithParent = function () {
  7132. this._parentRenderId = this.parent._currentRenderId;
  7133. };
  7134. Node.prototype.isSynchronizedWithParent = function () {
  7135. if (!this.parent) {
  7136. return true;
  7137. }
  7138. if (this._parentRenderId !== this.parent._currentRenderId) {
  7139. return false;
  7140. }
  7141. return this.parent.isSynchronized();
  7142. };
  7143. Node.prototype.isSynchronized = function (updateCache) {
  7144. var check = this.hasNewParent();
  7145. check = check || !this.isSynchronizedWithParent();
  7146. check = check || !this._isSynchronized();
  7147. if (updateCache)
  7148. this.updateCache(true);
  7149. return !check;
  7150. };
  7151. Node.prototype.hasNewParent = function (update) {
  7152. if (this._cache.parent === this.parent)
  7153. return false;
  7154. if (update)
  7155. this._cache.parent = this.parent;
  7156. return true;
  7157. };
  7158. /**
  7159. * Is this node ready to be used/rendered
  7160. * @return {boolean} is it ready
  7161. */
  7162. Node.prototype.isReady = function () {
  7163. return this._isReady;
  7164. };
  7165. /**
  7166. * Is this node enabled.
  7167. * If the node has a parent and is enabled, the parent will be inspected as well.
  7168. * @return {boolean} whether this node (and its parent) is enabled.
  7169. * @see setEnabled
  7170. */
  7171. Node.prototype.isEnabled = function () {
  7172. if (!this._isEnabled) {
  7173. return false;
  7174. }
  7175. if (this.parent) {
  7176. return this.parent.isEnabled();
  7177. }
  7178. return true;
  7179. };
  7180. /**
  7181. * Set the enabled state of this node.
  7182. * @param {boolean} value - the new enabled state
  7183. * @see isEnabled
  7184. */
  7185. Node.prototype.setEnabled = function (value) {
  7186. this._isEnabled = value;
  7187. };
  7188. /**
  7189. * Is this node a descendant of the given node.
  7190. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7191. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7192. * @see parent
  7193. */
  7194. Node.prototype.isDescendantOf = function (ancestor) {
  7195. if (this.parent) {
  7196. if (this.parent === ancestor) {
  7197. return true;
  7198. }
  7199. return this.parent.isDescendantOf(ancestor);
  7200. }
  7201. return false;
  7202. };
  7203. Node.prototype._getDescendants = function (list, results) {
  7204. for (var index = 0; index < list.length; index++) {
  7205. var item = list[index];
  7206. if (item.isDescendantOf(this)) {
  7207. results.push(item);
  7208. }
  7209. }
  7210. };
  7211. /**
  7212. * Will return all nodes that have this node as parent.
  7213. * @return {BABYLON.Node[]} all children nodes of all types.
  7214. */
  7215. Node.prototype.getDescendants = function () {
  7216. var results = [];
  7217. this._getDescendants(this._scene.meshes, results);
  7218. this._getDescendants(this._scene.lights, results);
  7219. this._getDescendants(this._scene.cameras, results);
  7220. return results;
  7221. };
  7222. Node.prototype._setReady = function (state) {
  7223. if (state == this._isReady) {
  7224. return;
  7225. }
  7226. if (!state) {
  7227. this._isReady = false;
  7228. return;
  7229. }
  7230. this._isReady = true;
  7231. if (this.onReady) {
  7232. this.onReady(this);
  7233. }
  7234. };
  7235. return Node;
  7236. })();
  7237. BABYLON.Node = Node;
  7238. })(BABYLON || (BABYLON = {}));
  7239. var BABYLON;
  7240. (function (BABYLON) {
  7241. var FilesInput = (function () {
  7242. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7243. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7244. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7245. this._engine = p_engine;
  7246. this._canvas = p_canvas;
  7247. this._currentScene = p_scene;
  7248. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7249. this._progressCallback = p_progressCallback;
  7250. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7251. this._textureLoadingCallback = p_textureLoadingCallback;
  7252. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7253. }
  7254. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7255. var _this = this;
  7256. if (p_elementToMonitor) {
  7257. this._elementToMonitor = p_elementToMonitor;
  7258. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7259. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7260. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7261. }
  7262. };
  7263. FilesInput.prototype.renderFunction = function () {
  7264. if (this._additionnalRenderLoopLogicCallback) {
  7265. this._additionnalRenderLoopLogicCallback();
  7266. }
  7267. if (this._currentScene) {
  7268. if (this._textureLoadingCallback) {
  7269. var remaining = this._currentScene.getWaitingItemsCount();
  7270. if (remaining > 0) {
  7271. this._textureLoadingCallback(remaining);
  7272. }
  7273. }
  7274. this._currentScene.render();
  7275. }
  7276. };
  7277. FilesInput.prototype.drag = function (e) {
  7278. e.stopPropagation();
  7279. e.preventDefault();
  7280. };
  7281. FilesInput.prototype.drop = function (eventDrop) {
  7282. eventDrop.stopPropagation();
  7283. eventDrop.preventDefault();
  7284. this.loadFiles(eventDrop);
  7285. };
  7286. FilesInput.prototype.loadFiles = function (event) {
  7287. if (this._startingProcessingFilesCallback)
  7288. this._startingProcessingFilesCallback();
  7289. // Handling data transfer via drag'n'drop
  7290. if (event && event.dataTransfer && event.dataTransfer.files) {
  7291. this._filesToLoad = event.dataTransfer.files;
  7292. }
  7293. // Handling files from input files
  7294. if (event && event.target && event.target.files) {
  7295. this._filesToLoad = event.target.files;
  7296. }
  7297. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7298. for (var i = 0; i < this._filesToLoad.length; i++) {
  7299. switch (this._filesToLoad[i].type) {
  7300. case "image/jpeg":
  7301. case "image/png":
  7302. case "image/bmp":
  7303. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7304. break;
  7305. case "image/targa":
  7306. case "image/vnd.ms-dds":
  7307. case "audio/wav":
  7308. case "audio/x-wav":
  7309. case "audio/mp3":
  7310. case "audio/mpeg":
  7311. case "audio/mpeg3":
  7312. case "audio/x-mpeg-3":
  7313. case "audio/ogg":
  7314. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7315. break;
  7316. default:
  7317. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7318. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7319. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7320. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7321. this._sceneFileToLoad = this._filesToLoad[i];
  7322. }
  7323. break;
  7324. }
  7325. }
  7326. this.reload();
  7327. }
  7328. };
  7329. FilesInput.prototype.reload = function () {
  7330. var _this = this;
  7331. var that = this;
  7332. // If a ".babylon" file has been provided
  7333. if (this._sceneFileToLoad) {
  7334. if (this._currentScene) {
  7335. if (BABYLON.Tools.errorsCount > 0) {
  7336. BABYLON.Tools.ClearLogCache();
  7337. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7338. }
  7339. this._engine.stopRenderLoop();
  7340. this._currentScene.dispose();
  7341. }
  7342. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7343. that._currentScene = newScene;
  7344. // Wait for textures and shaders to be ready
  7345. that._currentScene.executeWhenReady(function () {
  7346. // Attach camera to canvas inputs
  7347. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7348. that._currentScene.createDefaultCameraOrLight();
  7349. }
  7350. that._currentScene.activeCamera.attachControl(that._canvas);
  7351. if (that._sceneLoadedCallback) {
  7352. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7353. }
  7354. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7355. });
  7356. }, function (progress) {
  7357. if (_this._progressCallback) {
  7358. _this._progressCallback(progress);
  7359. }
  7360. });
  7361. }
  7362. else {
  7363. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7364. }
  7365. };
  7366. FilesInput.FilesTextures = new Array();
  7367. FilesInput.FilesToLoad = new Array();
  7368. return FilesInput;
  7369. })();
  7370. BABYLON.FilesInput = FilesInput;
  7371. })(BABYLON || (BABYLON = {}));
  7372. var BABYLON;
  7373. (function (BABYLON) {
  7374. var IntersectionInfo = (function () {
  7375. function IntersectionInfo(bu, bv, distance) {
  7376. this.bu = bu;
  7377. this.bv = bv;
  7378. this.distance = distance;
  7379. this.faceId = 0;
  7380. this.subMeshId = 0;
  7381. }
  7382. return IntersectionInfo;
  7383. })();
  7384. BABYLON.IntersectionInfo = IntersectionInfo;
  7385. var PickingInfo = (function () {
  7386. function PickingInfo() {
  7387. this.hit = false;
  7388. this.distance = 0;
  7389. this.pickedPoint = null;
  7390. this.pickedMesh = null;
  7391. this.bu = 0;
  7392. this.bv = 0;
  7393. this.faceId = -1;
  7394. this.subMeshId = 0;
  7395. }
  7396. // Methods
  7397. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7398. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7399. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7400. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7401. return null;
  7402. }
  7403. var indices = this.pickedMesh.getIndices();
  7404. var result;
  7405. if (useVerticesNormals) {
  7406. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7407. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7408. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7409. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7410. normal0 = normal0.scale(this.bu);
  7411. normal1 = normal1.scale(this.bv);
  7412. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7413. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7414. }
  7415. else {
  7416. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7417. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7418. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7419. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7420. var p1p2 = vertex1.subtract(vertex2);
  7421. var p3p2 = vertex3.subtract(vertex2);
  7422. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7423. }
  7424. if (useWorldCoordinates) {
  7425. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7426. }
  7427. return BABYLON.Vector3.Normalize(result);
  7428. };
  7429. PickingInfo.prototype.getTextureCoordinates = function () {
  7430. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7431. return null;
  7432. }
  7433. var indices = this.pickedMesh.getIndices();
  7434. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7435. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7436. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7437. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7438. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7439. uv1 = uv1.scale(this.bu);
  7440. uv2 = uv2.scale(this.bv);
  7441. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7442. };
  7443. return PickingInfo;
  7444. })();
  7445. BABYLON.PickingInfo = PickingInfo;
  7446. })(BABYLON || (BABYLON = {}));
  7447. var BABYLON;
  7448. (function (BABYLON) {
  7449. var BoundingSphere = (function () {
  7450. function BoundingSphere(minimum, maximum) {
  7451. this.minimum = minimum;
  7452. this.maximum = maximum;
  7453. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7454. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7455. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7456. this.radius = distance * 0.5;
  7457. this.centerWorld = BABYLON.Vector3.Zero();
  7458. this._update(BABYLON.Matrix.Identity());
  7459. }
  7460. // Methods
  7461. BoundingSphere.prototype._update = function (world) {
  7462. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7463. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7464. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7465. };
  7466. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7467. for (var i = 0; i < 6; i++) {
  7468. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7469. return false;
  7470. }
  7471. return true;
  7472. };
  7473. BoundingSphere.prototype.intersectsPoint = function (point) {
  7474. var x = this.centerWorld.x - point.x;
  7475. var y = this.centerWorld.y - point.y;
  7476. var z = this.centerWorld.z - point.z;
  7477. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7478. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7479. return false;
  7480. return true;
  7481. };
  7482. // Statics
  7483. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7484. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7485. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7486. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7487. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7488. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7489. return false;
  7490. return true;
  7491. };
  7492. return BoundingSphere;
  7493. })();
  7494. BABYLON.BoundingSphere = BoundingSphere;
  7495. })(BABYLON || (BABYLON = {}));
  7496. var BABYLON;
  7497. (function (BABYLON) {
  7498. var BoundingBox = (function () {
  7499. function BoundingBox(minimum, maximum) {
  7500. this.minimum = minimum;
  7501. this.maximum = maximum;
  7502. this.vectors = new Array();
  7503. this.vectorsWorld = new Array();
  7504. // Bounding vectors
  7505. this.vectors.push(this.minimum.clone());
  7506. this.vectors.push(this.maximum.clone());
  7507. this.vectors.push(this.minimum.clone());
  7508. this.vectors[2].x = this.maximum.x;
  7509. this.vectors.push(this.minimum.clone());
  7510. this.vectors[3].y = this.maximum.y;
  7511. this.vectors.push(this.minimum.clone());
  7512. this.vectors[4].z = this.maximum.z;
  7513. this.vectors.push(this.maximum.clone());
  7514. this.vectors[5].z = this.minimum.z;
  7515. this.vectors.push(this.maximum.clone());
  7516. this.vectors[6].x = this.minimum.x;
  7517. this.vectors.push(this.maximum.clone());
  7518. this.vectors[7].y = this.minimum.y;
  7519. // OBB
  7520. this.center = this.maximum.add(this.minimum).scale(0.5);
  7521. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7522. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7523. // World
  7524. for (var index = 0; index < this.vectors.length; index++) {
  7525. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7526. }
  7527. this.minimumWorld = BABYLON.Vector3.Zero();
  7528. this.maximumWorld = BABYLON.Vector3.Zero();
  7529. this._update(BABYLON.Matrix.Identity());
  7530. }
  7531. // Methods
  7532. BoundingBox.prototype.getWorldMatrix = function () {
  7533. return this._worldMatrix;
  7534. };
  7535. BoundingBox.prototype._update = function (world) {
  7536. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7537. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7538. for (var index = 0; index < this.vectors.length; index++) {
  7539. var v = this.vectorsWorld[index];
  7540. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7541. if (v.x < this.minimumWorld.x)
  7542. this.minimumWorld.x = v.x;
  7543. if (v.y < this.minimumWorld.y)
  7544. this.minimumWorld.y = v.y;
  7545. if (v.z < this.minimumWorld.z)
  7546. this.minimumWorld.z = v.z;
  7547. if (v.x > this.maximumWorld.x)
  7548. this.maximumWorld.x = v.x;
  7549. if (v.y > this.maximumWorld.y)
  7550. this.maximumWorld.y = v.y;
  7551. if (v.z > this.maximumWorld.z)
  7552. this.maximumWorld.z = v.z;
  7553. }
  7554. // OBB
  7555. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7556. this.center.scaleInPlace(0.5);
  7557. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7558. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7559. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7560. this._worldMatrix = world;
  7561. };
  7562. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7563. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7564. };
  7565. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7566. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7567. };
  7568. BoundingBox.prototype.intersectsPoint = function (point) {
  7569. var delta = -BABYLON.Engine.Epsilon;
  7570. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7571. return false;
  7572. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7573. return false;
  7574. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7575. return false;
  7576. return true;
  7577. };
  7578. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7579. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7580. };
  7581. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7582. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7583. return false;
  7584. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7585. return false;
  7586. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7587. return false;
  7588. return true;
  7589. };
  7590. // Statics
  7591. BoundingBox.Intersects = function (box0, box1) {
  7592. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7593. return false;
  7594. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7595. return false;
  7596. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7597. return false;
  7598. return true;
  7599. };
  7600. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7601. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7602. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7603. return (num <= (sphereRadius * sphereRadius));
  7604. };
  7605. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7606. for (var p = 0; p < 6; p++) {
  7607. for (var i = 0; i < 8; i++) {
  7608. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7609. return false;
  7610. }
  7611. }
  7612. }
  7613. return true;
  7614. };
  7615. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7616. for (var p = 0; p < 6; p++) {
  7617. var inCount = 8;
  7618. for (var i = 0; i < 8; i++) {
  7619. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7620. --inCount;
  7621. }
  7622. else {
  7623. break;
  7624. }
  7625. }
  7626. if (inCount === 0)
  7627. return false;
  7628. }
  7629. return true;
  7630. };
  7631. return BoundingBox;
  7632. })();
  7633. BABYLON.BoundingBox = BoundingBox;
  7634. })(BABYLON || (BABYLON = {}));
  7635. var BABYLON;
  7636. (function (BABYLON) {
  7637. var computeBoxExtents = function (axis, box) {
  7638. var p = BABYLON.Vector3.Dot(box.center, axis);
  7639. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7640. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7641. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7642. var r = r0 + r1 + r2;
  7643. return {
  7644. min: p - r,
  7645. max: p + r
  7646. };
  7647. };
  7648. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7649. var axisOverlap = function (axis, box0, box1) {
  7650. var result0 = computeBoxExtents(axis, box0);
  7651. var result1 = computeBoxExtents(axis, box1);
  7652. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7653. };
  7654. var BoundingInfo = (function () {
  7655. function BoundingInfo(minimum, maximum) {
  7656. this.minimum = minimum;
  7657. this.maximum = maximum;
  7658. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7659. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7660. }
  7661. // Methods
  7662. BoundingInfo.prototype._update = function (world) {
  7663. this.boundingBox._update(world);
  7664. this.boundingSphere._update(world);
  7665. };
  7666. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7667. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7668. return false;
  7669. return this.boundingBox.isInFrustum(frustumPlanes);
  7670. };
  7671. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7672. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7673. };
  7674. BoundingInfo.prototype._checkCollision = function (collider) {
  7675. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7676. };
  7677. BoundingInfo.prototype.intersectsPoint = function (point) {
  7678. if (!this.boundingSphere.centerWorld) {
  7679. return false;
  7680. }
  7681. if (!this.boundingSphere.intersectsPoint(point)) {
  7682. return false;
  7683. }
  7684. if (!this.boundingBox.intersectsPoint(point)) {
  7685. return false;
  7686. }
  7687. return true;
  7688. };
  7689. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7690. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7691. return false;
  7692. }
  7693. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7694. return false;
  7695. }
  7696. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7697. return false;
  7698. }
  7699. if (!precise) {
  7700. return true;
  7701. }
  7702. var box0 = this.boundingBox;
  7703. var box1 = boundingInfo.boundingBox;
  7704. if (!axisOverlap(box0.directions[0], box0, box1))
  7705. return false;
  7706. if (!axisOverlap(box0.directions[1], box0, box1))
  7707. return false;
  7708. if (!axisOverlap(box0.directions[2], box0, box1))
  7709. return false;
  7710. if (!axisOverlap(box1.directions[0], box0, box1))
  7711. return false;
  7712. if (!axisOverlap(box1.directions[1], box0, box1))
  7713. return false;
  7714. if (!axisOverlap(box1.directions[2], box0, box1))
  7715. return false;
  7716. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7717. return false;
  7718. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7719. return false;
  7720. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7721. return false;
  7722. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7723. return false;
  7724. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7725. return false;
  7726. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7727. return false;
  7728. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7729. return false;
  7730. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7731. return false;
  7732. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7733. return false;
  7734. return true;
  7735. };
  7736. return BoundingInfo;
  7737. })();
  7738. BABYLON.BoundingInfo = BoundingInfo;
  7739. })(BABYLON || (BABYLON = {}));
  7740. var BABYLON;
  7741. (function (BABYLON) {
  7742. var AbstractMesh = (function (_super) {
  7743. __extends(AbstractMesh, _super);
  7744. function AbstractMesh(name, scene) {
  7745. var _this = this;
  7746. _super.call(this, name, scene);
  7747. // Properties
  7748. this.definedFacingForward = true; // orientation for POV movement & rotation
  7749. this.position = new BABYLON.Vector3(0, 0, 0);
  7750. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7751. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7752. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7753. this.visibility = 1.0;
  7754. this.alphaIndex = Number.MAX_VALUE;
  7755. this.infiniteDistance = false;
  7756. this.isVisible = true;
  7757. this.isPickable = true;
  7758. this.showBoundingBox = false;
  7759. this.showSubMeshesBoundingBox = false;
  7760. this.onDispose = null;
  7761. this.isBlocker = false;
  7762. this.renderingGroupId = 0;
  7763. this.receiveShadows = false;
  7764. this.renderOutline = false;
  7765. this.outlineColor = BABYLON.Color3.Red();
  7766. this.outlineWidth = 0.02;
  7767. this.renderOverlay = false;
  7768. this.overlayColor = BABYLON.Color3.Red();
  7769. this.overlayAlpha = 0.5;
  7770. this.hasVertexAlpha = false;
  7771. this.useVertexColors = true;
  7772. this.applyFog = true;
  7773. this.computeBonesUsingShaders = true;
  7774. this.useOctreeForRenderingSelection = true;
  7775. this.useOctreeForPicking = true;
  7776. this.useOctreeForCollisions = true;
  7777. this.layerMask = 0x0FFFFFFF;
  7778. this.alwaysSelectAsActiveMesh = false;
  7779. // Physics
  7780. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7781. // Collisions
  7782. this._checkCollisions = false;
  7783. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7784. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7785. this._collider = new BABYLON.Collider();
  7786. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7787. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7788. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7789. // Edges
  7790. this.edgesWidth = 1;
  7791. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  7792. // Cache
  7793. this._localScaling = BABYLON.Matrix.Zero();
  7794. this._localRotation = BABYLON.Matrix.Zero();
  7795. this._localTranslation = BABYLON.Matrix.Zero();
  7796. this._localBillboard = BABYLON.Matrix.Zero();
  7797. this._localPivotScaling = BABYLON.Matrix.Zero();
  7798. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7799. this._localWorld = BABYLON.Matrix.Zero();
  7800. this._worldMatrix = BABYLON.Matrix.Zero();
  7801. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7802. this._absolutePosition = BABYLON.Vector3.Zero();
  7803. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7804. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7805. this._isDirty = false;
  7806. this._pivotMatrix = BABYLON.Matrix.Identity();
  7807. this._isDisposed = false;
  7808. this._renderId = 0;
  7809. this._intersectionsInProgress = new Array();
  7810. this._onAfterWorldMatrixUpdate = new Array();
  7811. this._isWorldMatrixFrozen = false;
  7812. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7813. if (collidedMesh === void 0) { collidedMesh = null; }
  7814. //TODO move this to the collision coordinator!
  7815. if (_this.getScene().workerCollisions)
  7816. newPosition.multiplyInPlace(_this._collider.radius);
  7817. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7818. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7819. _this.position.addInPlace(_this._diffPositionForCollisions);
  7820. }
  7821. if (_this.onCollide && collidedMesh) {
  7822. _this.onCollide(collidedMesh);
  7823. }
  7824. };
  7825. scene.addMesh(this);
  7826. }
  7827. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7828. get: function () {
  7829. return AbstractMesh._BILLBOARDMODE_NONE;
  7830. },
  7831. enumerable: true,
  7832. configurable: true
  7833. });
  7834. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7835. get: function () {
  7836. return AbstractMesh._BILLBOARDMODE_X;
  7837. },
  7838. enumerable: true,
  7839. configurable: true
  7840. });
  7841. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7842. get: function () {
  7843. return AbstractMesh._BILLBOARDMODE_Y;
  7844. },
  7845. enumerable: true,
  7846. configurable: true
  7847. });
  7848. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7849. get: function () {
  7850. return AbstractMesh._BILLBOARDMODE_Z;
  7851. },
  7852. enumerable: true,
  7853. configurable: true
  7854. });
  7855. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7856. get: function () {
  7857. return AbstractMesh._BILLBOARDMODE_ALL;
  7858. },
  7859. enumerable: true,
  7860. configurable: true
  7861. });
  7862. // Methods
  7863. AbstractMesh.prototype.disableEdgesRendering = function () {
  7864. if (this._edgesRenderer !== undefined) {
  7865. this._edgesRenderer.dispose();
  7866. this._edgesRenderer = undefined;
  7867. }
  7868. };
  7869. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  7870. if (epsilon === void 0) { epsilon = 0.95; }
  7871. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  7872. this.disableEdgesRendering();
  7873. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  7874. };
  7875. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7876. get: function () {
  7877. return false;
  7878. },
  7879. enumerable: true,
  7880. configurable: true
  7881. });
  7882. AbstractMesh.prototype.getLOD = function (camera) {
  7883. return this;
  7884. };
  7885. AbstractMesh.prototype.getTotalVertices = function () {
  7886. return 0;
  7887. };
  7888. AbstractMesh.prototype.getIndices = function () {
  7889. return null;
  7890. };
  7891. AbstractMesh.prototype.getVerticesData = function (kind) {
  7892. return null;
  7893. };
  7894. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7895. return false;
  7896. };
  7897. AbstractMesh.prototype.getBoundingInfo = function () {
  7898. if (this._masterMesh) {
  7899. return this._masterMesh.getBoundingInfo();
  7900. }
  7901. if (!this._boundingInfo) {
  7902. this._updateBoundingInfo();
  7903. }
  7904. return this._boundingInfo;
  7905. };
  7906. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7907. get: function () {
  7908. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. AbstractMesh.prototype._preActivate = function () {
  7914. };
  7915. AbstractMesh.prototype._activate = function (renderId) {
  7916. this._renderId = renderId;
  7917. };
  7918. AbstractMesh.prototype.getWorldMatrix = function () {
  7919. if (this._masterMesh) {
  7920. return this._masterMesh.getWorldMatrix();
  7921. }
  7922. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7923. this.computeWorldMatrix();
  7924. }
  7925. return this._worldMatrix;
  7926. };
  7927. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7928. get: function () {
  7929. return this._worldMatrix;
  7930. },
  7931. enumerable: true,
  7932. configurable: true
  7933. });
  7934. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7935. get: function () {
  7936. return this._absolutePosition;
  7937. },
  7938. enumerable: true,
  7939. configurable: true
  7940. });
  7941. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7942. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7943. this.computeWorldMatrix(true);
  7944. this._isWorldMatrixFrozen = true;
  7945. };
  7946. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7947. this._isWorldMatrixFrozen = false;
  7948. this.computeWorldMatrix(true);
  7949. };
  7950. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7951. get: function () {
  7952. return this._isWorldMatrixFrozen;
  7953. },
  7954. enumerable: true,
  7955. configurable: true
  7956. });
  7957. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7958. axis.normalize();
  7959. if (!this.rotationQuaternion) {
  7960. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7961. this.rotation = BABYLON.Vector3.Zero();
  7962. }
  7963. if (!space || space === BABYLON.Space.LOCAL) {
  7964. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7965. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7966. }
  7967. else {
  7968. if (this.parent) {
  7969. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7970. invertParentWorldMatrix.invert();
  7971. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7972. }
  7973. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7974. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7975. }
  7976. };
  7977. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7978. var displacementVector = axis.scale(distance);
  7979. if (!space || space === BABYLON.Space.LOCAL) {
  7980. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7981. this.setPositionWithLocalVector(tempV3);
  7982. }
  7983. else {
  7984. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7985. }
  7986. };
  7987. AbstractMesh.prototype.getAbsolutePosition = function () {
  7988. this.computeWorldMatrix();
  7989. return this._absolutePosition;
  7990. };
  7991. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7992. if (!absolutePosition) {
  7993. return;
  7994. }
  7995. var absolutePositionX;
  7996. var absolutePositionY;
  7997. var absolutePositionZ;
  7998. if (absolutePosition.x === undefined) {
  7999. if (arguments.length < 3) {
  8000. return;
  8001. }
  8002. absolutePositionX = arguments[0];
  8003. absolutePositionY = arguments[1];
  8004. absolutePositionZ = arguments[2];
  8005. }
  8006. else {
  8007. absolutePositionX = absolutePosition.x;
  8008. absolutePositionY = absolutePosition.y;
  8009. absolutePositionZ = absolutePosition.z;
  8010. }
  8011. if (this.parent) {
  8012. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8013. invertParentWorldMatrix.invert();
  8014. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8015. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8016. }
  8017. else {
  8018. this.position.x = absolutePositionX;
  8019. this.position.y = absolutePositionY;
  8020. this.position.z = absolutePositionZ;
  8021. }
  8022. };
  8023. // ================================== Point of View Movement =================================
  8024. /**
  8025. * Perform relative position change from the point of view of behind the front of the mesh.
  8026. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8027. * Supports definition of mesh facing forward or backward.
  8028. * @param {number} amountRight
  8029. * @param {number} amountUp
  8030. * @param {number} amountForward
  8031. */
  8032. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8033. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8034. };
  8035. /**
  8036. * Calculate relative position change from the point of view of behind the front of the mesh.
  8037. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8038. * Supports definition of mesh facing forward or backward.
  8039. * @param {number} amountRight
  8040. * @param {number} amountUp
  8041. * @param {number} amountForward
  8042. */
  8043. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8044. var rotMatrix = new BABYLON.Matrix();
  8045. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8046. rotQuaternion.toRotationMatrix(rotMatrix);
  8047. var translationDelta = BABYLON.Vector3.Zero();
  8048. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8049. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8050. return translationDelta;
  8051. };
  8052. // ================================== Point of View Rotation =================================
  8053. /**
  8054. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8055. * Supports definition of mesh facing forward or backward.
  8056. * @param {number} flipBack
  8057. * @param {number} twirlClockwise
  8058. * @param {number} tiltRight
  8059. */
  8060. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8061. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8062. };
  8063. /**
  8064. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8065. * Supports definition of mesh facing forward or backward.
  8066. * @param {number} flipBack
  8067. * @param {number} twirlClockwise
  8068. * @param {number} tiltRight
  8069. */
  8070. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8071. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8072. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8073. };
  8074. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8075. this._pivotMatrix = matrix;
  8076. this._cache.pivotMatrixUpdated = true;
  8077. };
  8078. AbstractMesh.prototype.getPivotMatrix = function () {
  8079. return this._pivotMatrix;
  8080. };
  8081. AbstractMesh.prototype._isSynchronized = function () {
  8082. if (this._isDirty) {
  8083. return false;
  8084. }
  8085. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8086. return false;
  8087. if (this._cache.pivotMatrixUpdated) {
  8088. return false;
  8089. }
  8090. if (this.infiniteDistance) {
  8091. return false;
  8092. }
  8093. if (!this._cache.position.equals(this.position))
  8094. return false;
  8095. if (this.rotationQuaternion) {
  8096. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8097. return false;
  8098. }
  8099. else {
  8100. if (!this._cache.rotation.equals(this.rotation))
  8101. return false;
  8102. }
  8103. if (!this._cache.scaling.equals(this.scaling))
  8104. return false;
  8105. return true;
  8106. };
  8107. AbstractMesh.prototype._initCache = function () {
  8108. _super.prototype._initCache.call(this);
  8109. this._cache.localMatrixUpdated = false;
  8110. this._cache.position = BABYLON.Vector3.Zero();
  8111. this._cache.scaling = BABYLON.Vector3.Zero();
  8112. this._cache.rotation = BABYLON.Vector3.Zero();
  8113. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8114. };
  8115. AbstractMesh.prototype.markAsDirty = function (property) {
  8116. if (property === "rotation") {
  8117. this.rotationQuaternion = null;
  8118. }
  8119. this._currentRenderId = Number.MAX_VALUE;
  8120. this._isDirty = true;
  8121. };
  8122. AbstractMesh.prototype._updateBoundingInfo = function () {
  8123. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8124. this._boundingInfo._update(this.worldMatrixFromCache);
  8125. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8126. };
  8127. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8128. if (!this.subMeshes) {
  8129. return;
  8130. }
  8131. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8132. var subMesh = this.subMeshes[subIndex];
  8133. subMesh.updateBoundingInfo(matrix);
  8134. }
  8135. };
  8136. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8137. if (this._isWorldMatrixFrozen) {
  8138. return this._worldMatrix;
  8139. }
  8140. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8141. return this._worldMatrix;
  8142. }
  8143. this._cache.position.copyFrom(this.position);
  8144. this._cache.scaling.copyFrom(this.scaling);
  8145. this._cache.pivotMatrixUpdated = false;
  8146. this._currentRenderId = this.getScene().getRenderId();
  8147. this._isDirty = false;
  8148. // Scaling
  8149. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8150. // Rotation
  8151. if (this.rotationQuaternion) {
  8152. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8153. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8154. }
  8155. else {
  8156. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8157. this._cache.rotation.copyFrom(this.rotation);
  8158. }
  8159. // Translation
  8160. if (this.infiniteDistance && !this.parent) {
  8161. var camera = this.getScene().activeCamera;
  8162. if (camera) {
  8163. var cameraWorldMatrix = camera.getWorldMatrix();
  8164. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8165. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8166. }
  8167. }
  8168. else {
  8169. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8170. }
  8171. // Composing transformations
  8172. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8173. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8174. // Billboarding
  8175. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8176. var localPosition = this.position.clone();
  8177. var zero = this.getScene().activeCamera.globalPosition.clone();
  8178. if (this.parent && this.parent.position) {
  8179. localPosition.addInPlace(this.parent.position);
  8180. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8181. }
  8182. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  8183. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8184. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8185. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8186. zero.y = localPosition.y + 0.001;
  8187. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8188. zero.z = localPosition.z + 0.001;
  8189. }
  8190. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8191. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8192. this._localBillboard.invert();
  8193. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8194. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8195. }
  8196. // Local world
  8197. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8198. // Parent
  8199. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8200. this._markSyncedWithParent();
  8201. if (this._meshToBoneReferal) {
  8202. if (!this._localMeshReferalTransform) {
  8203. this._localMeshReferalTransform = BABYLON.Matrix.Zero();
  8204. }
  8205. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._localMeshReferalTransform);
  8206. this._localMeshReferalTransform.multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8207. }
  8208. else {
  8209. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8210. }
  8211. }
  8212. else {
  8213. this._worldMatrix.copyFrom(this._localWorld);
  8214. }
  8215. // Bounding info
  8216. this._updateBoundingInfo();
  8217. // Absolute position
  8218. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8219. // Callbacks
  8220. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8221. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8222. }
  8223. return this._worldMatrix;
  8224. };
  8225. /**
  8226. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8227. * @param func: callback function to add
  8228. */
  8229. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8230. this._onAfterWorldMatrixUpdate.push(func);
  8231. };
  8232. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8233. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8234. if (index > -1) {
  8235. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8236. }
  8237. };
  8238. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8239. this.computeWorldMatrix();
  8240. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8241. };
  8242. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8243. this.computeWorldMatrix();
  8244. var invLocalWorldMatrix = this._localWorld.clone();
  8245. invLocalWorldMatrix.invert();
  8246. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8247. };
  8248. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8249. this.computeWorldMatrix(true);
  8250. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8251. };
  8252. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8253. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8254. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8255. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8256. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8257. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8258. /// <returns>Mesh oriented towards targetMesh</returns>
  8259. yawCor = yawCor || 0; // default to zero if undefined
  8260. pitchCor = pitchCor || 0;
  8261. rollCor = rollCor || 0;
  8262. var dv = targetPoint.subtract(this.position);
  8263. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8264. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8265. var pitch = Math.atan2(dv.y, len);
  8266. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8267. };
  8268. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8269. this._meshToBoneReferal = affectedMesh;
  8270. this.parent = bone;
  8271. };
  8272. AbstractMesh.prototype.detachFromBone = function () {
  8273. this._meshToBoneReferal = null;
  8274. this.parent = null;
  8275. };
  8276. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8277. return this._boundingInfo.isInFrustum(frustumPlanes);
  8278. };
  8279. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8280. if (!camera) {
  8281. camera = this.getScene().activeCamera;
  8282. }
  8283. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8284. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8285. return false;
  8286. }
  8287. return true;
  8288. };
  8289. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8290. if (!this._boundingInfo || !mesh._boundingInfo) {
  8291. return false;
  8292. }
  8293. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8294. };
  8295. AbstractMesh.prototype.intersectsPoint = function (point) {
  8296. if (!this._boundingInfo) {
  8297. return false;
  8298. }
  8299. return this._boundingInfo.intersectsPoint(point);
  8300. };
  8301. // Physics
  8302. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8303. var physicsEngine = this.getScene().getPhysicsEngine();
  8304. if (!physicsEngine) {
  8305. return;
  8306. }
  8307. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8308. if (impostor.impostor) {
  8309. // Old API
  8310. options = impostor;
  8311. impostor = impostor.impostor;
  8312. }
  8313. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8314. physicsEngine._unregisterMesh(this);
  8315. return;
  8316. }
  8317. if (!options) {
  8318. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8319. }
  8320. else {
  8321. if (!options.mass && options.mass !== 0)
  8322. options.mass = 0;
  8323. if (!options.friction && options.friction !== 0)
  8324. options.friction = 0.2;
  8325. if (!options.restitution && options.restitution !== 0)
  8326. options.restitution = 0.2;
  8327. }
  8328. this._physicImpostor = impostor;
  8329. this._physicsMass = options.mass;
  8330. this._physicsFriction = options.friction;
  8331. this._physicRestitution = options.restitution;
  8332. return physicsEngine._registerMesh(this, impostor, options);
  8333. };
  8334. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8335. if (!this._physicImpostor) {
  8336. return BABYLON.PhysicsEngine.NoImpostor;
  8337. }
  8338. return this._physicImpostor;
  8339. };
  8340. AbstractMesh.prototype.getPhysicsMass = function () {
  8341. if (!this._physicsMass) {
  8342. return 0;
  8343. }
  8344. return this._physicsMass;
  8345. };
  8346. AbstractMesh.prototype.getPhysicsFriction = function () {
  8347. if (!this._physicsFriction) {
  8348. return 0;
  8349. }
  8350. return this._physicsFriction;
  8351. };
  8352. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8353. if (!this._physicRestitution) {
  8354. return 0;
  8355. }
  8356. return this._physicRestitution;
  8357. };
  8358. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8359. if (!camera) {
  8360. camera = this.getScene().activeCamera;
  8361. }
  8362. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8363. };
  8364. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8365. if (!camera) {
  8366. camera = this.getScene().activeCamera;
  8367. }
  8368. return this.absolutePosition.subtract(camera.position).length();
  8369. };
  8370. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8371. if (!this._physicImpostor) {
  8372. return;
  8373. }
  8374. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8375. };
  8376. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8377. if (!this._physicImpostor) {
  8378. return;
  8379. }
  8380. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8381. };
  8382. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8383. if (!this._physicImpostor) {
  8384. return;
  8385. }
  8386. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8387. };
  8388. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8389. // Collisions
  8390. get: function () {
  8391. return this._checkCollisions;
  8392. },
  8393. set: function (collisionEnabled) {
  8394. this._checkCollisions = collisionEnabled;
  8395. if (this.getScene().workerCollisions) {
  8396. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8397. }
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8403. var globalPosition = this.getAbsolutePosition();
  8404. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8405. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8406. this._collider.radius = this.ellipsoid;
  8407. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8408. };
  8409. // Submeshes octree
  8410. /**
  8411. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8412. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8413. */
  8414. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8415. if (maxCapacity === void 0) { maxCapacity = 64; }
  8416. if (maxDepth === void 0) { maxDepth = 2; }
  8417. if (!this._submeshesOctree) {
  8418. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8419. }
  8420. this.computeWorldMatrix(true);
  8421. // Update octree
  8422. var bbox = this.getBoundingInfo().boundingBox;
  8423. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8424. return this._submeshesOctree;
  8425. };
  8426. // Collisions
  8427. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8428. this._generatePointsArray();
  8429. // Transformation
  8430. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8431. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8432. subMesh._lastColliderWorldVertices = [];
  8433. subMesh._trianglePlanes = [];
  8434. var start = subMesh.verticesStart;
  8435. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8436. for (var i = start; i < end; i++) {
  8437. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8438. }
  8439. }
  8440. // Collide
  8441. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8442. if (collider.collisionFound) {
  8443. collider.collidedMesh = this;
  8444. }
  8445. };
  8446. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8447. var subMeshes;
  8448. var len;
  8449. // Octrees
  8450. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8451. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8452. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8453. len = intersections.length;
  8454. subMeshes = intersections.data;
  8455. }
  8456. else {
  8457. subMeshes = this.subMeshes;
  8458. len = subMeshes.length;
  8459. }
  8460. for (var index = 0; index < len; index++) {
  8461. var subMesh = subMeshes[index];
  8462. // Bounding test
  8463. if (len > 1 && !subMesh._checkCollision(collider))
  8464. continue;
  8465. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8466. }
  8467. };
  8468. AbstractMesh.prototype._checkCollision = function (collider) {
  8469. // Bounding box test
  8470. if (!this._boundingInfo._checkCollision(collider))
  8471. return;
  8472. // Transformation matrix
  8473. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8474. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8475. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8476. };
  8477. // Picking
  8478. AbstractMesh.prototype._generatePointsArray = function () {
  8479. return false;
  8480. };
  8481. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8482. var pickingInfo = new BABYLON.PickingInfo();
  8483. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8484. return pickingInfo;
  8485. }
  8486. if (!this._generatePointsArray()) {
  8487. return pickingInfo;
  8488. }
  8489. var intersectInfo = null;
  8490. // Octrees
  8491. var subMeshes;
  8492. var len;
  8493. if (this._submeshesOctree && this.useOctreeForPicking) {
  8494. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8495. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8496. len = intersections.length;
  8497. subMeshes = intersections.data;
  8498. }
  8499. else {
  8500. subMeshes = this.subMeshes;
  8501. len = subMeshes.length;
  8502. }
  8503. for (var index = 0; index < len; index++) {
  8504. var subMesh = subMeshes[index];
  8505. // Bounding test
  8506. if (len > 1 && !subMesh.canIntersects(ray))
  8507. continue;
  8508. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8509. if (currentIntersectInfo) {
  8510. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8511. intersectInfo = currentIntersectInfo;
  8512. intersectInfo.subMeshId = index;
  8513. if (fastCheck) {
  8514. break;
  8515. }
  8516. }
  8517. }
  8518. }
  8519. if (intersectInfo) {
  8520. // Get picked point
  8521. var world = this.getWorldMatrix();
  8522. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8523. var direction = ray.direction.clone();
  8524. direction = direction.scale(intersectInfo.distance);
  8525. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8526. var pickedPoint = worldOrigin.add(worldDirection);
  8527. // Return result
  8528. pickingInfo.hit = true;
  8529. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8530. pickingInfo.pickedPoint = pickedPoint;
  8531. pickingInfo.pickedMesh = this;
  8532. pickingInfo.bu = intersectInfo.bu;
  8533. pickingInfo.bv = intersectInfo.bv;
  8534. pickingInfo.faceId = intersectInfo.faceId;
  8535. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8536. return pickingInfo;
  8537. }
  8538. return pickingInfo;
  8539. };
  8540. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8541. return null;
  8542. };
  8543. AbstractMesh.prototype.releaseSubMeshes = function () {
  8544. if (this.subMeshes) {
  8545. while (this.subMeshes.length) {
  8546. this.subMeshes[0].dispose();
  8547. }
  8548. }
  8549. else {
  8550. this.subMeshes = new Array();
  8551. }
  8552. };
  8553. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8554. var index;
  8555. // Physics
  8556. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8557. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8558. }
  8559. // Intersections in progress
  8560. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8561. var other = this._intersectionsInProgress[index];
  8562. var pos = other._intersectionsInProgress.indexOf(this);
  8563. other._intersectionsInProgress.splice(pos, 1);
  8564. }
  8565. this._intersectionsInProgress = [];
  8566. // Edges
  8567. if (this._edgesRenderer) {
  8568. this._edgesRenderer.dispose();
  8569. this._edgesRenderer = null;
  8570. }
  8571. // SubMeshes
  8572. this.releaseSubMeshes();
  8573. // Remove from scene
  8574. this.getScene().removeMesh(this);
  8575. if (!doNotRecurse) {
  8576. // Particles
  8577. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8578. if (this.getScene().particleSystems[index].emitter === this) {
  8579. this.getScene().particleSystems[index].dispose();
  8580. index--;
  8581. }
  8582. }
  8583. // Children
  8584. var objects = this.getScene().meshes.slice(0);
  8585. for (index = 0; index < objects.length; index++) {
  8586. if (objects[index].parent === this) {
  8587. objects[index].dispose();
  8588. }
  8589. }
  8590. }
  8591. else {
  8592. for (index = 0; index < this.getScene().meshes.length; index++) {
  8593. var obj = this.getScene().meshes[index];
  8594. if (obj.parent === this) {
  8595. obj.parent = null;
  8596. obj.computeWorldMatrix(true);
  8597. }
  8598. }
  8599. }
  8600. this._onAfterWorldMatrixUpdate = [];
  8601. this._isDisposed = true;
  8602. // Callback
  8603. if (this.onDispose) {
  8604. this.onDispose();
  8605. }
  8606. };
  8607. // Statics
  8608. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8609. AbstractMesh._BILLBOARDMODE_X = 1;
  8610. AbstractMesh._BILLBOARDMODE_Y = 2;
  8611. AbstractMesh._BILLBOARDMODE_Z = 4;
  8612. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8613. return AbstractMesh;
  8614. })(BABYLON.Node);
  8615. BABYLON.AbstractMesh = AbstractMesh;
  8616. })(BABYLON || (BABYLON = {}));
  8617. var BABYLON;
  8618. (function (BABYLON) {
  8619. var Light = (function (_super) {
  8620. __extends(Light, _super);
  8621. function Light(name, scene) {
  8622. _super.call(this, name, scene);
  8623. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8624. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8625. this.intensity = 1.0;
  8626. this.range = Number.MAX_VALUE;
  8627. this.includeOnlyWithLayerMask = 0;
  8628. this.includedOnlyMeshes = new Array();
  8629. this.excludedMeshes = new Array();
  8630. this.excludeWithLayerMask = 0;
  8631. this._excludedMeshesIds = new Array();
  8632. this._includedOnlyMeshesIds = new Array();
  8633. scene.addLight(this);
  8634. }
  8635. Light.prototype.getShadowGenerator = function () {
  8636. return this._shadowGenerator;
  8637. };
  8638. Light.prototype.getAbsolutePosition = function () {
  8639. return BABYLON.Vector3.Zero();
  8640. };
  8641. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8642. };
  8643. Light.prototype._getWorldMatrix = function () {
  8644. return BABYLON.Matrix.Identity();
  8645. };
  8646. Light.prototype.canAffectMesh = function (mesh) {
  8647. if (!mesh) {
  8648. return true;
  8649. }
  8650. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8651. return false;
  8652. }
  8653. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8654. return false;
  8655. }
  8656. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8657. return false;
  8658. }
  8659. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8660. return false;
  8661. }
  8662. return true;
  8663. };
  8664. Light.prototype.getWorldMatrix = function () {
  8665. this._currentRenderId = this.getScene().getRenderId();
  8666. var worldMatrix = this._getWorldMatrix();
  8667. if (this.parent && this.parent.getWorldMatrix) {
  8668. if (!this._parentedWorldMatrix) {
  8669. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8670. }
  8671. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8672. this._markSyncedWithParent();
  8673. return this._parentedWorldMatrix;
  8674. }
  8675. return worldMatrix;
  8676. };
  8677. Light.prototype.dispose = function () {
  8678. if (this._shadowGenerator) {
  8679. this._shadowGenerator.dispose();
  8680. this._shadowGenerator = null;
  8681. }
  8682. // Remove from scene
  8683. this.getScene().removeLight(this);
  8684. };
  8685. return Light;
  8686. })(BABYLON.Node);
  8687. BABYLON.Light = Light;
  8688. })(BABYLON || (BABYLON = {}));
  8689. var BABYLON;
  8690. (function (BABYLON) {
  8691. var PointLight = (function (_super) {
  8692. __extends(PointLight, _super);
  8693. function PointLight(name, position, scene) {
  8694. _super.call(this, name, scene);
  8695. this.position = position;
  8696. }
  8697. PointLight.prototype.getAbsolutePosition = function () {
  8698. return this._transformedPosition ? this._transformedPosition : this.position;
  8699. };
  8700. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8701. if (this.parent && this.parent.getWorldMatrix) {
  8702. if (!this._transformedPosition) {
  8703. this._transformedPosition = BABYLON.Vector3.Zero();
  8704. }
  8705. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8706. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8707. return;
  8708. }
  8709. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8710. };
  8711. PointLight.prototype.getShadowGenerator = function () {
  8712. return null;
  8713. };
  8714. PointLight.prototype._getWorldMatrix = function () {
  8715. if (!this._worldMatrix) {
  8716. this._worldMatrix = BABYLON.Matrix.Identity();
  8717. }
  8718. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8719. return this._worldMatrix;
  8720. };
  8721. return PointLight;
  8722. })(BABYLON.Light);
  8723. BABYLON.PointLight = PointLight;
  8724. })(BABYLON || (BABYLON = {}));
  8725. var BABYLON;
  8726. (function (BABYLON) {
  8727. var SpotLight = (function (_super) {
  8728. __extends(SpotLight, _super);
  8729. function SpotLight(name, position, direction, angle, exponent, scene) {
  8730. _super.call(this, name, scene);
  8731. this.position = position;
  8732. this.direction = direction;
  8733. this.angle = angle;
  8734. this.exponent = exponent;
  8735. }
  8736. SpotLight.prototype.getAbsolutePosition = function () {
  8737. return this.transformedPosition ? this.transformedPosition : this.position;
  8738. };
  8739. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8740. var activeCamera = this.getScene().activeCamera;
  8741. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8742. };
  8743. SpotLight.prototype.supportsVSM = function () {
  8744. return true;
  8745. };
  8746. SpotLight.prototype.needRefreshPerFrame = function () {
  8747. return false;
  8748. };
  8749. SpotLight.prototype.setDirectionToTarget = function (target) {
  8750. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8751. return this.direction;
  8752. };
  8753. SpotLight.prototype.computeTransformedPosition = function () {
  8754. if (this.parent && this.parent.getWorldMatrix) {
  8755. if (!this.transformedPosition) {
  8756. this.transformedPosition = BABYLON.Vector3.Zero();
  8757. }
  8758. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8759. return true;
  8760. }
  8761. return false;
  8762. };
  8763. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8764. var normalizeDirection;
  8765. if (this.parent && this.parent.getWorldMatrix) {
  8766. if (!this._transformedDirection) {
  8767. this._transformedDirection = BABYLON.Vector3.Zero();
  8768. }
  8769. this.computeTransformedPosition();
  8770. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8771. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8772. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8773. }
  8774. else {
  8775. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8776. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8777. }
  8778. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8779. };
  8780. SpotLight.prototype._getWorldMatrix = function () {
  8781. if (!this._worldMatrix) {
  8782. this._worldMatrix = BABYLON.Matrix.Identity();
  8783. }
  8784. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8785. return this._worldMatrix;
  8786. };
  8787. return SpotLight;
  8788. })(BABYLON.Light);
  8789. BABYLON.SpotLight = SpotLight;
  8790. })(BABYLON || (BABYLON = {}));
  8791. var BABYLON;
  8792. (function (BABYLON) {
  8793. var HemisphericLight = (function (_super) {
  8794. __extends(HemisphericLight, _super);
  8795. function HemisphericLight(name, direction, scene) {
  8796. _super.call(this, name, scene);
  8797. this.direction = direction;
  8798. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8799. }
  8800. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8801. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8802. return this.direction;
  8803. };
  8804. HemisphericLight.prototype.getShadowGenerator = function () {
  8805. return null;
  8806. };
  8807. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8808. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8809. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8810. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8811. };
  8812. HemisphericLight.prototype._getWorldMatrix = function () {
  8813. if (!this._worldMatrix) {
  8814. this._worldMatrix = BABYLON.Matrix.Identity();
  8815. }
  8816. return this._worldMatrix;
  8817. };
  8818. return HemisphericLight;
  8819. })(BABYLON.Light);
  8820. BABYLON.HemisphericLight = HemisphericLight;
  8821. })(BABYLON || (BABYLON = {}));
  8822. var BABYLON;
  8823. (function (BABYLON) {
  8824. var DirectionalLight = (function (_super) {
  8825. __extends(DirectionalLight, _super);
  8826. function DirectionalLight(name, direction, scene) {
  8827. _super.call(this, name, scene);
  8828. this.direction = direction;
  8829. this.shadowOrthoScale = 0.5;
  8830. this.position = direction.scale(-1);
  8831. }
  8832. DirectionalLight.prototype.getAbsolutePosition = function () {
  8833. return this.transformedPosition ? this.transformedPosition : this.position;
  8834. };
  8835. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8836. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8837. return this.direction;
  8838. };
  8839. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8840. var orthoLeft = Number.MAX_VALUE;
  8841. var orthoRight = Number.MIN_VALUE;
  8842. var orthoTop = Number.MIN_VALUE;
  8843. var orthoBottom = Number.MAX_VALUE;
  8844. var tempVector3 = BABYLON.Vector3.Zero();
  8845. var activeCamera = this.getScene().activeCamera;
  8846. // Check extends
  8847. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8848. var mesh = renderList[meshIndex];
  8849. if (!mesh) {
  8850. continue;
  8851. }
  8852. var boundingInfo = mesh.getBoundingInfo();
  8853. if (!boundingInfo) {
  8854. continue;
  8855. }
  8856. var boundingBox = boundingInfo.boundingBox;
  8857. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8858. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8859. if (tempVector3.x < orthoLeft)
  8860. orthoLeft = tempVector3.x;
  8861. if (tempVector3.y < orthoBottom)
  8862. orthoBottom = tempVector3.y;
  8863. if (tempVector3.x > orthoRight)
  8864. orthoRight = tempVector3.x;
  8865. if (tempVector3.y > orthoTop)
  8866. orthoTop = tempVector3.y;
  8867. }
  8868. }
  8869. var xOffset = orthoRight - orthoLeft;
  8870. var yOffset = orthoTop - orthoBottom;
  8871. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8872. };
  8873. DirectionalLight.prototype.supportsVSM = function () {
  8874. return true;
  8875. };
  8876. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8877. return true;
  8878. };
  8879. DirectionalLight.prototype.computeTransformedPosition = function () {
  8880. if (this.parent && this.parent.getWorldMatrix) {
  8881. if (!this.transformedPosition) {
  8882. this.transformedPosition = BABYLON.Vector3.Zero();
  8883. }
  8884. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8885. return true;
  8886. }
  8887. return false;
  8888. };
  8889. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8890. if (this.parent && this.parent.getWorldMatrix) {
  8891. if (!this._transformedDirection) {
  8892. this._transformedDirection = BABYLON.Vector3.Zero();
  8893. }
  8894. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8895. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8896. return;
  8897. }
  8898. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8899. };
  8900. DirectionalLight.prototype._getWorldMatrix = function () {
  8901. if (!this._worldMatrix) {
  8902. this._worldMatrix = BABYLON.Matrix.Identity();
  8903. }
  8904. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8905. return this._worldMatrix;
  8906. };
  8907. return DirectionalLight;
  8908. })(BABYLON.Light);
  8909. BABYLON.DirectionalLight = DirectionalLight;
  8910. })(BABYLON || (BABYLON = {}));
  8911. var BABYLON;
  8912. (function (BABYLON) {
  8913. var ShadowGenerator = (function () {
  8914. function ShadowGenerator(mapSize, light) {
  8915. var _this = this;
  8916. // Members
  8917. this._filter = ShadowGenerator.FILTER_NONE;
  8918. this.blurScale = 2;
  8919. this._blurBoxOffset = 0;
  8920. this._bias = 0.00005;
  8921. this._lightDirection = BABYLON.Vector3.Zero();
  8922. this._darkness = 0;
  8923. this._transparencyShadow = false;
  8924. this._viewMatrix = BABYLON.Matrix.Zero();
  8925. this._projectionMatrix = BABYLON.Matrix.Zero();
  8926. this._transformMatrix = BABYLON.Matrix.Zero();
  8927. this._worldViewProjection = BABYLON.Matrix.Zero();
  8928. this._light = light;
  8929. this._scene = light.getScene();
  8930. this._mapSize = mapSize;
  8931. light._shadowGenerator = this;
  8932. // Render target
  8933. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8934. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8935. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8936. this._shadowMap.anisotropicFilteringLevel = 1;
  8937. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8938. this._shadowMap.renderParticles = false;
  8939. this._shadowMap.onAfterUnbind = function () {
  8940. if (!_this.useBlurVarianceShadowMap) {
  8941. return;
  8942. }
  8943. if (!_this._shadowMap2) {
  8944. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8945. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8946. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8947. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8948. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8949. _this._downSamplePostprocess.onApply = function (effect) {
  8950. effect.setTexture("textureSampler", _this._shadowMap);
  8951. };
  8952. _this.blurBoxOffset = 1;
  8953. }
  8954. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8955. };
  8956. // Custom render function
  8957. var renderSubMesh = function (subMesh) {
  8958. var mesh = subMesh.getRenderingMesh();
  8959. var scene = _this._scene;
  8960. var engine = scene.getEngine();
  8961. // Culling
  8962. engine.setState(subMesh.getMaterial().backFaceCulling);
  8963. // Managing instances
  8964. var batch = mesh._getInstancesRenderList(subMesh._id);
  8965. if (batch.mustReturn) {
  8966. return;
  8967. }
  8968. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8969. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8970. engine.enableEffect(_this._effect);
  8971. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8972. var material = subMesh.getMaterial();
  8973. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8974. // Alpha test
  8975. if (material && material.needAlphaTesting()) {
  8976. var alphaTexture = material.getAlphaTestTexture();
  8977. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8978. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8979. }
  8980. // Bones
  8981. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  8982. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8983. }
  8984. // Draw
  8985. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8986. }
  8987. else {
  8988. // Need to reset refresh rate of the shadowMap
  8989. _this._shadowMap.resetRefreshCounter();
  8990. }
  8991. };
  8992. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8993. var index;
  8994. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8995. renderSubMesh(opaqueSubMeshes.data[index]);
  8996. }
  8997. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8998. renderSubMesh(alphaTestSubMeshes.data[index]);
  8999. }
  9000. if (_this._transparencyShadow) {
  9001. for (index = 0; index < transparentSubMeshes.length; index++) {
  9002. renderSubMesh(transparentSubMeshes.data[index]);
  9003. }
  9004. }
  9005. };
  9006. this._shadowMap.onClear = function (engine) {
  9007. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9008. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9009. }
  9010. else {
  9011. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9012. }
  9013. };
  9014. }
  9015. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9016. // Static
  9017. get: function () {
  9018. return ShadowGenerator._FILTER_NONE;
  9019. },
  9020. enumerable: true,
  9021. configurable: true
  9022. });
  9023. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9024. get: function () {
  9025. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9026. },
  9027. enumerable: true,
  9028. configurable: true
  9029. });
  9030. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9031. get: function () {
  9032. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9033. },
  9034. enumerable: true,
  9035. configurable: true
  9036. });
  9037. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9038. get: function () {
  9039. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  9040. },
  9041. enumerable: true,
  9042. configurable: true
  9043. });
  9044. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  9045. get: function () {
  9046. return this._bias;
  9047. },
  9048. set: function (bias) {
  9049. this._bias = bias;
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  9055. get: function () {
  9056. return this._blurBoxOffset;
  9057. },
  9058. set: function (value) {
  9059. var _this = this;
  9060. if (this._blurBoxOffset === value) {
  9061. return;
  9062. }
  9063. this._blurBoxOffset = value;
  9064. if (this._boxBlurPostprocess) {
  9065. this._boxBlurPostprocess.dispose();
  9066. }
  9067. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  9068. this._boxBlurPostprocess.onApply = function (effect) {
  9069. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  9070. };
  9071. },
  9072. enumerable: true,
  9073. configurable: true
  9074. });
  9075. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  9076. get: function () {
  9077. return this._filter;
  9078. },
  9079. set: function (value) {
  9080. if (this._filter === value) {
  9081. return;
  9082. }
  9083. this._filter = value;
  9084. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9085. this._shadowMap.anisotropicFilteringLevel = 16;
  9086. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  9087. }
  9088. else {
  9089. this._shadowMap.anisotropicFilteringLevel = 1;
  9090. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9091. }
  9092. },
  9093. enumerable: true,
  9094. configurable: true
  9095. });
  9096. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  9097. get: function () {
  9098. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  9099. },
  9100. set: function (value) {
  9101. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9102. },
  9103. enumerable: true,
  9104. configurable: true
  9105. });
  9106. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  9107. get: function () {
  9108. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  9109. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  9110. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  9111. },
  9112. set: function (value) {
  9113. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  9114. },
  9115. enumerable: true,
  9116. configurable: true
  9117. });
  9118. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  9119. get: function () {
  9120. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  9121. },
  9122. set: function (value) {
  9123. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  9124. },
  9125. enumerable: true,
  9126. configurable: true
  9127. });
  9128. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  9129. var defines = [];
  9130. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  9131. defines.push("#define VSM");
  9132. }
  9133. var attribs = [BABYLON.VertexBuffer.PositionKind];
  9134. var mesh = subMesh.getMesh();
  9135. var material = subMesh.getMaterial();
  9136. // Alpha test
  9137. if (material && material.needAlphaTesting()) {
  9138. defines.push("#define ALPHATEST");
  9139. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9140. attribs.push(BABYLON.VertexBuffer.UVKind);
  9141. defines.push("#define UV1");
  9142. }
  9143. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  9144. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  9145. defines.push("#define UV2");
  9146. }
  9147. }
  9148. // Bones
  9149. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9150. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  9151. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  9152. defines.push("#define BONES");
  9153. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  9154. }
  9155. // Instances
  9156. if (useInstances) {
  9157. defines.push("#define INSTANCES");
  9158. attribs.push("world0");
  9159. attribs.push("world1");
  9160. attribs.push("world2");
  9161. attribs.push("world3");
  9162. }
  9163. // Get correct effect
  9164. var join = defines.join("\n");
  9165. if (this._cachedDefines !== join) {
  9166. this._cachedDefines = join;
  9167. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  9168. }
  9169. return this._effect.isReady();
  9170. };
  9171. ShadowGenerator.prototype.getShadowMap = function () {
  9172. return this._shadowMap;
  9173. };
  9174. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  9175. if (this._shadowMap2) {
  9176. return this._shadowMap2;
  9177. }
  9178. return this._shadowMap;
  9179. };
  9180. ShadowGenerator.prototype.getLight = function () {
  9181. return this._light;
  9182. };
  9183. // Methods
  9184. ShadowGenerator.prototype.getTransformMatrix = function () {
  9185. var scene = this._scene;
  9186. if (this._currentRenderID === scene.getRenderId()) {
  9187. return this._transformMatrix;
  9188. }
  9189. this._currentRenderID = scene.getRenderId();
  9190. var lightPosition = this._light.position;
  9191. BABYLON.Vector3.NormalizeToRef(this._light.direction, this._lightDirection);
  9192. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) == 1.0) {
  9193. this._lightDirection.z = 0.0000000000001; // Need to avoid perfectly perpendicular light
  9194. }
  9195. if (this._light.computeTransformedPosition()) {
  9196. lightPosition = this._light.transformedPosition;
  9197. }
  9198. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  9199. this._cachedPosition = lightPosition.clone();
  9200. this._cachedDirection = this._lightDirection.clone();
  9201. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  9202. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  9203. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  9204. }
  9205. return this._transformMatrix;
  9206. };
  9207. ShadowGenerator.prototype.getDarkness = function () {
  9208. return this._darkness;
  9209. };
  9210. ShadowGenerator.prototype.setDarkness = function (darkness) {
  9211. if (darkness >= 1.0)
  9212. this._darkness = 1.0;
  9213. else if (darkness <= 0.0)
  9214. this._darkness = 0.0;
  9215. else
  9216. this._darkness = darkness;
  9217. };
  9218. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  9219. this._transparencyShadow = hasShadow;
  9220. };
  9221. ShadowGenerator.prototype._packHalf = function (depth) {
  9222. var scale = depth * 255.0;
  9223. var fract = scale - Math.floor(scale);
  9224. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  9225. };
  9226. ShadowGenerator.prototype.dispose = function () {
  9227. this._shadowMap.dispose();
  9228. if (this._shadowMap2) {
  9229. this._shadowMap2.dispose();
  9230. }
  9231. if (this._downSamplePostprocess) {
  9232. this._downSamplePostprocess.dispose();
  9233. }
  9234. if (this._boxBlurPostprocess) {
  9235. this._boxBlurPostprocess.dispose();
  9236. }
  9237. };
  9238. ShadowGenerator._FILTER_NONE = 0;
  9239. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9240. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9241. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9242. return ShadowGenerator;
  9243. })();
  9244. BABYLON.ShadowGenerator = ShadowGenerator;
  9245. })(BABYLON || (BABYLON = {}));
  9246. var BABYLON;
  9247. (function (BABYLON) {
  9248. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9249. if (boxMin.x > sphereCenter.x + sphereRadius)
  9250. return false;
  9251. if (sphereCenter.x - sphereRadius > boxMax.x)
  9252. return false;
  9253. if (boxMin.y > sphereCenter.y + sphereRadius)
  9254. return false;
  9255. if (sphereCenter.y - sphereRadius > boxMax.y)
  9256. return false;
  9257. if (boxMin.z > sphereCenter.z + sphereRadius)
  9258. return false;
  9259. if (sphereCenter.z - sphereRadius > boxMax.z)
  9260. return false;
  9261. return true;
  9262. };
  9263. var getLowestRoot = function (a, b, c, maxR) {
  9264. var determinant = b * b - 4.0 * a * c;
  9265. var result = { root: 0, found: false };
  9266. if (determinant < 0)
  9267. return result;
  9268. var sqrtD = Math.sqrt(determinant);
  9269. var r1 = (-b - sqrtD) / (2.0 * a);
  9270. var r2 = (-b + sqrtD) / (2.0 * a);
  9271. if (r1 > r2) {
  9272. var temp = r2;
  9273. r2 = r1;
  9274. r1 = temp;
  9275. }
  9276. if (r1 > 0 && r1 < maxR) {
  9277. result.root = r1;
  9278. result.found = true;
  9279. return result;
  9280. }
  9281. if (r2 > 0 && r2 < maxR) {
  9282. result.root = r2;
  9283. result.found = true;
  9284. return result;
  9285. }
  9286. return result;
  9287. };
  9288. var Collider = (function () {
  9289. function Collider() {
  9290. this.radius = new BABYLON.Vector3(1, 1, 1);
  9291. this.retry = 0;
  9292. this.basePointWorld = BABYLON.Vector3.Zero();
  9293. this.velocityWorld = BABYLON.Vector3.Zero();
  9294. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9295. this._collisionPoint = BABYLON.Vector3.Zero();
  9296. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9297. this._tempVector = BABYLON.Vector3.Zero();
  9298. this._tempVector2 = BABYLON.Vector3.Zero();
  9299. this._tempVector3 = BABYLON.Vector3.Zero();
  9300. this._tempVector4 = BABYLON.Vector3.Zero();
  9301. this._edge = BABYLON.Vector3.Zero();
  9302. this._baseToVertex = BABYLON.Vector3.Zero();
  9303. this._destinationPoint = BABYLON.Vector3.Zero();
  9304. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9305. this._displacementVector = BABYLON.Vector3.Zero();
  9306. }
  9307. // Methods
  9308. Collider.prototype._initialize = function (source, dir, e) {
  9309. this.velocity = dir;
  9310. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9311. this.basePoint = source;
  9312. source.multiplyToRef(this.radius, this.basePointWorld);
  9313. dir.multiplyToRef(this.radius, this.velocityWorld);
  9314. this.velocityWorldLength = this.velocityWorld.length();
  9315. this.epsilon = e;
  9316. this.collisionFound = false;
  9317. };
  9318. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9319. pa.subtractToRef(point, this._tempVector);
  9320. pb.subtractToRef(point, this._tempVector2);
  9321. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9322. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9323. if (d < 0)
  9324. return false;
  9325. pc.subtractToRef(point, this._tempVector3);
  9326. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9327. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9328. if (d < 0)
  9329. return false;
  9330. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9331. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9332. return d >= 0;
  9333. };
  9334. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9335. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9336. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9337. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9338. return false;
  9339. }
  9340. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9341. return false;
  9342. return true;
  9343. };
  9344. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9345. var t0;
  9346. var embeddedInPlane = false;
  9347. //defensive programming, actually not needed.
  9348. if (!trianglePlaneArray) {
  9349. trianglePlaneArray = [];
  9350. }
  9351. if (!trianglePlaneArray[faceIndex]) {
  9352. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9353. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9354. }
  9355. var trianglePlane = trianglePlaneArray[faceIndex];
  9356. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9357. return;
  9358. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9359. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9360. if (normalDotVelocity == 0) {
  9361. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9362. return;
  9363. embeddedInPlane = true;
  9364. t0 = 0;
  9365. }
  9366. else {
  9367. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9368. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9369. if (t0 > t1) {
  9370. var temp = t1;
  9371. t1 = t0;
  9372. t0 = temp;
  9373. }
  9374. if (t0 > 1.0 || t1 < 0.0)
  9375. return;
  9376. if (t0 < 0)
  9377. t0 = 0;
  9378. if (t0 > 1.0)
  9379. t0 = 1.0;
  9380. }
  9381. this._collisionPoint.copyFromFloats(0, 0, 0);
  9382. var found = false;
  9383. var t = 1.0;
  9384. if (!embeddedInPlane) {
  9385. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9386. this.velocity.scaleToRef(t0, this._tempVector);
  9387. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9388. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9389. found = true;
  9390. t = t0;
  9391. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9392. }
  9393. }
  9394. if (!found) {
  9395. var velocitySquaredLength = this.velocity.lengthSquared();
  9396. var a = velocitySquaredLength;
  9397. this.basePoint.subtractToRef(p1, this._tempVector);
  9398. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9399. var c = this._tempVector.lengthSquared() - 1.0;
  9400. var lowestRoot = getLowestRoot(a, b, c, t);
  9401. if (lowestRoot.found) {
  9402. t = lowestRoot.root;
  9403. found = true;
  9404. this._collisionPoint.copyFrom(p1);
  9405. }
  9406. this.basePoint.subtractToRef(p2, this._tempVector);
  9407. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9408. c = this._tempVector.lengthSquared() - 1.0;
  9409. lowestRoot = getLowestRoot(a, b, c, t);
  9410. if (lowestRoot.found) {
  9411. t = lowestRoot.root;
  9412. found = true;
  9413. this._collisionPoint.copyFrom(p2);
  9414. }
  9415. this.basePoint.subtractToRef(p3, this._tempVector);
  9416. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9417. c = this._tempVector.lengthSquared() - 1.0;
  9418. lowestRoot = getLowestRoot(a, b, c, t);
  9419. if (lowestRoot.found) {
  9420. t = lowestRoot.root;
  9421. found = true;
  9422. this._collisionPoint.copyFrom(p3);
  9423. }
  9424. p2.subtractToRef(p1, this._edge);
  9425. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9426. var edgeSquaredLength = this._edge.lengthSquared();
  9427. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9428. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9429. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9430. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9431. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9432. lowestRoot = getLowestRoot(a, b, c, t);
  9433. if (lowestRoot.found) {
  9434. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9435. if (f >= 0.0 && f <= 1.0) {
  9436. t = lowestRoot.root;
  9437. found = true;
  9438. this._edge.scaleInPlace(f);
  9439. p1.addToRef(this._edge, this._collisionPoint);
  9440. }
  9441. }
  9442. p3.subtractToRef(p2, this._edge);
  9443. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9444. edgeSquaredLength = this._edge.lengthSquared();
  9445. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9446. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9447. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9448. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9449. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9450. lowestRoot = getLowestRoot(a, b, c, t);
  9451. if (lowestRoot.found) {
  9452. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9453. if (f >= 0.0 && f <= 1.0) {
  9454. t = lowestRoot.root;
  9455. found = true;
  9456. this._edge.scaleInPlace(f);
  9457. p2.addToRef(this._edge, this._collisionPoint);
  9458. }
  9459. }
  9460. p1.subtractToRef(p3, this._edge);
  9461. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9462. edgeSquaredLength = this._edge.lengthSquared();
  9463. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9464. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9465. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9466. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9467. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9468. lowestRoot = getLowestRoot(a, b, c, t);
  9469. if (lowestRoot.found) {
  9470. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9471. if (f >= 0.0 && f <= 1.0) {
  9472. t = lowestRoot.root;
  9473. found = true;
  9474. this._edge.scaleInPlace(f);
  9475. p3.addToRef(this._edge, this._collisionPoint);
  9476. }
  9477. }
  9478. }
  9479. if (found) {
  9480. var distToCollision = t * this.velocity.length();
  9481. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9482. if (!this.intersectionPoint) {
  9483. this.intersectionPoint = this._collisionPoint.clone();
  9484. }
  9485. else {
  9486. this.intersectionPoint.copyFrom(this._collisionPoint);
  9487. }
  9488. this.nearestDistance = distToCollision;
  9489. this.collisionFound = true;
  9490. }
  9491. }
  9492. };
  9493. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9494. for (var i = indexStart; i < indexEnd; i += 3) {
  9495. var p1 = pts[indices[i] - decal];
  9496. var p2 = pts[indices[i + 1] - decal];
  9497. var p3 = pts[indices[i + 2] - decal];
  9498. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9499. }
  9500. };
  9501. Collider.prototype._getResponse = function (pos, vel) {
  9502. pos.addToRef(vel, this._destinationPoint);
  9503. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9504. this.basePoint.addToRef(vel, pos);
  9505. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9506. this._slidePlaneNormal.normalize();
  9507. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9508. pos.addInPlace(this._displacementVector);
  9509. this.intersectionPoint.addInPlace(this._displacementVector);
  9510. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9511. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9512. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9513. };
  9514. return Collider;
  9515. })();
  9516. BABYLON.Collider = Collider;
  9517. })(BABYLON || (BABYLON = {}));
  9518. var BABYLON;
  9519. (function (BABYLON) {
  9520. //WebWorker code will be inserted to this variable.
  9521. BABYLON.CollisionWorker = "";
  9522. (function (WorkerTaskType) {
  9523. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9524. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9525. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9526. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9527. var WorkerTaskType = BABYLON.WorkerTaskType;
  9528. (function (WorkerReplyType) {
  9529. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9530. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9531. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9532. var WorkerReplyType = BABYLON.WorkerReplyType;
  9533. var CollisionCoordinatorWorker = (function () {
  9534. function CollisionCoordinatorWorker() {
  9535. var _this = this;
  9536. this._scaledPosition = BABYLON.Vector3.Zero();
  9537. this._scaledVelocity = BABYLON.Vector3.Zero();
  9538. this.onMeshUpdated = function (mesh) {
  9539. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9540. };
  9541. this.onGeometryUpdated = function (geometry) {
  9542. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9543. };
  9544. this._afterRender = function () {
  9545. if (!_this._init)
  9546. return;
  9547. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9548. return;
  9549. }
  9550. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9551. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9552. if (_this._runningUpdated > 4) {
  9553. return;
  9554. }
  9555. ++_this._runningUpdated;
  9556. var payload = {
  9557. updatedMeshes: _this._addUpdateMeshesList,
  9558. updatedGeometries: _this._addUpdateGeometriesList,
  9559. removedGeometries: _this._toRemoveGeometryArray,
  9560. removedMeshes: _this._toRemoveMeshesArray
  9561. };
  9562. var message = {
  9563. payload: payload,
  9564. taskType: WorkerTaskType.UPDATE
  9565. };
  9566. var serializable = [];
  9567. for (var id in payload.updatedGeometries) {
  9568. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9569. //prepare transferables
  9570. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9571. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9572. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9573. }
  9574. }
  9575. _this._worker.postMessage(message, serializable);
  9576. _this._addUpdateMeshesList = {};
  9577. _this._addUpdateGeometriesList = {};
  9578. _this._toRemoveGeometryArray = [];
  9579. _this._toRemoveMeshesArray = [];
  9580. };
  9581. this._onMessageFromWorker = function (e) {
  9582. var returnData = e.data;
  9583. if (returnData.error != WorkerReplyType.SUCCESS) {
  9584. //TODO what errors can be returned from the worker?
  9585. BABYLON.Tools.Warn("error returned from worker!");
  9586. return;
  9587. }
  9588. switch (returnData.taskType) {
  9589. case WorkerTaskType.INIT:
  9590. _this._init = true;
  9591. //Update the worked with ALL of the scene's current state
  9592. _this._scene.meshes.forEach(function (mesh) {
  9593. _this.onMeshAdded(mesh);
  9594. });
  9595. _this._scene.getGeometries().forEach(function (geometry) {
  9596. _this.onGeometryAdded(geometry);
  9597. });
  9598. break;
  9599. case WorkerTaskType.UPDATE:
  9600. _this._runningUpdated--;
  9601. break;
  9602. case WorkerTaskType.COLLIDE:
  9603. _this._runningCollisionTask = false;
  9604. var returnPayload = returnData.payload;
  9605. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9606. return;
  9607. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9608. //cleanup
  9609. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9610. break;
  9611. }
  9612. };
  9613. this._collisionsCallbackArray = [];
  9614. this._init = false;
  9615. this._runningUpdated = 0;
  9616. this._runningCollisionTask = false;
  9617. this._addUpdateMeshesList = {};
  9618. this._addUpdateGeometriesList = {};
  9619. this._toRemoveGeometryArray = [];
  9620. this._toRemoveMeshesArray = [];
  9621. }
  9622. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9623. if (!this._init)
  9624. return;
  9625. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9626. return;
  9627. position.divideToRef(collider.radius, this._scaledPosition);
  9628. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9629. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9630. var payload = {
  9631. collider: {
  9632. position: this._scaledPosition.asArray(),
  9633. velocity: this._scaledVelocity.asArray(),
  9634. radius: collider.radius.asArray()
  9635. },
  9636. collisionId: collisionIndex,
  9637. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9638. maximumRetry: maximumRetry
  9639. };
  9640. var message = {
  9641. payload: payload,
  9642. taskType: WorkerTaskType.COLLIDE
  9643. };
  9644. this._worker.postMessage(message);
  9645. };
  9646. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9647. this._scene = scene;
  9648. this._scene.registerAfterRender(this._afterRender);
  9649. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9650. this._worker = new Worker(workerUrl);
  9651. this._worker.onmessage = this._onMessageFromWorker;
  9652. var message = {
  9653. payload: {},
  9654. taskType: WorkerTaskType.INIT
  9655. };
  9656. this._worker.postMessage(message);
  9657. };
  9658. CollisionCoordinatorWorker.prototype.destroy = function () {
  9659. this._scene.unregisterAfterRender(this._afterRender);
  9660. this._worker.terminate();
  9661. };
  9662. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9663. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9664. this.onMeshUpdated(mesh);
  9665. };
  9666. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9667. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9668. };
  9669. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9670. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9671. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9672. this.onGeometryUpdated(geometry);
  9673. };
  9674. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9675. this._toRemoveGeometryArray.push(geometry.id);
  9676. };
  9677. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9678. var submeshes = [];
  9679. if (mesh.subMeshes) {
  9680. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9681. return {
  9682. position: idx,
  9683. verticesStart: sm.verticesStart,
  9684. verticesCount: sm.verticesCount,
  9685. indexStart: sm.indexStart,
  9686. indexCount: sm.indexCount,
  9687. hasMaterial: !!sm.getMaterial(),
  9688. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9689. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9690. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9691. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9692. };
  9693. });
  9694. }
  9695. var geometryId = null;
  9696. if (mesh instanceof BABYLON.Mesh) {
  9697. geometryId = mesh.geometry ? mesh.geometry.id : null;
  9698. }
  9699. else if (mesh instanceof BABYLON.InstancedMesh) {
  9700. geometryId = mesh.sourceMesh.geometry ? mesh.sourceMesh.geometry.id : null;
  9701. }
  9702. return {
  9703. uniqueId: mesh.uniqueId,
  9704. id: mesh.id,
  9705. name: mesh.name,
  9706. geometryId: geometryId,
  9707. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9708. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9709. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9710. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9711. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9712. subMeshes: submeshes,
  9713. checkCollisions: mesh.checkCollisions
  9714. };
  9715. };
  9716. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9717. return {
  9718. id: geometry.id,
  9719. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9720. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9721. indices: new Int32Array(geometry.getIndices() || []),
  9722. };
  9723. };
  9724. return CollisionCoordinatorWorker;
  9725. })();
  9726. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9727. var CollisionCoordinatorLegacy = (function () {
  9728. function CollisionCoordinatorLegacy() {
  9729. this._scaledPosition = BABYLON.Vector3.Zero();
  9730. this._scaledVelocity = BABYLON.Vector3.Zero();
  9731. this._finalPosition = BABYLON.Vector3.Zero();
  9732. }
  9733. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9734. position.divideToRef(collider.radius, this._scaledPosition);
  9735. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9736. collider.collidedMesh = null;
  9737. collider.retry = 0;
  9738. collider.initialVelocity = this._scaledVelocity;
  9739. collider.initialPosition = this._scaledPosition;
  9740. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9741. this._finalPosition.multiplyInPlace(collider.radius);
  9742. //run the callback
  9743. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9744. };
  9745. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9746. this._scene = scene;
  9747. };
  9748. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9749. //Legacy need no destruction method.
  9750. };
  9751. //No update in legacy mode
  9752. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9753. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9754. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9755. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9756. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9757. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9758. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9759. if (excludedMesh === void 0) { excludedMesh = null; }
  9760. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9761. if (collider.retry >= maximumRetry) {
  9762. finalPosition.copyFrom(position);
  9763. return;
  9764. }
  9765. collider._initialize(position, velocity, closeDistance);
  9766. // Check all meshes
  9767. for (var index = 0; index < this._scene.meshes.length; index++) {
  9768. var mesh = this._scene.meshes[index];
  9769. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9770. mesh._checkCollision(collider);
  9771. }
  9772. }
  9773. if (!collider.collisionFound) {
  9774. position.addToRef(velocity, finalPosition);
  9775. return;
  9776. }
  9777. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9778. collider._getResponse(position, velocity);
  9779. }
  9780. if (velocity.length() <= closeDistance) {
  9781. finalPosition.copyFrom(position);
  9782. return;
  9783. }
  9784. collider.retry++;
  9785. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9786. };
  9787. return CollisionCoordinatorLegacy;
  9788. })();
  9789. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9790. })(BABYLON || (BABYLON = {}));
  9791. var BABYLON;
  9792. (function (BABYLON) {
  9793. var VRCameraMetrics = (function () {
  9794. function VRCameraMetrics() {
  9795. this.compensateDistorsion = true;
  9796. }
  9797. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9798. get: function () {
  9799. return this.hResolution / (2 * this.vResolution);
  9800. },
  9801. enumerable: true,
  9802. configurable: true
  9803. });
  9804. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9805. get: function () {
  9806. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9807. },
  9808. enumerable: true,
  9809. configurable: true
  9810. });
  9811. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9812. get: function () {
  9813. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9814. var h = (4 * meters) / this.hScreenSize;
  9815. return BABYLON.Matrix.Translation(h, 0, 0);
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9821. get: function () {
  9822. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9823. var h = (4 * meters) / this.hScreenSize;
  9824. return BABYLON.Matrix.Translation(-h, 0, 0);
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9830. get: function () {
  9831. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9832. },
  9833. enumerable: true,
  9834. configurable: true
  9835. });
  9836. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9837. get: function () {
  9838. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. VRCameraMetrics.GetDefault = function () {
  9844. var result = new VRCameraMetrics();
  9845. result.hResolution = 1280;
  9846. result.vResolution = 800;
  9847. result.hScreenSize = 0.149759993;
  9848. result.vScreenSize = 0.0935999975;
  9849. result.vScreenCenter = 0.0467999987,
  9850. result.eyeToScreenDistance = 0.0410000011;
  9851. result.lensSeparationDistance = 0.0635000020;
  9852. result.interpupillaryDistance = 0.0640000030;
  9853. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9854. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9855. result.postProcessScaleFactor = 1.714605507808412;
  9856. result.lensCenterOffset = 0.151976421;
  9857. return result;
  9858. };
  9859. return VRCameraMetrics;
  9860. })();
  9861. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9862. var Camera = (function (_super) {
  9863. __extends(Camera, _super);
  9864. function Camera(name, position, scene) {
  9865. _super.call(this, name, scene);
  9866. this.position = position;
  9867. // Members
  9868. this.upVector = BABYLON.Vector3.Up();
  9869. this.orthoLeft = null;
  9870. this.orthoRight = null;
  9871. this.orthoBottom = null;
  9872. this.orthoTop = null;
  9873. this.fov = 0.8;
  9874. this.minZ = 1.0;
  9875. this.maxZ = 10000.0;
  9876. this.inertia = 0.9;
  9877. this.mode = Camera.PERSPECTIVE_CAMERA;
  9878. this.isIntermediate = false;
  9879. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9880. this.layerMask = 0x0FFFFFFF;
  9881. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9882. // Camera rig members
  9883. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9884. this._rigCameras = new Array();
  9885. // Cache
  9886. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9887. this._projectionMatrix = new BABYLON.Matrix();
  9888. this._postProcesses = new Array();
  9889. this._postProcessesTakenIndices = [];
  9890. this._activeMeshes = new BABYLON.SmartArray(256);
  9891. this._globalPosition = BABYLON.Vector3.Zero();
  9892. scene.addCamera(this);
  9893. if (!scene.activeCamera) {
  9894. scene.activeCamera = this;
  9895. }
  9896. }
  9897. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9898. get: function () {
  9899. return Camera._PERSPECTIVE_CAMERA;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9905. get: function () {
  9906. return Camera._ORTHOGRAPHIC_CAMERA;
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9912. get: function () {
  9913. return Camera._FOVMODE_VERTICAL_FIXED;
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9919. get: function () {
  9920. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9926. get: function () {
  9927. return Camera._RIG_MODE_NONE;
  9928. },
  9929. enumerable: true,
  9930. configurable: true
  9931. });
  9932. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9933. get: function () {
  9934. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9940. get: function () {
  9941. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9947. get: function () {
  9948. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9954. get: function () {
  9955. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9961. get: function () {
  9962. return Camera._RIG_MODE_VR;
  9963. },
  9964. enumerable: true,
  9965. configurable: true
  9966. });
  9967. Object.defineProperty(Camera.prototype, "globalPosition", {
  9968. get: function () {
  9969. return this._globalPosition;
  9970. },
  9971. enumerable: true,
  9972. configurable: true
  9973. });
  9974. Camera.prototype.getActiveMeshes = function () {
  9975. return this._activeMeshes;
  9976. };
  9977. Camera.prototype.isActiveMesh = function (mesh) {
  9978. return (this._activeMeshes.indexOf(mesh) !== -1);
  9979. };
  9980. //Cache
  9981. Camera.prototype._initCache = function () {
  9982. _super.prototype._initCache.call(this);
  9983. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9984. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9985. this._cache.mode = undefined;
  9986. this._cache.minZ = undefined;
  9987. this._cache.maxZ = undefined;
  9988. this._cache.fov = undefined;
  9989. this._cache.aspectRatio = undefined;
  9990. this._cache.orthoLeft = undefined;
  9991. this._cache.orthoRight = undefined;
  9992. this._cache.orthoBottom = undefined;
  9993. this._cache.orthoTop = undefined;
  9994. this._cache.renderWidth = undefined;
  9995. this._cache.renderHeight = undefined;
  9996. };
  9997. Camera.prototype._updateCache = function (ignoreParentClass) {
  9998. if (!ignoreParentClass) {
  9999. _super.prototype._updateCache.call(this);
  10000. }
  10001. var engine = this.getEngine();
  10002. this._cache.position.copyFrom(this.position);
  10003. this._cache.upVector.copyFrom(this.upVector);
  10004. this._cache.mode = this.mode;
  10005. this._cache.minZ = this.minZ;
  10006. this._cache.maxZ = this.maxZ;
  10007. this._cache.fov = this.fov;
  10008. this._cache.aspectRatio = engine.getAspectRatio(this);
  10009. this._cache.orthoLeft = this.orthoLeft;
  10010. this._cache.orthoRight = this.orthoRight;
  10011. this._cache.orthoBottom = this.orthoBottom;
  10012. this._cache.orthoTop = this.orthoTop;
  10013. this._cache.renderWidth = engine.getRenderWidth();
  10014. this._cache.renderHeight = engine.getRenderHeight();
  10015. };
  10016. Camera.prototype._updateFromScene = function () {
  10017. this.updateCache();
  10018. this._update();
  10019. };
  10020. // Synchronized
  10021. Camera.prototype._isSynchronized = function () {
  10022. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10023. };
  10024. Camera.prototype._isSynchronizedViewMatrix = function () {
  10025. if (!_super.prototype._isSynchronized.call(this))
  10026. return false;
  10027. return this._cache.position.equals(this.position)
  10028. && this._cache.upVector.equals(this.upVector)
  10029. && this.isSynchronizedWithParent();
  10030. };
  10031. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10032. var check = this._cache.mode === this.mode
  10033. && this._cache.minZ === this.minZ
  10034. && this._cache.maxZ === this.maxZ;
  10035. if (!check) {
  10036. return false;
  10037. }
  10038. var engine = this.getEngine();
  10039. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10040. check = this._cache.fov === this.fov
  10041. && this._cache.aspectRatio === engine.getAspectRatio(this);
  10042. }
  10043. else {
  10044. check = this._cache.orthoLeft === this.orthoLeft
  10045. && this._cache.orthoRight === this.orthoRight
  10046. && this._cache.orthoBottom === this.orthoBottom
  10047. && this._cache.orthoTop === this.orthoTop
  10048. && this._cache.renderWidth === engine.getRenderWidth()
  10049. && this._cache.renderHeight === engine.getRenderHeight();
  10050. }
  10051. return check;
  10052. };
  10053. // Controls
  10054. Camera.prototype.attachControl = function (element) {
  10055. };
  10056. Camera.prototype.detachControl = function (element) {
  10057. };
  10058. Camera.prototype._update = function () {
  10059. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  10060. this._updateRigCameras();
  10061. }
  10062. this._checkInputs();
  10063. };
  10064. Camera.prototype._checkInputs = function () {
  10065. };
  10066. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  10067. if (insertAt === void 0) { insertAt = null; }
  10068. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  10069. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  10070. return 0;
  10071. }
  10072. if (insertAt == null || insertAt < 0) {
  10073. this._postProcesses.push(postProcess);
  10074. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  10075. return this._postProcesses.length - 1;
  10076. }
  10077. var add = 0;
  10078. if (this._postProcesses[insertAt]) {
  10079. var start = this._postProcesses.length - 1;
  10080. for (var i = start; i >= insertAt + 1; --i) {
  10081. this._postProcesses[i + 1] = this._postProcesses[i];
  10082. }
  10083. add = 1;
  10084. }
  10085. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10086. if (this._postProcessesTakenIndices[i] < insertAt) {
  10087. continue;
  10088. }
  10089. start = this._postProcessesTakenIndices.length - 1;
  10090. for (var j = start; j >= i; --j) {
  10091. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  10092. }
  10093. this._postProcessesTakenIndices[i] = insertAt;
  10094. break;
  10095. }
  10096. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  10097. this._postProcessesTakenIndices.push(insertAt);
  10098. }
  10099. var result = insertAt + add;
  10100. this._postProcesses[result] = postProcess;
  10101. return result;
  10102. };
  10103. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  10104. if (atIndices === void 0) { atIndices = null; }
  10105. var result = [];
  10106. if (!atIndices) {
  10107. var length = this._postProcesses.length;
  10108. for (var i = 0; i < length; i++) {
  10109. if (this._postProcesses[i] !== postProcess) {
  10110. continue;
  10111. }
  10112. delete this._postProcesses[i];
  10113. var index = this._postProcessesTakenIndices.indexOf(i);
  10114. this._postProcessesTakenIndices.splice(index, 1);
  10115. }
  10116. }
  10117. else {
  10118. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  10119. for (i = 0; i < atIndices.length; i++) {
  10120. var foundPostProcess = this._postProcesses[atIndices[i]];
  10121. if (foundPostProcess !== postProcess) {
  10122. result.push(i);
  10123. continue;
  10124. }
  10125. delete this._postProcesses[atIndices[i]];
  10126. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  10127. this._postProcessesTakenIndices.splice(index, 1);
  10128. }
  10129. }
  10130. return result;
  10131. };
  10132. Camera.prototype.getWorldMatrix = function () {
  10133. if (!this._worldMatrix) {
  10134. this._worldMatrix = BABYLON.Matrix.Identity();
  10135. }
  10136. var viewMatrix = this.getViewMatrix();
  10137. viewMatrix.invertToRef(this._worldMatrix);
  10138. return this._worldMatrix;
  10139. };
  10140. Camera.prototype._getViewMatrix = function () {
  10141. return BABYLON.Matrix.Identity();
  10142. };
  10143. Camera.prototype.getViewMatrix = function (force) {
  10144. this._computedViewMatrix = this._computeViewMatrix(force);
  10145. if (!force && this._isSynchronizedViewMatrix()) {
  10146. return this._computedViewMatrix;
  10147. }
  10148. if (!this.parent || !this.parent.getWorldMatrix) {
  10149. this._globalPosition.copyFrom(this.position);
  10150. }
  10151. else {
  10152. if (!this._worldMatrix) {
  10153. this._worldMatrix = BABYLON.Matrix.Identity();
  10154. }
  10155. this._computedViewMatrix.invertToRef(this._worldMatrix);
  10156. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  10157. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  10158. this._computedViewMatrix.invert();
  10159. this._markSyncedWithParent();
  10160. }
  10161. this._currentRenderId = this.getScene().getRenderId();
  10162. return this._computedViewMatrix;
  10163. };
  10164. Camera.prototype._computeViewMatrix = function (force) {
  10165. if (!force && this._isSynchronizedViewMatrix()) {
  10166. return this._computedViewMatrix;
  10167. }
  10168. this._computedViewMatrix = this._getViewMatrix();
  10169. this._currentRenderId = this.getScene().getRenderId();
  10170. return this._computedViewMatrix;
  10171. };
  10172. Camera.prototype.getProjectionMatrix = function (force) {
  10173. if (!force && this._isSynchronizedProjectionMatrix()) {
  10174. return this._projectionMatrix;
  10175. }
  10176. var engine = this.getEngine();
  10177. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  10178. if (this.minZ <= 0) {
  10179. this.minZ = 0.1;
  10180. }
  10181. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  10182. return this._projectionMatrix;
  10183. }
  10184. var halfWidth = engine.getRenderWidth() / 2.0;
  10185. var halfHeight = engine.getRenderHeight() / 2.0;
  10186. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  10187. return this._projectionMatrix;
  10188. };
  10189. Camera.prototype.dispose = function () {
  10190. // Remove from scene
  10191. this.getScene().removeCamera(this);
  10192. while (this._rigCameras.length > 0) {
  10193. this._rigCameras.pop().dispose();
  10194. }
  10195. // Postprocesses
  10196. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  10197. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  10198. }
  10199. };
  10200. // ---- Camera rigs section ----
  10201. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  10202. while (this._rigCameras.length > 0) {
  10203. this._rigCameras.pop().dispose();
  10204. }
  10205. this.cameraRigMode = mode;
  10206. this._cameraRigParams = {};
  10207. switch (this.cameraRigMode) {
  10208. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10209. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10210. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10211. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10212. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  10213. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  10214. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  10215. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  10216. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10217. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10218. break;
  10219. }
  10220. var postProcesses = new Array();
  10221. switch (this.cameraRigMode) {
  10222. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10223. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  10224. this._rigCameras[0].isIntermediate = true;
  10225. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  10226. postProcesses[1].onApply = function (effect) {
  10227. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  10228. };
  10229. break;
  10230. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10231. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10232. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10233. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  10234. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  10235. var secondCamIndex = 1 - firstCamIndex;
  10236. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  10237. this._rigCameras[firstCamIndex].isIntermediate = true;
  10238. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  10239. break;
  10240. case Camera.RIG_MODE_VR:
  10241. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  10242. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  10243. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10244. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10245. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10246. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10247. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10248. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10249. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10250. if (metrics.compensateDistorsion) {
  10251. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10252. }
  10253. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10254. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10255. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10256. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10257. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10258. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10259. if (metrics.compensateDistorsion) {
  10260. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10261. }
  10262. break;
  10263. }
  10264. this._update();
  10265. };
  10266. Camera.prototype._getVRProjectionMatrix = function () {
  10267. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10268. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10269. return this._projectionMatrix;
  10270. };
  10271. Camera.prototype.setCameraRigParameter = function (name, value) {
  10272. this._cameraRigParams[name] = value;
  10273. //provisionnally:
  10274. if (name === "interaxialDistance") {
  10275. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10276. }
  10277. };
  10278. /**
  10279. * May needs to be overridden by children so sub has required properties to be copied
  10280. */
  10281. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10282. return null;
  10283. };
  10284. /**
  10285. * May needs to be overridden by children
  10286. */
  10287. Camera.prototype._updateRigCameras = function () {
  10288. for (var i = 0; i < this._rigCameras.length; i++) {
  10289. this._rigCameras[i].minZ = this.minZ;
  10290. this._rigCameras[i].maxZ = this.maxZ;
  10291. this._rigCameras[i].fov = this.fov;
  10292. }
  10293. // only update viewport when ANAGLYPH
  10294. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10295. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10296. }
  10297. };
  10298. // Statics
  10299. Camera._PERSPECTIVE_CAMERA = 0;
  10300. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10301. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10302. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10303. Camera._RIG_MODE_NONE = 0;
  10304. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10305. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10306. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10307. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10308. Camera._RIG_MODE_VR = 20;
  10309. return Camera;
  10310. })(BABYLON.Node);
  10311. BABYLON.Camera = Camera;
  10312. })(BABYLON || (BABYLON = {}));
  10313. var BABYLON;
  10314. (function (BABYLON) {
  10315. var TargetCamera = (function (_super) {
  10316. __extends(TargetCamera, _super);
  10317. function TargetCamera(name, position, scene) {
  10318. _super.call(this, name, position, scene);
  10319. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10320. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10321. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10322. this.speed = 2.0;
  10323. this.noRotationConstraint = false;
  10324. this.lockedTarget = null;
  10325. this._currentTarget = BABYLON.Vector3.Zero();
  10326. this._viewMatrix = BABYLON.Matrix.Zero();
  10327. this._camMatrix = BABYLON.Matrix.Zero();
  10328. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10329. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10330. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10331. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10332. this._lookAtTemp = BABYLON.Matrix.Zero();
  10333. this._tempMatrix = BABYLON.Matrix.Zero();
  10334. }
  10335. TargetCamera.prototype.getFrontPosition = function (distance) {
  10336. var direction = this.getTarget().subtract(this.position);
  10337. direction.normalize();
  10338. direction.scaleInPlace(distance);
  10339. return this.globalPosition.add(direction);
  10340. };
  10341. TargetCamera.prototype._getLockedTargetPosition = function () {
  10342. if (!this.lockedTarget) {
  10343. return null;
  10344. }
  10345. return this.lockedTarget.position || this.lockedTarget;
  10346. };
  10347. // Cache
  10348. TargetCamera.prototype._initCache = function () {
  10349. _super.prototype._initCache.call(this);
  10350. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10351. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10352. };
  10353. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10354. if (!ignoreParentClass) {
  10355. _super.prototype._updateCache.call(this);
  10356. }
  10357. var lockedTargetPosition = this._getLockedTargetPosition();
  10358. if (!lockedTargetPosition) {
  10359. this._cache.lockedTarget = null;
  10360. }
  10361. else {
  10362. if (!this._cache.lockedTarget) {
  10363. this._cache.lockedTarget = lockedTargetPosition.clone();
  10364. }
  10365. else {
  10366. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10367. }
  10368. }
  10369. this._cache.rotation.copyFrom(this.rotation);
  10370. };
  10371. // Synchronized
  10372. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10373. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10374. return false;
  10375. }
  10376. var lockedTargetPosition = this._getLockedTargetPosition();
  10377. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10378. && this._cache.rotation.equals(this.rotation);
  10379. };
  10380. // Methods
  10381. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10382. var engine = this.getEngine();
  10383. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10384. };
  10385. // Target
  10386. TargetCamera.prototype.setTarget = function (target) {
  10387. this.upVector.normalize();
  10388. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10389. this._camMatrix.invert();
  10390. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10391. var vDir = target.subtract(this.position);
  10392. if (vDir.x >= 0.0) {
  10393. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10394. }
  10395. else {
  10396. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10397. }
  10398. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10399. if (isNaN(this.rotation.x)) {
  10400. this.rotation.x = 0;
  10401. }
  10402. if (isNaN(this.rotation.y)) {
  10403. this.rotation.y = 0;
  10404. }
  10405. if (isNaN(this.rotation.z)) {
  10406. this.rotation.z = 0;
  10407. }
  10408. };
  10409. TargetCamera.prototype.getTarget = function () {
  10410. return this._currentTarget;
  10411. };
  10412. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10413. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10414. };
  10415. TargetCamera.prototype._updatePosition = function () {
  10416. this.position.addInPlace(this.cameraDirection);
  10417. };
  10418. TargetCamera.prototype._checkInputs = function () {
  10419. var needToMove = this._decideIfNeedsToMove();
  10420. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10421. // Move
  10422. if (needToMove) {
  10423. this._updatePosition();
  10424. }
  10425. // Rotate
  10426. if (needToRotate) {
  10427. this.rotation.x += this.cameraRotation.x;
  10428. this.rotation.y += this.cameraRotation.y;
  10429. if (!this.noRotationConstraint) {
  10430. var limit = (Math.PI / 2) * 0.95;
  10431. if (this.rotation.x > limit)
  10432. this.rotation.x = limit;
  10433. if (this.rotation.x < -limit)
  10434. this.rotation.x = -limit;
  10435. }
  10436. }
  10437. // Inertia
  10438. if (needToMove) {
  10439. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10440. this.cameraDirection.x = 0;
  10441. }
  10442. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10443. this.cameraDirection.y = 0;
  10444. }
  10445. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10446. this.cameraDirection.z = 0;
  10447. }
  10448. this.cameraDirection.scaleInPlace(this.inertia);
  10449. }
  10450. if (needToRotate) {
  10451. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10452. this.cameraRotation.x = 0;
  10453. }
  10454. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10455. this.cameraRotation.y = 0;
  10456. }
  10457. this.cameraRotation.scaleInPlace(this.inertia);
  10458. }
  10459. _super.prototype._checkInputs.call(this);
  10460. };
  10461. TargetCamera.prototype._getViewMatrix = function () {
  10462. if (!this.lockedTarget) {
  10463. // Compute
  10464. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10465. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10466. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10467. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10468. this._lookAtTemp.invert();
  10469. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10470. }
  10471. else {
  10472. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10473. }
  10474. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10475. // Computing target and final matrix
  10476. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10477. }
  10478. else {
  10479. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10480. }
  10481. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10482. return this._viewMatrix;
  10483. };
  10484. TargetCamera.prototype._getVRViewMatrix = function () {
  10485. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10486. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10487. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10488. // Computing target and final matrix
  10489. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10490. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10491. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10492. return this._viewMatrix;
  10493. };
  10494. /**
  10495. * @override
  10496. * Override Camera.createRigCamera
  10497. */
  10498. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10499. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10500. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10501. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10502. rigCamera._cameraRigParams = {};
  10503. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10504. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10505. }
  10506. return rigCamera;
  10507. }
  10508. return null;
  10509. };
  10510. /**
  10511. * @override
  10512. * Override Camera._updateRigCameras
  10513. */
  10514. TargetCamera.prototype._updateRigCameras = function () {
  10515. switch (this.cameraRigMode) {
  10516. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10517. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10518. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10519. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10520. case BABYLON.Camera.RIG_MODE_VR:
  10521. var camLeft = this._rigCameras[0];
  10522. var camRight = this._rigCameras[1];
  10523. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10524. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10525. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10526. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10527. camLeft.position.copyFrom(this.position);
  10528. camRight.position.copyFrom(this.position);
  10529. }
  10530. else {
  10531. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10532. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10533. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10534. camLeft.setTarget(this.getTarget());
  10535. camRight.setTarget(this.getTarget());
  10536. }
  10537. break;
  10538. }
  10539. _super.prototype._updateRigCameras.call(this);
  10540. };
  10541. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10542. if (!this._rigCamTransformMatrix) {
  10543. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10544. }
  10545. var target = this.getTarget();
  10546. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10547. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10548. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10549. };
  10550. return TargetCamera;
  10551. })(BABYLON.Camera);
  10552. BABYLON.TargetCamera = TargetCamera;
  10553. })(BABYLON || (BABYLON = {}));
  10554. var BABYLON;
  10555. (function (BABYLON) {
  10556. var FreeCamera = (function (_super) {
  10557. __extends(FreeCamera, _super);
  10558. function FreeCamera(name, position, scene) {
  10559. var _this = this;
  10560. _super.call(this, name, position, scene);
  10561. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10562. this.keysUp = [38];
  10563. this.keysDown = [40];
  10564. this.keysLeft = [37];
  10565. this.keysRight = [39];
  10566. this.checkCollisions = false;
  10567. this.applyGravity = false;
  10568. this.angularSensibility = 2000.0;
  10569. this._keys = [];
  10570. this._collider = new BABYLON.Collider();
  10571. this._needMoveForGravity = false;
  10572. this._oldPosition = BABYLON.Vector3.Zero();
  10573. this._diffPosition = BABYLON.Vector3.Zero();
  10574. this._newPosition = BABYLON.Vector3.Zero();
  10575. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10576. if (collidedMesh === void 0) { collidedMesh = null; }
  10577. //TODO move this to the collision coordinator!
  10578. if (_this.getScene().workerCollisions)
  10579. newPosition.multiplyInPlace(_this._collider.radius);
  10580. var updatePosition = function (newPos) {
  10581. _this._newPosition.copyFrom(newPos);
  10582. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10583. var oldPosition = _this.position.clone();
  10584. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10585. _this.position.addInPlace(_this._diffPosition);
  10586. if (_this.onCollide && collidedMesh) {
  10587. _this.onCollide(collidedMesh);
  10588. }
  10589. }
  10590. };
  10591. updatePosition(newPosition);
  10592. };
  10593. }
  10594. // Controls
  10595. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10596. var _this = this;
  10597. var previousPosition;
  10598. var engine = this.getEngine();
  10599. if (this._attachedElement) {
  10600. return;
  10601. }
  10602. this._attachedElement = element;
  10603. if (this._onMouseDown === undefined) {
  10604. this._onMouseDown = function (evt) {
  10605. previousPosition = {
  10606. x: evt.clientX,
  10607. y: evt.clientY
  10608. };
  10609. if (!noPreventDefault) {
  10610. evt.preventDefault();
  10611. }
  10612. };
  10613. this._onMouseUp = function (evt) {
  10614. previousPosition = null;
  10615. if (!noPreventDefault) {
  10616. evt.preventDefault();
  10617. }
  10618. };
  10619. this._onMouseOut = function (evt) {
  10620. previousPosition = null;
  10621. _this._keys = [];
  10622. if (!noPreventDefault) {
  10623. evt.preventDefault();
  10624. }
  10625. };
  10626. this._onMouseMove = function (evt) {
  10627. if (!previousPosition && !engine.isPointerLock) {
  10628. return;
  10629. }
  10630. var offsetX;
  10631. var offsetY;
  10632. if (!engine.isPointerLock) {
  10633. offsetX = evt.clientX - previousPosition.x;
  10634. offsetY = evt.clientY - previousPosition.y;
  10635. }
  10636. else {
  10637. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10638. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10639. }
  10640. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10641. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10642. previousPosition = {
  10643. x: evt.clientX,
  10644. y: evt.clientY
  10645. };
  10646. if (!noPreventDefault) {
  10647. evt.preventDefault();
  10648. }
  10649. };
  10650. this._onKeyDown = function (evt) {
  10651. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10652. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10653. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10654. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10655. var index = _this._keys.indexOf(evt.keyCode);
  10656. if (index === -1) {
  10657. _this._keys.push(evt.keyCode);
  10658. }
  10659. if (!noPreventDefault) {
  10660. evt.preventDefault();
  10661. }
  10662. }
  10663. };
  10664. this._onKeyUp = function (evt) {
  10665. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10666. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10667. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10668. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10669. var index = _this._keys.indexOf(evt.keyCode);
  10670. if (index >= 0) {
  10671. _this._keys.splice(index, 1);
  10672. }
  10673. if (!noPreventDefault) {
  10674. evt.preventDefault();
  10675. }
  10676. }
  10677. };
  10678. this._onLostFocus = function () {
  10679. _this._keys = [];
  10680. };
  10681. this._reset = function () {
  10682. _this._keys = [];
  10683. previousPosition = null;
  10684. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10685. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10686. };
  10687. }
  10688. element.addEventListener("mousedown", this._onMouseDown, false);
  10689. element.addEventListener("mouseup", this._onMouseUp, false);
  10690. element.addEventListener("mouseout", this._onMouseOut, false);
  10691. element.addEventListener("mousemove", this._onMouseMove, false);
  10692. BABYLON.Tools.RegisterTopRootEvents([
  10693. { name: "keydown", handler: this._onKeyDown },
  10694. { name: "keyup", handler: this._onKeyUp },
  10695. { name: "blur", handler: this._onLostFocus }
  10696. ]);
  10697. };
  10698. FreeCamera.prototype.detachControl = function (element) {
  10699. if (this._attachedElement != element) {
  10700. return;
  10701. }
  10702. element.removeEventListener("mousedown", this._onMouseDown);
  10703. element.removeEventListener("mouseup", this._onMouseUp);
  10704. element.removeEventListener("mouseout", this._onMouseOut);
  10705. element.removeEventListener("mousemove", this._onMouseMove);
  10706. BABYLON.Tools.UnregisterTopRootEvents([
  10707. { name: "keydown", handler: this._onKeyDown },
  10708. { name: "keyup", handler: this._onKeyUp },
  10709. { name: "blur", handler: this._onLostFocus }
  10710. ]);
  10711. this._attachedElement = null;
  10712. if (this._reset) {
  10713. this._reset();
  10714. }
  10715. };
  10716. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10717. var globalPosition;
  10718. if (this.parent) {
  10719. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10720. }
  10721. else {
  10722. globalPosition = this.position;
  10723. }
  10724. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10725. this._collider.radius = this.ellipsoid;
  10726. //add gravity to the velocity to prevent the dual-collision checking
  10727. if (this.applyGravity) {
  10728. velocity.addInPlace(this.getScene().gravity);
  10729. }
  10730. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10731. };
  10732. FreeCamera.prototype._checkInputs = function () {
  10733. if (!this._localDirection) {
  10734. this._localDirection = BABYLON.Vector3.Zero();
  10735. this._transformedDirection = BABYLON.Vector3.Zero();
  10736. }
  10737. // Keyboard
  10738. for (var index = 0; index < this._keys.length; index++) {
  10739. var keyCode = this._keys[index];
  10740. var speed = this._computeLocalCameraSpeed();
  10741. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10742. this._localDirection.copyFromFloats(-speed, 0, 0);
  10743. }
  10744. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10745. this._localDirection.copyFromFloats(0, 0, speed);
  10746. }
  10747. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10748. this._localDirection.copyFromFloats(speed, 0, 0);
  10749. }
  10750. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10751. this._localDirection.copyFromFloats(0, 0, -speed);
  10752. }
  10753. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10754. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10755. this.cameraDirection.addInPlace(this._transformedDirection);
  10756. }
  10757. _super.prototype._checkInputs.call(this);
  10758. };
  10759. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10760. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10761. };
  10762. FreeCamera.prototype._updatePosition = function () {
  10763. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10764. this._collideWithWorld(this.cameraDirection);
  10765. }
  10766. else {
  10767. this.position.addInPlace(this.cameraDirection);
  10768. }
  10769. };
  10770. return FreeCamera;
  10771. })(BABYLON.TargetCamera);
  10772. BABYLON.FreeCamera = FreeCamera;
  10773. })(BABYLON || (BABYLON = {}));
  10774. var BABYLON;
  10775. (function (BABYLON) {
  10776. var FollowCamera = (function (_super) {
  10777. __extends(FollowCamera, _super);
  10778. function FollowCamera(name, position, scene) {
  10779. _super.call(this, name, position, scene);
  10780. this.radius = 12;
  10781. this.rotationOffset = 0;
  10782. this.heightOffset = 4;
  10783. this.cameraAcceleration = 0.05;
  10784. this.maxCameraSpeed = 20;
  10785. }
  10786. FollowCamera.prototype.getRadians = function (degrees) {
  10787. return degrees * Math.PI / 180;
  10788. };
  10789. FollowCamera.prototype.follow = function (cameraTarget) {
  10790. if (!cameraTarget)
  10791. return;
  10792. var yRotation;
  10793. if (cameraTarget.rotationQuaternion) {
  10794. var rotMatrix = new BABYLON.Matrix();
  10795. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10796. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10797. }
  10798. else {
  10799. yRotation = cameraTarget.rotation.y;
  10800. }
  10801. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10802. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10803. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10804. var dx = targetX - this.position.x;
  10805. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10806. var dz = (targetZ) - this.position.z;
  10807. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10808. var vy = dy * this.cameraAcceleration;
  10809. var vz = dz * this.cameraAcceleration * 2;
  10810. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10811. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10812. }
  10813. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10814. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10815. }
  10816. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10817. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10818. }
  10819. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10820. this.setTarget(cameraTarget.position);
  10821. };
  10822. FollowCamera.prototype._checkInputs = function () {
  10823. _super.prototype._checkInputs.call(this);
  10824. this.follow(this.target);
  10825. };
  10826. return FollowCamera;
  10827. })(BABYLON.TargetCamera);
  10828. BABYLON.FollowCamera = FollowCamera;
  10829. var ArcFollowCamera = (function (_super) {
  10830. __extends(ArcFollowCamera, _super);
  10831. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  10832. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10833. this.alpha = alpha;
  10834. this.beta = beta;
  10835. this.radius = radius;
  10836. this.target = target;
  10837. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  10838. this.follow();
  10839. }
  10840. ArcFollowCamera.prototype.follow = function () {
  10841. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  10842. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  10843. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  10844. this.position = this.target.position.add(this._cartesianCoordinates);
  10845. this.setTarget(this.target.position);
  10846. };
  10847. ArcFollowCamera.prototype._checkInputs = function () {
  10848. _super.prototype._checkInputs.call(this);
  10849. this.follow();
  10850. };
  10851. return ArcFollowCamera;
  10852. })(BABYLON.TargetCamera);
  10853. BABYLON.ArcFollowCamera = ArcFollowCamera;
  10854. })(BABYLON || (BABYLON = {}));
  10855. var BABYLON;
  10856. (function (BABYLON) {
  10857. // We're mainly based on the logic defined into the FreeCamera code
  10858. var TouchCamera = (function (_super) {
  10859. __extends(TouchCamera, _super);
  10860. function TouchCamera(name, position, scene) {
  10861. _super.call(this, name, position, scene);
  10862. this._offsetX = null;
  10863. this._offsetY = null;
  10864. this._pointerCount = 0;
  10865. this._pointerPressed = [];
  10866. this.angularSensibility = 200000.0;
  10867. this.moveSensibility = 500.0;
  10868. }
  10869. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10870. var _this = this;
  10871. var previousPosition;
  10872. if (this._attachedCanvas) {
  10873. return;
  10874. }
  10875. this._attachedCanvas = canvas;
  10876. if (this._onPointerDown === undefined) {
  10877. this._onPointerDown = function (evt) {
  10878. if (!noPreventDefault) {
  10879. evt.preventDefault();
  10880. }
  10881. _this._pointerPressed.push(evt.pointerId);
  10882. if (_this._pointerPressed.length !== 1) {
  10883. return;
  10884. }
  10885. previousPosition = {
  10886. x: evt.clientX,
  10887. y: evt.clientY
  10888. };
  10889. };
  10890. this._onPointerUp = function (evt) {
  10891. if (!noPreventDefault) {
  10892. evt.preventDefault();
  10893. }
  10894. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10895. if (index === -1) {
  10896. return;
  10897. }
  10898. _this._pointerPressed.splice(index, 1);
  10899. if (index != 0) {
  10900. return;
  10901. }
  10902. previousPosition = null;
  10903. _this._offsetX = null;
  10904. _this._offsetY = null;
  10905. };
  10906. this._onPointerMove = function (evt) {
  10907. if (!noPreventDefault) {
  10908. evt.preventDefault();
  10909. }
  10910. if (!previousPosition) {
  10911. return;
  10912. }
  10913. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10914. if (index != 0) {
  10915. return;
  10916. }
  10917. _this._offsetX = evt.clientX - previousPosition.x;
  10918. _this._offsetY = -(evt.clientY - previousPosition.y);
  10919. };
  10920. this._onLostFocus = function () {
  10921. _this._offsetX = null;
  10922. _this._offsetY = null;
  10923. };
  10924. }
  10925. canvas.addEventListener("pointerdown", this._onPointerDown);
  10926. canvas.addEventListener("pointerup", this._onPointerUp);
  10927. canvas.addEventListener("pointerout", this._onPointerUp);
  10928. canvas.addEventListener("pointermove", this._onPointerMove);
  10929. BABYLON.Tools.RegisterTopRootEvents([
  10930. { name: "blur", handler: this._onLostFocus }
  10931. ]);
  10932. };
  10933. TouchCamera.prototype.detachControl = function (canvas) {
  10934. if (this._attachedCanvas != canvas) {
  10935. return;
  10936. }
  10937. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10938. canvas.removeEventListener("pointerup", this._onPointerUp);
  10939. canvas.removeEventListener("pointerout", this._onPointerUp);
  10940. canvas.removeEventListener("pointermove", this._onPointerMove);
  10941. BABYLON.Tools.UnregisterTopRootEvents([
  10942. { name: "blur", handler: this._onLostFocus }
  10943. ]);
  10944. this._attachedCanvas = null;
  10945. };
  10946. TouchCamera.prototype._checkInputs = function () {
  10947. if (this._offsetX) {
  10948. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10949. if (this._pointerPressed.length > 1) {
  10950. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10951. }
  10952. else {
  10953. var speed = this._computeLocalCameraSpeed();
  10954. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10955. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10956. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10957. }
  10958. }
  10959. _super.prototype._checkInputs.call(this);
  10960. };
  10961. return TouchCamera;
  10962. })(BABYLON.FreeCamera);
  10963. BABYLON.TouchCamera = TouchCamera;
  10964. })(BABYLON || (BABYLON = {}));
  10965. var BABYLON;
  10966. (function (BABYLON) {
  10967. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10968. var ArcRotateCamera = (function (_super) {
  10969. __extends(ArcRotateCamera, _super);
  10970. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10971. var _this = this;
  10972. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10973. this.alpha = alpha;
  10974. this.beta = beta;
  10975. this.radius = radius;
  10976. this.target = target;
  10977. this.inertialAlphaOffset = 0;
  10978. this.inertialBetaOffset = 0;
  10979. this.inertialRadiusOffset = 0;
  10980. this.lowerAlphaLimit = null;
  10981. this.upperAlphaLimit = null;
  10982. this.lowerBetaLimit = 0.01;
  10983. this.upperBetaLimit = Math.PI;
  10984. this.lowerRadiusLimit = null;
  10985. this.upperRadiusLimit = null;
  10986. this.angularSensibilityX = 1000.0;
  10987. this.angularSensibilityY = 1000.0;
  10988. this.wheelPrecision = 3.0;
  10989. this.pinchPrecision = 2.0;
  10990. this.panningSensibility = 50.0;
  10991. this.inertialPanningX = 0;
  10992. this.inertialPanningY = 0;
  10993. this.keysUp = [38];
  10994. this.keysDown = [40];
  10995. this.keysLeft = [37];
  10996. this.keysRight = [39];
  10997. this.zoomOnFactor = 1;
  10998. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10999. this.pinchInwards = true;
  11000. this.allowUpsideDown = true;
  11001. this._keys = [];
  11002. this._viewMatrix = new BABYLON.Matrix();
  11003. this._isRightClick = false;
  11004. this._isCtrlPushed = false;
  11005. this.checkCollisions = false;
  11006. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  11007. this._collider = new BABYLON.Collider();
  11008. this._previousPosition = BABYLON.Vector3.Zero();
  11009. this._collisionVelocity = BABYLON.Vector3.Zero();
  11010. this._newPosition = BABYLON.Vector3.Zero();
  11011. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11012. if (collidedMesh === void 0) { collidedMesh = null; }
  11013. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  11014. newPosition.multiplyInPlace(_this._collider.radius);
  11015. }
  11016. if (!collidedMesh) {
  11017. _this._previousPosition.copyFrom(_this.position);
  11018. }
  11019. else {
  11020. _this.setPosition(_this.position);
  11021. if (_this.onCollide) {
  11022. _this.onCollide(collidedMesh);
  11023. }
  11024. }
  11025. // Recompute because of constraints
  11026. var cosa = Math.cos(_this.alpha);
  11027. var sina = Math.sin(_this.alpha);
  11028. var cosb = Math.cos(_this.beta);
  11029. var sinb = Math.sin(_this.beta);
  11030. var target = _this._getTargetPosition();
  11031. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  11032. _this.position.copyFrom(_this._newPosition);
  11033. var up = _this.upVector;
  11034. if (_this.allowUpsideDown && _this.beta < 0) {
  11035. var up = up.clone();
  11036. up = up.negate();
  11037. }
  11038. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  11039. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  11040. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  11041. _this._collisionTriggered = false;
  11042. };
  11043. if (!this.target) {
  11044. this.target = BABYLON.Vector3.Zero();
  11045. }
  11046. this.getViewMatrix();
  11047. }
  11048. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibility", {
  11049. //deprecated angularSensibility support
  11050. get: function () {
  11051. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11052. return Math.max(this.angularSensibilityX, this.angularSensibilityY);
  11053. },
  11054. //deprecated angularSensibility support
  11055. set: function (value) {
  11056. BABYLON.Tools.Warn("Warning: angularSensibility is deprecated, use angularSensibilityX and angularSensibilityY instead.");
  11057. this.angularSensibilityX = value;
  11058. this.angularSensibilityY = value;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. ArcRotateCamera.prototype._getTargetPosition = function () {
  11064. return this.target.position || this.target;
  11065. };
  11066. // Cache
  11067. ArcRotateCamera.prototype._initCache = function () {
  11068. _super.prototype._initCache.call(this);
  11069. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  11070. this._cache.alpha = undefined;
  11071. this._cache.beta = undefined;
  11072. this._cache.radius = undefined;
  11073. this._cache.targetScreenOffset = undefined;
  11074. };
  11075. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  11076. if (!ignoreParentClass) {
  11077. _super.prototype._updateCache.call(this);
  11078. }
  11079. this._cache.target.copyFrom(this._getTargetPosition());
  11080. this._cache.alpha = this.alpha;
  11081. this._cache.beta = this.beta;
  11082. this._cache.radius = this.radius;
  11083. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  11084. };
  11085. // Synchronized
  11086. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  11087. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  11088. return false;
  11089. return this._cache.target.equals(this._getTargetPosition())
  11090. && this._cache.alpha === this.alpha
  11091. && this._cache.beta === this.beta
  11092. && this._cache.radius === this.radius
  11093. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  11094. };
  11095. // Methods
  11096. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  11097. var _this = this;
  11098. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  11099. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  11100. var previousPinchDistance = 0;
  11101. var pointers = new BABYLON.SmartCollection();
  11102. if (this._attachedElement) {
  11103. return;
  11104. }
  11105. this._attachedElement = element;
  11106. var engine = this.getEngine();
  11107. if (this._onPointerDown === undefined) {
  11108. this._onPointerDown = function (evt) {
  11109. // Manage panning with right click
  11110. _this._isRightClick = evt.button === 2 ? true : false;
  11111. // manage pointers
  11112. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  11113. cacheSoloPointer = pointers.item(evt.pointerId);
  11114. if (!noPreventDefault) {
  11115. evt.preventDefault();
  11116. }
  11117. };
  11118. this._onPointerUp = function (evt) {
  11119. cacheSoloPointer = null;
  11120. previousPinchDistance = 0;
  11121. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  11122. //but emptying completly pointers collection is required to fix a bug on iPhone :
  11123. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  11124. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  11125. pointers.empty();
  11126. if (!noPreventDefault) {
  11127. evt.preventDefault();
  11128. }
  11129. };
  11130. this._onContextMenu = function (evt) {
  11131. evt.preventDefault();
  11132. };
  11133. this._onPointerMove = function (evt) {
  11134. if (!noPreventDefault) {
  11135. evt.preventDefault();
  11136. }
  11137. switch (pointers.count) {
  11138. case 1:
  11139. if ((_this._isCtrlPushed && useCtrlForPanning) || (!useCtrlForPanning && _this._isRightClick)) {
  11140. _this.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  11141. _this.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  11142. }
  11143. else {
  11144. var offsetX = evt.clientX - cacheSoloPointer.x;
  11145. var offsetY = evt.clientY - cacheSoloPointer.y;
  11146. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11147. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11148. }
  11149. cacheSoloPointer.x = evt.clientX;
  11150. cacheSoloPointer.y = evt.clientY;
  11151. break;
  11152. case 2:
  11153. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  11154. pointers.item(evt.pointerId).x = evt.clientX;
  11155. pointers.item(evt.pointerId).y = evt.clientY;
  11156. var direction = _this.pinchInwards ? 1 : -1;
  11157. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  11158. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  11159. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  11160. if (previousPinchDistance === 0) {
  11161. previousPinchDistance = pinchSquaredDistance;
  11162. return;
  11163. }
  11164. if (pinchSquaredDistance !== previousPinchDistance) {
  11165. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  11166. previousPinchDistance = pinchSquaredDistance;
  11167. }
  11168. break;
  11169. default:
  11170. if (pointers.item(evt.pointerId)) {
  11171. pointers.item(evt.pointerId).x = evt.clientX;
  11172. pointers.item(evt.pointerId).y = evt.clientY;
  11173. }
  11174. }
  11175. };
  11176. this._onMouseMove = function (evt) {
  11177. if (!engine.isPointerLock) {
  11178. return;
  11179. }
  11180. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11181. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11182. _this.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  11183. _this.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  11184. if (!noPreventDefault) {
  11185. evt.preventDefault();
  11186. }
  11187. };
  11188. this._wheel = function (event) {
  11189. var delta = 0;
  11190. if (event.wheelDelta) {
  11191. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  11192. }
  11193. else if (event.detail) {
  11194. delta = -event.detail / _this.wheelPrecision;
  11195. }
  11196. if (delta)
  11197. _this.inertialRadiusOffset += delta;
  11198. if (event.preventDefault) {
  11199. if (!noPreventDefault) {
  11200. event.preventDefault();
  11201. }
  11202. }
  11203. };
  11204. this._onKeyDown = function (evt) {
  11205. _this._isCtrlPushed = evt.ctrlKey;
  11206. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11207. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11208. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11209. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11210. var index = _this._keys.indexOf(evt.keyCode);
  11211. if (index === -1) {
  11212. _this._keys.push(evt.keyCode);
  11213. }
  11214. if (evt.preventDefault) {
  11215. if (!noPreventDefault) {
  11216. evt.preventDefault();
  11217. }
  11218. }
  11219. }
  11220. };
  11221. this._onKeyUp = function (evt) {
  11222. _this._isCtrlPushed = evt.ctrlKey;
  11223. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11224. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11225. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11226. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11227. var index = _this._keys.indexOf(evt.keyCode);
  11228. if (index >= 0) {
  11229. _this._keys.splice(index, 1);
  11230. }
  11231. if (evt.preventDefault) {
  11232. if (!noPreventDefault) {
  11233. evt.preventDefault();
  11234. }
  11235. }
  11236. }
  11237. };
  11238. this._onLostFocus = function () {
  11239. _this._keys = [];
  11240. pointers.empty();
  11241. previousPinchDistance = 0;
  11242. cacheSoloPointer = null;
  11243. };
  11244. this._onGestureStart = function (e) {
  11245. if (window.MSGesture === undefined) {
  11246. return;
  11247. }
  11248. if (!_this._MSGestureHandler) {
  11249. _this._MSGestureHandler = new MSGesture();
  11250. _this._MSGestureHandler.target = element;
  11251. }
  11252. _this._MSGestureHandler.addPointer(e.pointerId);
  11253. };
  11254. this._onGesture = function (e) {
  11255. _this.radius *= e.scale;
  11256. if (e.preventDefault) {
  11257. if (!noPreventDefault) {
  11258. e.stopPropagation();
  11259. e.preventDefault();
  11260. }
  11261. }
  11262. };
  11263. this._reset = function () {
  11264. _this._keys = [];
  11265. _this.inertialAlphaOffset = 0;
  11266. _this.inertialBetaOffset = 0;
  11267. _this.inertialRadiusOffset = 0;
  11268. pointers.empty();
  11269. previousPinchDistance = 0;
  11270. cacheSoloPointer = null;
  11271. };
  11272. }
  11273. if (!useCtrlForPanning) {
  11274. element.addEventListener("contextmenu", this._onContextMenu, false);
  11275. }
  11276. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  11277. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  11278. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  11279. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  11280. element.addEventListener("mousemove", this._onMouseMove, false);
  11281. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  11282. element.addEventListener("MSGestureChange", this._onGesture, false);
  11283. element.addEventListener('mousewheel', this._wheel, false);
  11284. element.addEventListener('DOMMouseScroll', this._wheel, false);
  11285. BABYLON.Tools.RegisterTopRootEvents([
  11286. { name: "keydown", handler: this._onKeyDown },
  11287. { name: "keyup", handler: this._onKeyUp },
  11288. { name: "blur", handler: this._onLostFocus }
  11289. ]);
  11290. };
  11291. ArcRotateCamera.prototype.detachControl = function (element) {
  11292. if (this._attachedElement !== element) {
  11293. return;
  11294. }
  11295. element.removeEventListener("contextmenu", this._onContextMenu);
  11296. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  11297. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  11298. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  11299. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  11300. element.removeEventListener("mousemove", this._onMouseMove);
  11301. element.removeEventListener("MSPointerDown", this._onGestureStart);
  11302. element.removeEventListener("MSGestureChange", this._onGesture);
  11303. element.removeEventListener('mousewheel', this._wheel);
  11304. element.removeEventListener('DOMMouseScroll', this._wheel);
  11305. BABYLON.Tools.UnregisterTopRootEvents([
  11306. { name: "keydown", handler: this._onKeyDown },
  11307. { name: "keyup", handler: this._onKeyUp },
  11308. { name: "blur", handler: this._onLostFocus }
  11309. ]);
  11310. this._MSGestureHandler = null;
  11311. this._attachedElement = null;
  11312. if (this._reset) {
  11313. this._reset();
  11314. }
  11315. };
  11316. ArcRotateCamera.prototype._checkInputs = function () {
  11317. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11318. if (this._collisionTriggered) {
  11319. return;
  11320. }
  11321. // Keyboard
  11322. for (var index = 0; index < this._keys.length; index++) {
  11323. var keyCode = this._keys[index];
  11324. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11325. this.inertialAlphaOffset -= 0.01;
  11326. }
  11327. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11328. this.inertialBetaOffset -= 0.01;
  11329. }
  11330. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11331. this.inertialAlphaOffset += 0.01;
  11332. }
  11333. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11334. this.inertialBetaOffset += 0.01;
  11335. }
  11336. }
  11337. // Inertia
  11338. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11339. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11340. this.beta += this.inertialBetaOffset;
  11341. this.radius -= this.inertialRadiusOffset;
  11342. this.inertialAlphaOffset *= this.inertia;
  11343. this.inertialBetaOffset *= this.inertia;
  11344. this.inertialRadiusOffset *= this.inertia;
  11345. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11346. this.inertialAlphaOffset = 0;
  11347. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11348. this.inertialBetaOffset = 0;
  11349. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11350. this.inertialRadiusOffset = 0;
  11351. }
  11352. // Panning inertia
  11353. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  11354. if (!this._localDirection) {
  11355. this._localDirection = BABYLON.Vector3.Zero();
  11356. this._transformedDirection = BABYLON.Vector3.Zero();
  11357. }
  11358. this.inertialPanningX *= this.inertia;
  11359. this.inertialPanningY *= this.inertia;
  11360. if (Math.abs(this.inertialPanningX) < BABYLON.Engine.Epsilon)
  11361. this.inertialPanningX = 0;
  11362. if (Math.abs(this.inertialPanningY) < BABYLON.Engine.Epsilon)
  11363. this.inertialPanningY = 0;
  11364. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, 0);
  11365. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  11366. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  11367. this.target.addInPlace(this._transformedDirection);
  11368. }
  11369. // Limits
  11370. this._checkLimits();
  11371. _super.prototype._checkInputs.call(this);
  11372. };
  11373. ArcRotateCamera.prototype._checkLimits = function () {
  11374. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11375. if (this.allowUpsideDown && this.beta > Math.PI) {
  11376. this.beta = this.beta - (2 * Math.PI);
  11377. }
  11378. }
  11379. else {
  11380. if (this.beta < this.lowerBetaLimit) {
  11381. this.beta = this.lowerBetaLimit;
  11382. }
  11383. }
  11384. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11385. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11386. this.beta = this.beta + (2 * Math.PI);
  11387. }
  11388. }
  11389. else {
  11390. if (this.beta > this.upperBetaLimit) {
  11391. this.beta = this.upperBetaLimit;
  11392. }
  11393. }
  11394. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11395. this.alpha = this.lowerAlphaLimit;
  11396. }
  11397. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11398. this.alpha = this.upperAlphaLimit;
  11399. }
  11400. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11401. this.radius = this.lowerRadiusLimit;
  11402. }
  11403. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11404. this.radius = this.upperRadiusLimit;
  11405. }
  11406. };
  11407. ArcRotateCamera.prototype.setPosition = function (position) {
  11408. var radiusv3 = position.subtract(this._getTargetPosition());
  11409. this.radius = radiusv3.length();
  11410. // Alpha
  11411. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11412. if (radiusv3.z < 0) {
  11413. this.alpha = 2 * Math.PI - this.alpha;
  11414. }
  11415. // Beta
  11416. this.beta = Math.acos(radiusv3.y / this.radius);
  11417. this._checkLimits();
  11418. };
  11419. ArcRotateCamera.prototype._getViewMatrix = function () {
  11420. // Compute
  11421. var cosa = Math.cos(this.alpha);
  11422. var sina = Math.sin(this.alpha);
  11423. var cosb = Math.cos(this.beta);
  11424. var sinb = Math.sin(this.beta);
  11425. var target = this._getTargetPosition();
  11426. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11427. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11428. this._collider.radius = this.collisionRadius;
  11429. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11430. this._collisionTriggered = true;
  11431. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11432. }
  11433. else {
  11434. this.position.copyFrom(this._newPosition);
  11435. var up = this.upVector;
  11436. if (this.allowUpsideDown && this.beta < 0) {
  11437. var up = up.clone();
  11438. up = up.negate();
  11439. }
  11440. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11441. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11442. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11443. }
  11444. return this._viewMatrix;
  11445. };
  11446. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  11447. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11448. meshes = meshes || this.getScene().meshes;
  11449. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11450. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11451. this.radius = distance * this.zoomOnFactor;
  11452. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  11453. };
  11454. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  11455. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  11456. var meshesOrMinMaxVector;
  11457. var distance;
  11458. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11459. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11460. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11461. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11462. }
  11463. else {
  11464. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11465. distance = meshesOrMinMaxVectorAndDistance.distance;
  11466. }
  11467. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11468. if (!doNotUpdateMaxZ) {
  11469. this.maxZ = distance * 2;
  11470. }
  11471. };
  11472. /**
  11473. * @override
  11474. * Override Camera.createRigCamera
  11475. */
  11476. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11477. switch (this.cameraRigMode) {
  11478. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11479. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11480. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11481. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11482. case BABYLON.Camera.RIG_MODE_VR:
  11483. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11484. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11485. }
  11486. };
  11487. /**
  11488. * @override
  11489. * Override Camera._updateRigCameras
  11490. */
  11491. ArcRotateCamera.prototype._updateRigCameras = function () {
  11492. switch (this.cameraRigMode) {
  11493. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11494. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11495. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11496. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11497. case BABYLON.Camera.RIG_MODE_VR:
  11498. var camLeft = this._rigCameras[0];
  11499. var camRight = this._rigCameras[1];
  11500. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11501. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11502. camLeft.beta = camRight.beta = this.beta;
  11503. camLeft.radius = camRight.radius = this.radius;
  11504. break;
  11505. }
  11506. _super.prototype._updateRigCameras.call(this);
  11507. };
  11508. return ArcRotateCamera;
  11509. })(BABYLON.TargetCamera);
  11510. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11511. })(BABYLON || (BABYLON = {}));
  11512. var BABYLON;
  11513. (function (BABYLON) {
  11514. // We're mainly based on the logic defined into the FreeCamera code
  11515. var DeviceOrientationCamera = (function (_super) {
  11516. __extends(DeviceOrientationCamera, _super);
  11517. function DeviceOrientationCamera(name, position, scene) {
  11518. var _this = this;
  11519. _super.call(this, name, position, scene);
  11520. this._offsetX = null;
  11521. this._offsetY = null;
  11522. this._orientationGamma = 0;
  11523. this._orientationBeta = 0;
  11524. this._initialOrientationGamma = 0;
  11525. this._initialOrientationBeta = 0;
  11526. this.angularSensibility = 10000.0;
  11527. this.moveSensibility = 50.0;
  11528. window.addEventListener("resize", function () {
  11529. _this._initialOrientationGamma = null;
  11530. }, false);
  11531. }
  11532. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11533. var _this = this;
  11534. if (this._attachedCanvas) {
  11535. return;
  11536. }
  11537. this._attachedCanvas = canvas;
  11538. if (!this._orientationChanged) {
  11539. this._orientationChanged = function (evt) {
  11540. if (!_this._initialOrientationGamma) {
  11541. _this._initialOrientationGamma = evt.gamma;
  11542. _this._initialOrientationBeta = evt.beta;
  11543. }
  11544. _this._orientationGamma = evt.gamma;
  11545. _this._orientationBeta = evt.beta;
  11546. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11547. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11548. };
  11549. }
  11550. window.addEventListener("deviceorientation", this._orientationChanged);
  11551. };
  11552. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11553. if (this._attachedCanvas != canvas) {
  11554. return;
  11555. }
  11556. window.removeEventListener("deviceorientation", this._orientationChanged);
  11557. this._attachedCanvas = null;
  11558. this._orientationGamma = 0;
  11559. this._orientationBeta = 0;
  11560. this._initialOrientationGamma = 0;
  11561. this._initialOrientationBeta = 0;
  11562. };
  11563. DeviceOrientationCamera.prototype._checkInputs = function () {
  11564. if (!this._offsetX) {
  11565. return;
  11566. }
  11567. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11568. var speed = this._computeLocalCameraSpeed();
  11569. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11570. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11571. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11572. _super.prototype._checkInputs.call(this);
  11573. };
  11574. return DeviceOrientationCamera;
  11575. })(BABYLON.FreeCamera);
  11576. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11577. })(BABYLON || (BABYLON = {}));
  11578. var BABYLON;
  11579. (function (BABYLON) {
  11580. var Gamepads = (function () {
  11581. function Gamepads(ongamedpadconnected) {
  11582. var _this = this;
  11583. this.babylonGamepads = [];
  11584. this.oneGamepadConnected = false;
  11585. this.isMonitoring = false;
  11586. this.gamepadEventSupported = 'GamepadEvent' in window;
  11587. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11588. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11589. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  11590. this._callbackGamepadConnected = ongamedpadconnected;
  11591. if (this.gamepadSupportAvailable) {
  11592. // Checking if the gamepad connected event is supported (like in Firefox)
  11593. if (this.gamepadEventSupported) {
  11594. window.addEventListener('gamepadconnected', function (evt) {
  11595. _this._onGamepadConnected(evt);
  11596. }, false);
  11597. window.addEventListener('gamepaddisconnected', function (evt) {
  11598. _this._onGamepadDisconnected(evt);
  11599. }, false);
  11600. }
  11601. else {
  11602. this._startMonitoringGamepads();
  11603. }
  11604. if (!this.oneGamepadConnected) {
  11605. this._insertGamepadDOMInstructions();
  11606. }
  11607. }
  11608. else {
  11609. this._insertGamepadDOMNotSupported();
  11610. }
  11611. }
  11612. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11613. Gamepads.gamepadDOMInfo = document.createElement("div");
  11614. var buttonAImage = document.createElement("img");
  11615. buttonAImage.src = this.buttonADataURL;
  11616. var spanMessage = document.createElement("span");
  11617. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11618. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11619. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11620. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11621. Gamepads.gamepadDOMInfo.style.width = "100%";
  11622. Gamepads.gamepadDOMInfo.style.height = "48px";
  11623. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11624. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11625. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11626. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11627. buttonAImage.style.position = "relative";
  11628. buttonAImage.style.bottom = "8px";
  11629. spanMessage.style.position = "relative";
  11630. spanMessage.style.fontSize = "32px";
  11631. spanMessage.style.bottom = "32px";
  11632. spanMessage.style.color = "green";
  11633. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11634. };
  11635. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11636. Gamepads.gamepadDOMInfo = document.createElement("div");
  11637. var spanMessage = document.createElement("span");
  11638. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11639. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11640. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11641. Gamepads.gamepadDOMInfo.style.width = "100%";
  11642. Gamepads.gamepadDOMInfo.style.height = "40px";
  11643. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11644. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11645. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11646. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11647. spanMessage.style.position = "relative";
  11648. spanMessage.style.fontSize = "32px";
  11649. spanMessage.style.color = "red";
  11650. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11651. };
  11652. Gamepads.prototype.dispose = function () {
  11653. if (Gamepads.gamepadDOMInfo) {
  11654. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11655. }
  11656. };
  11657. Gamepads.prototype._onGamepadConnected = function (evt) {
  11658. var newGamepad = this._addNewGamepad(evt.gamepad);
  11659. if (this._callbackGamepadConnected)
  11660. this._callbackGamepadConnected(newGamepad);
  11661. this._startMonitoringGamepads();
  11662. };
  11663. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11664. if (!this.oneGamepadConnected) {
  11665. this.oneGamepadConnected = true;
  11666. if (Gamepads.gamepadDOMInfo) {
  11667. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11668. Gamepads.gamepadDOMInfo = null;
  11669. }
  11670. }
  11671. var newGamepad;
  11672. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11673. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11674. }
  11675. else {
  11676. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11677. }
  11678. this.babylonGamepads.push(newGamepad);
  11679. return newGamepad;
  11680. };
  11681. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11682. // Remove the gamepad from the list of gamepads to monitor.
  11683. for (var i in this.babylonGamepads) {
  11684. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11685. this.babylonGamepads.splice(i, 1);
  11686. break;
  11687. }
  11688. }
  11689. // If no gamepads are left, stop the polling loop.
  11690. if (this.babylonGamepads.length == 0) {
  11691. this._stopMonitoringGamepads();
  11692. }
  11693. };
  11694. Gamepads.prototype._startMonitoringGamepads = function () {
  11695. if (!this.isMonitoring) {
  11696. this.isMonitoring = true;
  11697. this._checkGamepadsStatus();
  11698. }
  11699. };
  11700. Gamepads.prototype._stopMonitoringGamepads = function () {
  11701. this.isMonitoring = false;
  11702. };
  11703. Gamepads.prototype._checkGamepadsStatus = function () {
  11704. var _this = this;
  11705. // updating gamepad objects
  11706. this._updateGamepadObjects();
  11707. for (var i in this.babylonGamepads) {
  11708. this.babylonGamepads[i].update();
  11709. }
  11710. if (this.isMonitoring) {
  11711. if (window.requestAnimationFrame) {
  11712. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11713. }
  11714. else if (window.mozRequestAnimationFrame) {
  11715. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11716. }
  11717. else if (window.webkitRequestAnimationFrame) {
  11718. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11719. }
  11720. }
  11721. };
  11722. // This function is called only on Chrome, which does not yet support
  11723. // connection/disconnection events, but requires you to monitor
  11724. // an array for changes.
  11725. Gamepads.prototype._updateGamepadObjects = function () {
  11726. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11727. for (var i = 0; i < gamepads.length; i++) {
  11728. if (gamepads[i]) {
  11729. if (!(gamepads[i].index in this.babylonGamepads)) {
  11730. var newGamepad = this._addNewGamepad(gamepads[i]);
  11731. if (this._callbackGamepadConnected) {
  11732. this._callbackGamepadConnected(newGamepad);
  11733. }
  11734. }
  11735. else {
  11736. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11737. }
  11738. }
  11739. }
  11740. };
  11741. return Gamepads;
  11742. })();
  11743. BABYLON.Gamepads = Gamepads;
  11744. var StickValues = (function () {
  11745. function StickValues(x, y) {
  11746. this.x = x;
  11747. this.y = y;
  11748. }
  11749. return StickValues;
  11750. })();
  11751. BABYLON.StickValues = StickValues;
  11752. var Gamepad = (function () {
  11753. function Gamepad(id, index, browserGamepad) {
  11754. this.id = id;
  11755. this.index = index;
  11756. this.browserGamepad = browserGamepad;
  11757. if (this.browserGamepad.axes.length >= 2) {
  11758. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11759. }
  11760. if (this.browserGamepad.axes.length >= 4) {
  11761. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11762. }
  11763. }
  11764. Gamepad.prototype.onleftstickchanged = function (callback) {
  11765. this._onleftstickchanged = callback;
  11766. };
  11767. Gamepad.prototype.onrightstickchanged = function (callback) {
  11768. this._onrightstickchanged = callback;
  11769. };
  11770. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11771. get: function () {
  11772. return this._leftStick;
  11773. },
  11774. set: function (newValues) {
  11775. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11776. this._onleftstickchanged(newValues);
  11777. }
  11778. this._leftStick = newValues;
  11779. },
  11780. enumerable: true,
  11781. configurable: true
  11782. });
  11783. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11784. get: function () {
  11785. return this._rightStick;
  11786. },
  11787. set: function (newValues) {
  11788. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11789. this._onrightstickchanged(newValues);
  11790. }
  11791. this._rightStick = newValues;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Gamepad.prototype.update = function () {
  11797. if (this._leftStick) {
  11798. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11799. }
  11800. if (this._rightStick) {
  11801. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11802. }
  11803. };
  11804. return Gamepad;
  11805. })();
  11806. BABYLON.Gamepad = Gamepad;
  11807. var GenericPad = (function (_super) {
  11808. __extends(GenericPad, _super);
  11809. function GenericPad(id, index, gamepad) {
  11810. _super.call(this, id, index, gamepad);
  11811. this.id = id;
  11812. this.index = index;
  11813. this.gamepad = gamepad;
  11814. this._buttons = new Array(gamepad.buttons.length);
  11815. }
  11816. GenericPad.prototype.onbuttondown = function (callback) {
  11817. this._onbuttondown = callback;
  11818. };
  11819. GenericPad.prototype.onbuttonup = function (callback) {
  11820. this._onbuttonup = callback;
  11821. };
  11822. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11823. if (newValue !== currentValue) {
  11824. if (this._onbuttondown && newValue === 1) {
  11825. this._onbuttondown(buttonIndex);
  11826. }
  11827. if (this._onbuttonup && newValue === 0) {
  11828. this._onbuttonup(buttonIndex);
  11829. }
  11830. }
  11831. return newValue;
  11832. };
  11833. GenericPad.prototype.update = function () {
  11834. _super.prototype.update.call(this);
  11835. for (var index = 0; index < this._buttons.length; index++) {
  11836. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11837. }
  11838. };
  11839. return GenericPad;
  11840. })(Gamepad);
  11841. BABYLON.GenericPad = GenericPad;
  11842. (function (Xbox360Button) {
  11843. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11844. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11845. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11846. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11847. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11848. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11849. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11850. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11851. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11852. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11853. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11854. var Xbox360Button = BABYLON.Xbox360Button;
  11855. (function (Xbox360Dpad) {
  11856. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11857. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11858. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11859. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11860. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11861. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11862. var Xbox360Pad = (function (_super) {
  11863. __extends(Xbox360Pad, _super);
  11864. function Xbox360Pad() {
  11865. _super.apply(this, arguments);
  11866. this._leftTrigger = 0;
  11867. this._rightTrigger = 0;
  11868. this._buttonA = 0;
  11869. this._buttonB = 0;
  11870. this._buttonX = 0;
  11871. this._buttonY = 0;
  11872. this._buttonBack = 0;
  11873. this._buttonStart = 0;
  11874. this._buttonLB = 0;
  11875. this._buttonRB = 0;
  11876. this._buttonLeftStick = 0;
  11877. this._buttonRightStick = 0;
  11878. this._dPadUp = 0;
  11879. this._dPadDown = 0;
  11880. this._dPadLeft = 0;
  11881. this._dPadRight = 0;
  11882. }
  11883. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11884. this._onlefttriggerchanged = callback;
  11885. };
  11886. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11887. this._onrighttriggerchanged = callback;
  11888. };
  11889. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11890. get: function () {
  11891. return this._leftTrigger;
  11892. },
  11893. set: function (newValue) {
  11894. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11895. this._onlefttriggerchanged(newValue);
  11896. }
  11897. this._leftTrigger = newValue;
  11898. },
  11899. enumerable: true,
  11900. configurable: true
  11901. });
  11902. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11903. get: function () {
  11904. return this._rightTrigger;
  11905. },
  11906. set: function (newValue) {
  11907. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11908. this._onrighttriggerchanged(newValue);
  11909. }
  11910. this._rightTrigger = newValue;
  11911. },
  11912. enumerable: true,
  11913. configurable: true
  11914. });
  11915. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11916. this._onbuttondown = callback;
  11917. };
  11918. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11919. this._onbuttonup = callback;
  11920. };
  11921. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11922. this._ondpaddown = callback;
  11923. };
  11924. Xbox360Pad.prototype.ondpadup = function (callback) {
  11925. this._ondpadup = callback;
  11926. };
  11927. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11928. if (newValue !== currentValue) {
  11929. if (this._onbuttondown && newValue === 1) {
  11930. this._onbuttondown(buttonType);
  11931. }
  11932. if (this._onbuttonup && newValue === 0) {
  11933. this._onbuttonup(buttonType);
  11934. }
  11935. }
  11936. return newValue;
  11937. };
  11938. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11939. if (newValue !== currentValue) {
  11940. if (this._ondpaddown && newValue === 1) {
  11941. this._ondpaddown(buttonType);
  11942. }
  11943. if (this._ondpadup && newValue === 0) {
  11944. this._ondpadup(buttonType);
  11945. }
  11946. }
  11947. return newValue;
  11948. };
  11949. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11950. get: function () {
  11951. return this._buttonA;
  11952. },
  11953. set: function (value) {
  11954. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11955. },
  11956. enumerable: true,
  11957. configurable: true
  11958. });
  11959. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11960. get: function () {
  11961. return this._buttonB;
  11962. },
  11963. set: function (value) {
  11964. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11970. get: function () {
  11971. return this._buttonX;
  11972. },
  11973. set: function (value) {
  11974. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11980. get: function () {
  11981. return this._buttonY;
  11982. },
  11983. set: function (value) {
  11984. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11990. get: function () {
  11991. return this._buttonStart;
  11992. },
  11993. set: function (value) {
  11994. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  12000. get: function () {
  12001. return this._buttonBack;
  12002. },
  12003. set: function (value) {
  12004. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  12010. get: function () {
  12011. return this._buttonLB;
  12012. },
  12013. set: function (value) {
  12014. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  12020. get: function () {
  12021. return this._buttonRB;
  12022. },
  12023. set: function (value) {
  12024. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  12030. get: function () {
  12031. return this._buttonLeftStick;
  12032. },
  12033. set: function (value) {
  12034. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  12040. get: function () {
  12041. return this._buttonRightStick;
  12042. },
  12043. set: function (value) {
  12044. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  12045. },
  12046. enumerable: true,
  12047. configurable: true
  12048. });
  12049. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  12050. get: function () {
  12051. return this._dPadUp;
  12052. },
  12053. set: function (value) {
  12054. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  12060. get: function () {
  12061. return this._dPadDown;
  12062. },
  12063. set: function (value) {
  12064. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  12065. },
  12066. enumerable: true,
  12067. configurable: true
  12068. });
  12069. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  12070. get: function () {
  12071. return this._dPadLeft;
  12072. },
  12073. set: function (value) {
  12074. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  12075. },
  12076. enumerable: true,
  12077. configurable: true
  12078. });
  12079. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  12080. get: function () {
  12081. return this._dPadRight;
  12082. },
  12083. set: function (value) {
  12084. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  12085. },
  12086. enumerable: true,
  12087. configurable: true
  12088. });
  12089. Xbox360Pad.prototype.update = function () {
  12090. _super.prototype.update.call(this);
  12091. this.buttonA = this.browserGamepad.buttons[0].value;
  12092. this.buttonB = this.browserGamepad.buttons[1].value;
  12093. this.buttonX = this.browserGamepad.buttons[2].value;
  12094. this.buttonY = this.browserGamepad.buttons[3].value;
  12095. this.buttonLB = this.browserGamepad.buttons[4].value;
  12096. this.buttonRB = this.browserGamepad.buttons[5].value;
  12097. this.leftTrigger = this.browserGamepad.buttons[6].value;
  12098. this.rightTrigger = this.browserGamepad.buttons[7].value;
  12099. this.buttonBack = this.browserGamepad.buttons[8].value;
  12100. this.buttonStart = this.browserGamepad.buttons[9].value;
  12101. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  12102. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  12103. this.dPadUp = this.browserGamepad.buttons[12].value;
  12104. this.dPadDown = this.browserGamepad.buttons[13].value;
  12105. this.dPadLeft = this.browserGamepad.buttons[14].value;
  12106. this.dPadRight = this.browserGamepad.buttons[15].value;
  12107. };
  12108. return Xbox360Pad;
  12109. })(Gamepad);
  12110. BABYLON.Xbox360Pad = Xbox360Pad;
  12111. })(BABYLON || (BABYLON = {}));
  12112. var BABYLON;
  12113. (function (BABYLON) {
  12114. // We're mainly based on the logic defined into the FreeCamera code
  12115. var GamepadCamera = (function (_super) {
  12116. __extends(GamepadCamera, _super);
  12117. function GamepadCamera(name, position, scene) {
  12118. var _this = this;
  12119. _super.call(this, name, position, scene);
  12120. this.angularSensibility = 200;
  12121. this.moveSensibility = 75;
  12122. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12123. }
  12124. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  12125. // Only the first gamepad can control the camera
  12126. if (gamepad.index === 0) {
  12127. this._gamepad = gamepad;
  12128. }
  12129. };
  12130. GamepadCamera.prototype._checkInputs = function () {
  12131. if (this._gamepad) {
  12132. var LSValues = this._gamepad.leftStick;
  12133. var normalizedLX = LSValues.x / this.moveSensibility;
  12134. var normalizedLY = LSValues.y / this.moveSensibility;
  12135. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12136. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12137. var RSValues = this._gamepad.rightStick;
  12138. var normalizedRX = RSValues.x / this.angularSensibility;
  12139. var normalizedRY = RSValues.y / this.angularSensibility;
  12140. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12141. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12142. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  12143. var speed = this._computeLocalCameraSpeed() * 50.0;
  12144. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12145. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  12146. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12147. }
  12148. _super.prototype._checkInputs.call(this);
  12149. };
  12150. GamepadCamera.prototype.dispose = function () {
  12151. this._gamepads.dispose();
  12152. _super.prototype.dispose.call(this);
  12153. };
  12154. return GamepadCamera;
  12155. })(BABYLON.FreeCamera);
  12156. BABYLON.GamepadCamera = GamepadCamera;
  12157. })(BABYLON || (BABYLON = {}));
  12158. var BABYLON;
  12159. (function (BABYLON) {
  12160. var RenderingManager = (function () {
  12161. function RenderingManager(scene) {
  12162. this._renderingGroups = new Array();
  12163. this._scene = scene;
  12164. }
  12165. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12166. if (this._scene._activeParticleSystems.length === 0) {
  12167. return;
  12168. }
  12169. // Particles
  12170. var beforeParticlesDate = BABYLON.Tools.Now;
  12171. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12172. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12173. if (particleSystem.renderingGroupId !== index) {
  12174. continue;
  12175. }
  12176. this._clearDepthBuffer();
  12177. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12178. this._scene._activeParticles += particleSystem.render();
  12179. }
  12180. }
  12181. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12182. };
  12183. RenderingManager.prototype._renderSprites = function (index) {
  12184. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12185. return;
  12186. }
  12187. // Sprites
  12188. var beforeSpritessDate = BABYLON.Tools.Now;
  12189. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12190. var spriteManager = this._scene.spriteManagers[id];
  12191. if (spriteManager.renderingGroupId === index) {
  12192. this._clearDepthBuffer();
  12193. spriteManager.render();
  12194. }
  12195. }
  12196. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12197. };
  12198. RenderingManager.prototype._clearDepthBuffer = function () {
  12199. if (this._depthBufferAlreadyCleaned) {
  12200. return;
  12201. }
  12202. this._scene.getEngine().clear(0, false, true);
  12203. this._depthBufferAlreadyCleaned = true;
  12204. };
  12205. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12206. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12207. this._depthBufferAlreadyCleaned = false;
  12208. var renderingGroup = this._renderingGroups[index];
  12209. var needToStepBack = false;
  12210. if (renderingGroup) {
  12211. this._clearDepthBuffer();
  12212. if (!renderingGroup.render(customRenderFunction)) {
  12213. this._renderingGroups.splice(index, 1);
  12214. needToStepBack = true;
  12215. }
  12216. }
  12217. if (renderSprites) {
  12218. this._renderSprites(index);
  12219. }
  12220. if (renderParticles) {
  12221. this._renderParticles(index, activeMeshes);
  12222. }
  12223. if (needToStepBack) {
  12224. index--;
  12225. }
  12226. }
  12227. };
  12228. RenderingManager.prototype.reset = function () {
  12229. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  12230. if (renderingGroup) {
  12231. renderingGroup.prepare();
  12232. }
  12233. });
  12234. };
  12235. RenderingManager.prototype.dispatch = function (subMesh) {
  12236. var mesh = subMesh.getMesh();
  12237. var renderingGroupId = mesh.renderingGroupId || 0;
  12238. if (!this._renderingGroups[renderingGroupId]) {
  12239. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12240. }
  12241. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12242. };
  12243. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12244. return RenderingManager;
  12245. })();
  12246. BABYLON.RenderingManager = RenderingManager;
  12247. })(BABYLON || (BABYLON = {}));
  12248. var BABYLON;
  12249. (function (BABYLON) {
  12250. var RenderingGroup = (function () {
  12251. function RenderingGroup(index, scene) {
  12252. this.index = index;
  12253. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12254. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12255. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12256. this._scene = scene;
  12257. }
  12258. RenderingGroup.prototype.render = function (customRenderFunction) {
  12259. if (customRenderFunction) {
  12260. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12261. return true;
  12262. }
  12263. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12264. return false;
  12265. }
  12266. var engine = this._scene.getEngine();
  12267. // Opaque
  12268. var subIndex;
  12269. var submesh;
  12270. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12271. submesh = this._opaqueSubMeshes.data[subIndex];
  12272. submesh.render(false);
  12273. }
  12274. // Alpha test
  12275. engine.setAlphaTesting(true);
  12276. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12277. submesh = this._alphaTestSubMeshes.data[subIndex];
  12278. submesh.render(false);
  12279. }
  12280. engine.setAlphaTesting(false);
  12281. // Transparent
  12282. if (this._transparentSubMeshes.length) {
  12283. // Sorting
  12284. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12285. submesh = this._transparentSubMeshes.data[subIndex];
  12286. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12287. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  12288. }
  12289. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12290. sortedArray.sort(function (a, b) {
  12291. // Alpha index first
  12292. if (a._alphaIndex > b._alphaIndex) {
  12293. return 1;
  12294. }
  12295. if (a._alphaIndex < b._alphaIndex) {
  12296. return -1;
  12297. }
  12298. // Then distance to camera
  12299. if (a._distanceToCamera < b._distanceToCamera) {
  12300. return 1;
  12301. }
  12302. if (a._distanceToCamera > b._distanceToCamera) {
  12303. return -1;
  12304. }
  12305. return 0;
  12306. });
  12307. // Rendering
  12308. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12309. submesh = sortedArray[subIndex];
  12310. submesh.render(true);
  12311. }
  12312. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12313. }
  12314. return true;
  12315. };
  12316. RenderingGroup.prototype.prepare = function () {
  12317. this._opaqueSubMeshes.reset();
  12318. this._transparentSubMeshes.reset();
  12319. this._alphaTestSubMeshes.reset();
  12320. };
  12321. RenderingGroup.prototype.dispatch = function (subMesh) {
  12322. var material = subMesh.getMaterial();
  12323. var mesh = subMesh.getMesh();
  12324. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12325. this._transparentSubMeshes.push(subMesh);
  12326. }
  12327. else if (material.needAlphaTesting()) {
  12328. this._alphaTestSubMeshes.push(subMesh);
  12329. }
  12330. else {
  12331. this._opaqueSubMeshes.push(subMesh); // Opaque
  12332. }
  12333. };
  12334. return RenderingGroup;
  12335. })();
  12336. BABYLON.RenderingGroup = RenderingGroup;
  12337. })(BABYLON || (BABYLON = {}));
  12338. var BABYLON;
  12339. (function (BABYLON) {
  12340. /**
  12341. * Represents a scene to be rendered by the engine.
  12342. * @see http://doc.babylonjs.com/page.php?p=21911
  12343. */
  12344. var Scene = (function () {
  12345. /**
  12346. * @constructor
  12347. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12348. */
  12349. function Scene(engine) {
  12350. // Members
  12351. this.autoClear = true;
  12352. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12353. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12354. this.forceWireframe = false;
  12355. this.forcePointsCloud = false;
  12356. this.forceShowBoundingBoxes = false;
  12357. this.animationsEnabled = true;
  12358. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  12359. // Fog
  12360. /**
  12361. * is fog enabled on this scene.
  12362. * @type {boolean}
  12363. */
  12364. this.fogEnabled = true;
  12365. this.fogMode = Scene.FOGMODE_NONE;
  12366. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12367. this.fogDensity = 0.1;
  12368. this.fogStart = 0;
  12369. this.fogEnd = 1000.0;
  12370. // Lights
  12371. /**
  12372. * is shadow enabled on this scene.
  12373. * @type {boolean}
  12374. */
  12375. this.shadowsEnabled = true;
  12376. /**
  12377. * is light enabled on this scene.
  12378. * @type {boolean}
  12379. */
  12380. this.lightsEnabled = true;
  12381. /**
  12382. * All of the lights added to this scene.
  12383. * @see BABYLON.Light
  12384. * @type {BABYLON.Light[]}
  12385. */
  12386. this.lights = new Array();
  12387. // Cameras
  12388. /**
  12389. * All of the cameras added to this scene.
  12390. * @see BABYLON.Camera
  12391. * @type {BABYLON.Camera[]}
  12392. */
  12393. this.cameras = new Array();
  12394. this.activeCameras = new Array();
  12395. // Meshes
  12396. /**
  12397. * All of the (abstract) meshes added to this scene.
  12398. * @see BABYLON.AbstractMesh
  12399. * @type {BABYLON.AbstractMesh[]}
  12400. */
  12401. this.meshes = new Array();
  12402. // Geometries
  12403. this._geometries = new Array();
  12404. this.materials = new Array();
  12405. this.multiMaterials = new Array();
  12406. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12407. // Textures
  12408. this.texturesEnabled = true;
  12409. this.textures = new Array();
  12410. // Particles
  12411. this.particlesEnabled = true;
  12412. this.particleSystems = new Array();
  12413. // Sprites
  12414. this.spritesEnabled = true;
  12415. this.spriteManagers = new Array();
  12416. // Layers
  12417. this.layers = new Array();
  12418. // Skeletons
  12419. this.skeletonsEnabled = true;
  12420. this.skeletons = new Array();
  12421. // Lens flares
  12422. this.lensFlaresEnabled = true;
  12423. this.lensFlareSystems = new Array();
  12424. // Collisions
  12425. this.collisionsEnabled = true;
  12426. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12427. // Postprocesses
  12428. this.postProcessesEnabled = true;
  12429. // Customs render targets
  12430. this.renderTargetsEnabled = true;
  12431. this.dumpNextRenderTargets = false;
  12432. this.customRenderTargets = new Array();
  12433. // Imported meshes
  12434. this.importedMeshesFiles = new Array();
  12435. this._actionManagers = new Array();
  12436. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12437. // Procedural textures
  12438. this.proceduralTexturesEnabled = true;
  12439. this._proceduralTextures = new Array();
  12440. this.soundTracks = new Array();
  12441. this._audioEnabled = true;
  12442. this._headphone = false;
  12443. this._totalVertices = 0;
  12444. this._activeIndices = 0;
  12445. this._activeParticles = 0;
  12446. this._lastFrameDuration = 0;
  12447. this._evaluateActiveMeshesDuration = 0;
  12448. this._renderTargetsDuration = 0;
  12449. this._particlesDuration = 0;
  12450. this._renderDuration = 0;
  12451. this._spritesDuration = 0;
  12452. this._animationRatio = 0;
  12453. this._renderId = 0;
  12454. this._executeWhenReadyTimeoutId = -1;
  12455. this._toBeDisposed = new BABYLON.SmartArray(256);
  12456. this._onReadyCallbacks = new Array();
  12457. this._pendingData = []; //ANY
  12458. this._onBeforeRenderCallbacks = new Array();
  12459. this._onAfterRenderCallbacks = new Array();
  12460. this._activeMeshes = new BABYLON.SmartArray(256);
  12461. this._processedMaterials = new BABYLON.SmartArray(256);
  12462. this._renderTargets = new BABYLON.SmartArray(256);
  12463. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12464. this._activeSkeletons = new BABYLON.SmartArray(32);
  12465. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  12466. this._activeBones = 0;
  12467. this._activeAnimatables = new Array();
  12468. this._transformMatrix = BABYLON.Matrix.Zero();
  12469. this._edgesRenderers = new BABYLON.SmartArray(16);
  12470. this._uniqueIdCounter = 0;
  12471. this._engine = engine;
  12472. engine.scenes.push(this);
  12473. this._renderingManager = new BABYLON.RenderingManager(this);
  12474. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12475. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12476. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12477. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12478. this.attachControl();
  12479. this._debugLayer = new BABYLON.DebugLayer(this);
  12480. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12481. //simplification queue
  12482. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12483. //collision coordinator initialization. For now legacy per default.
  12484. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12485. }
  12486. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12487. get: function () {
  12488. return Scene._FOGMODE_NONE;
  12489. },
  12490. enumerable: true,
  12491. configurable: true
  12492. });
  12493. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12494. get: function () {
  12495. return Scene._FOGMODE_EXP;
  12496. },
  12497. enumerable: true,
  12498. configurable: true
  12499. });
  12500. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12501. get: function () {
  12502. return Scene._FOGMODE_EXP2;
  12503. },
  12504. enumerable: true,
  12505. configurable: true
  12506. });
  12507. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12508. get: function () {
  12509. return Scene._FOGMODE_LINEAR;
  12510. },
  12511. enumerable: true,
  12512. configurable: true
  12513. });
  12514. Object.defineProperty(Scene.prototype, "debugLayer", {
  12515. // Properties
  12516. get: function () {
  12517. return this._debugLayer;
  12518. },
  12519. enumerable: true,
  12520. configurable: true
  12521. });
  12522. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12523. get: function () {
  12524. return this._workerCollisions;
  12525. },
  12526. set: function (enabled) {
  12527. enabled = (enabled && !!Worker);
  12528. this._workerCollisions = enabled;
  12529. if (this.collisionCoordinator) {
  12530. this.collisionCoordinator.destroy();
  12531. }
  12532. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12533. this.collisionCoordinator.init(this);
  12534. },
  12535. enumerable: true,
  12536. configurable: true
  12537. });
  12538. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  12539. get: function () {
  12540. return this._selectionOctree;
  12541. },
  12542. enumerable: true,
  12543. configurable: true
  12544. });
  12545. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12546. /**
  12547. * The mesh that is currently under the pointer.
  12548. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12549. */
  12550. get: function () {
  12551. return this._meshUnderPointer;
  12552. },
  12553. enumerable: true,
  12554. configurable: true
  12555. });
  12556. Object.defineProperty(Scene.prototype, "pointerX", {
  12557. /**
  12558. * Current on-screen X position of the pointer
  12559. * @return {number} X position of the pointer
  12560. */
  12561. get: function () {
  12562. return this._pointerX;
  12563. },
  12564. enumerable: true,
  12565. configurable: true
  12566. });
  12567. Object.defineProperty(Scene.prototype, "pointerY", {
  12568. /**
  12569. * Current on-screen Y position of the pointer
  12570. * @return {number} Y position of the pointer
  12571. */
  12572. get: function () {
  12573. return this._pointerY;
  12574. },
  12575. enumerable: true,
  12576. configurable: true
  12577. });
  12578. Scene.prototype.getCachedMaterial = function () {
  12579. return this._cachedMaterial;
  12580. };
  12581. Scene.prototype.getBoundingBoxRenderer = function () {
  12582. return this._boundingBoxRenderer;
  12583. };
  12584. Scene.prototype.getOutlineRenderer = function () {
  12585. return this._outlineRenderer;
  12586. };
  12587. Scene.prototype.getEngine = function () {
  12588. return this._engine;
  12589. };
  12590. Scene.prototype.getTotalVertices = function () {
  12591. return this._totalVertices;
  12592. };
  12593. Scene.prototype.getActiveIndices = function () {
  12594. return this._activeIndices;
  12595. };
  12596. Scene.prototype.getActiveParticles = function () {
  12597. return this._activeParticles;
  12598. };
  12599. Scene.prototype.getActiveBones = function () {
  12600. return this._activeBones;
  12601. };
  12602. // Stats
  12603. Scene.prototype.getLastFrameDuration = function () {
  12604. return this._lastFrameDuration;
  12605. };
  12606. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12607. return this._evaluateActiveMeshesDuration;
  12608. };
  12609. Scene.prototype.getActiveMeshes = function () {
  12610. return this._activeMeshes;
  12611. };
  12612. Scene.prototype.getRenderTargetsDuration = function () {
  12613. return this._renderTargetsDuration;
  12614. };
  12615. Scene.prototype.getRenderDuration = function () {
  12616. return this._renderDuration;
  12617. };
  12618. Scene.prototype.getParticlesDuration = function () {
  12619. return this._particlesDuration;
  12620. };
  12621. Scene.prototype.getSpritesDuration = function () {
  12622. return this._spritesDuration;
  12623. };
  12624. Scene.prototype.getAnimationRatio = function () {
  12625. return this._animationRatio;
  12626. };
  12627. Scene.prototype.getRenderId = function () {
  12628. return this._renderId;
  12629. };
  12630. Scene.prototype.incrementRenderId = function () {
  12631. this._renderId++;
  12632. };
  12633. Scene.prototype._updatePointerPosition = function (evt) {
  12634. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12635. this._pointerX = evt.clientX - canvasRect.left;
  12636. this._pointerY = evt.clientY - canvasRect.top;
  12637. if (this.cameraToUseForPointers) {
  12638. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12639. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12640. }
  12641. };
  12642. // Pointers handling
  12643. Scene.prototype.attachControl = function () {
  12644. var _this = this;
  12645. this._onPointerMove = function (evt) {
  12646. var canvas = _this._engine.getRenderingCanvas();
  12647. _this._updatePointerPosition(evt);
  12648. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady(); }, false, _this.cameraToUseForPointers);
  12649. if (pickResult.hit) {
  12650. _this._meshUnderPointer = pickResult.pickedMesh;
  12651. _this.setPointerOverMesh(pickResult.pickedMesh);
  12652. if (_this._meshUnderPointer.actionManager && _this._meshUnderPointer.actionManager.hasPointerTriggers) {
  12653. canvas.style.cursor = "pointer";
  12654. }
  12655. else {
  12656. canvas.style.cursor = "";
  12657. }
  12658. }
  12659. else {
  12660. _this.setPointerOverMesh(null);
  12661. canvas.style.cursor = "";
  12662. _this._meshUnderPointer = null;
  12663. }
  12664. };
  12665. this._onPointerDown = function (evt) {
  12666. var predicate = null;
  12667. if (!_this.onPointerDown) {
  12668. predicate = function (mesh) {
  12669. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12670. };
  12671. }
  12672. _this._updatePointerPosition(evt);
  12673. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12674. if (pickResult.hit) {
  12675. if (pickResult.pickedMesh.actionManager) {
  12676. switch (evt.button) {
  12677. case 0:
  12678. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12679. break;
  12680. case 1:
  12681. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12682. break;
  12683. case 2:
  12684. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12685. break;
  12686. }
  12687. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12688. }
  12689. }
  12690. if (_this.onPointerDown) {
  12691. _this.onPointerDown(evt, pickResult);
  12692. }
  12693. };
  12694. this._onPointerUp = function (evt) {
  12695. var predicate = null;
  12696. if (!_this.onPointerUp) {
  12697. predicate = function (mesh) {
  12698. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12699. };
  12700. }
  12701. _this._updatePointerPosition(evt);
  12702. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12703. if (pickResult.hit) {
  12704. if (pickResult.pickedMesh.actionManager) {
  12705. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12706. }
  12707. }
  12708. if (_this.onPointerUp) {
  12709. _this.onPointerUp(evt, pickResult);
  12710. }
  12711. };
  12712. this._onKeyDown = function (evt) {
  12713. if (_this.actionManager) {
  12714. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12715. }
  12716. };
  12717. this._onKeyUp = function (evt) {
  12718. if (_this.actionManager) {
  12719. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12720. }
  12721. };
  12722. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12723. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12724. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12725. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12726. // Wheel
  12727. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  12728. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  12729. BABYLON.Tools.RegisterTopRootEvents([
  12730. { name: "keydown", handler: this._onKeyDown },
  12731. { name: "keyup", handler: this._onKeyUp }
  12732. ]);
  12733. };
  12734. Scene.prototype.detachControl = function () {
  12735. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12736. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12737. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12738. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12739. // Wheel
  12740. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  12741. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  12742. BABYLON.Tools.UnregisterTopRootEvents([
  12743. { name: "keydown", handler: this._onKeyDown },
  12744. { name: "keyup", handler: this._onKeyUp }
  12745. ]);
  12746. };
  12747. // Ready
  12748. Scene.prototype.isReady = function () {
  12749. if (this._pendingData.length > 0) {
  12750. return false;
  12751. }
  12752. var index;
  12753. for (index = 0; index < this._geometries.length; index++) {
  12754. var geometry = this._geometries[index];
  12755. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12756. return false;
  12757. }
  12758. }
  12759. for (index = 0; index < this.meshes.length; index++) {
  12760. var mesh = this.meshes[index];
  12761. if (!mesh.isReady()) {
  12762. return false;
  12763. }
  12764. var mat = mesh.material;
  12765. if (mat) {
  12766. if (!mat.isReady(mesh)) {
  12767. return false;
  12768. }
  12769. }
  12770. }
  12771. return true;
  12772. };
  12773. Scene.prototype.resetCachedMaterial = function () {
  12774. this._cachedMaterial = null;
  12775. };
  12776. Scene.prototype.registerBeforeRender = function (func) {
  12777. this._onBeforeRenderCallbacks.push(func);
  12778. };
  12779. Scene.prototype.unregisterBeforeRender = function (func) {
  12780. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12781. if (index > -1) {
  12782. this._onBeforeRenderCallbacks.splice(index, 1);
  12783. }
  12784. };
  12785. Scene.prototype.registerAfterRender = function (func) {
  12786. this._onAfterRenderCallbacks.push(func);
  12787. };
  12788. Scene.prototype.unregisterAfterRender = function (func) {
  12789. var index = this._onAfterRenderCallbacks.indexOf(func);
  12790. if (index > -1) {
  12791. this._onAfterRenderCallbacks.splice(index, 1);
  12792. }
  12793. };
  12794. Scene.prototype._addPendingData = function (data) {
  12795. this._pendingData.push(data);
  12796. };
  12797. Scene.prototype._removePendingData = function (data) {
  12798. var index = this._pendingData.indexOf(data);
  12799. if (index !== -1) {
  12800. this._pendingData.splice(index, 1);
  12801. }
  12802. };
  12803. Scene.prototype.getWaitingItemsCount = function () {
  12804. return this._pendingData.length;
  12805. };
  12806. /**
  12807. * Registers a function to be executed when the scene is ready.
  12808. * @param {Function} func - the function to be executed.
  12809. */
  12810. Scene.prototype.executeWhenReady = function (func) {
  12811. var _this = this;
  12812. this._onReadyCallbacks.push(func);
  12813. if (this._executeWhenReadyTimeoutId !== -1) {
  12814. return;
  12815. }
  12816. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12817. _this._checkIsReady();
  12818. }, 150);
  12819. };
  12820. Scene.prototype._checkIsReady = function () {
  12821. var _this = this;
  12822. if (this.isReady()) {
  12823. this._onReadyCallbacks.forEach(function (func) {
  12824. func();
  12825. });
  12826. this._onReadyCallbacks = [];
  12827. this._executeWhenReadyTimeoutId = -1;
  12828. return;
  12829. }
  12830. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12831. _this._checkIsReady();
  12832. }, 150);
  12833. };
  12834. // Animations
  12835. /**
  12836. * Will start the animation sequence of a given target
  12837. * @param target - the target
  12838. * @param {number} from - from which frame should animation start
  12839. * @param {number} to - till which frame should animation run.
  12840. * @param {boolean} [loop] - should the animation loop
  12841. * @param {number} [speedRatio] - the speed in which to run the animation
  12842. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12843. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12844. * @return {BABYLON.Animatable} the animatable object created for this animation
  12845. * @see BABYLON.Animatable
  12846. * @see http://doc.babylonjs.com/page.php?p=22081
  12847. */
  12848. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12849. if (speedRatio === undefined) {
  12850. speedRatio = 1.0;
  12851. }
  12852. this.stopAnimation(target);
  12853. if (!animatable) {
  12854. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12855. }
  12856. // Local animations
  12857. if (target.animations) {
  12858. animatable.appendAnimations(target, target.animations);
  12859. }
  12860. // Children animations
  12861. if (target.getAnimatables) {
  12862. var animatables = target.getAnimatables();
  12863. for (var index = 0; index < animatables.length; index++) {
  12864. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12865. }
  12866. }
  12867. return animatable;
  12868. };
  12869. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12870. if (speedRatio === undefined) {
  12871. speedRatio = 1.0;
  12872. }
  12873. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12874. return animatable;
  12875. };
  12876. Scene.prototype.getAnimatableByTarget = function (target) {
  12877. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12878. if (this._activeAnimatables[index].target === target) {
  12879. return this._activeAnimatables[index];
  12880. }
  12881. }
  12882. return null;
  12883. };
  12884. /**
  12885. * Will stop the animation of the given target
  12886. * @param target - the target
  12887. * @see beginAnimation
  12888. */
  12889. Scene.prototype.stopAnimation = function (target) {
  12890. var animatable = this.getAnimatableByTarget(target);
  12891. if (animatable) {
  12892. animatable.stop();
  12893. }
  12894. };
  12895. Scene.prototype._animate = function () {
  12896. if (!this.animationsEnabled) {
  12897. return;
  12898. }
  12899. if (!this._animationStartDate) {
  12900. this._animationStartDate = BABYLON.Tools.Now;
  12901. }
  12902. // Getting time
  12903. var now = BABYLON.Tools.Now;
  12904. var delay = now - this._animationStartDate;
  12905. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12906. this._activeAnimatables[index]._animate(delay);
  12907. }
  12908. };
  12909. // Matrix
  12910. Scene.prototype.getViewMatrix = function () {
  12911. return this._viewMatrix;
  12912. };
  12913. Scene.prototype.getProjectionMatrix = function () {
  12914. return this._projectionMatrix;
  12915. };
  12916. Scene.prototype.getTransformMatrix = function () {
  12917. return this._transformMatrix;
  12918. };
  12919. Scene.prototype.setTransformMatrix = function (view, projection) {
  12920. this._viewMatrix = view;
  12921. this._projectionMatrix = projection;
  12922. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12923. };
  12924. // Methods
  12925. Scene.prototype.addMesh = function (newMesh) {
  12926. newMesh.uniqueId = this._uniqueIdCounter++;
  12927. var position = this.meshes.push(newMesh);
  12928. //notify the collision coordinator
  12929. this.collisionCoordinator.onMeshAdded(newMesh);
  12930. if (this.onNewMeshAdded) {
  12931. this.onNewMeshAdded(newMesh, position, this);
  12932. }
  12933. };
  12934. Scene.prototype.removeMesh = function (toRemove) {
  12935. var index = this.meshes.indexOf(toRemove);
  12936. if (index !== -1) {
  12937. // Remove from the scene if mesh found
  12938. this.meshes.splice(index, 1);
  12939. }
  12940. //notify the collision coordinator
  12941. this.collisionCoordinator.onMeshRemoved(toRemove);
  12942. if (this.onMeshRemoved) {
  12943. this.onMeshRemoved(toRemove);
  12944. }
  12945. return index;
  12946. };
  12947. Scene.prototype.removeLight = function (toRemove) {
  12948. var index = this.lights.indexOf(toRemove);
  12949. if (index !== -1) {
  12950. // Remove from the scene if mesh found
  12951. this.lights.splice(index, 1);
  12952. }
  12953. if (this.onLightRemoved) {
  12954. this.onLightRemoved(toRemove);
  12955. }
  12956. return index;
  12957. };
  12958. Scene.prototype.removeCamera = function (toRemove) {
  12959. var index = this.cameras.indexOf(toRemove);
  12960. if (index !== -1) {
  12961. // Remove from the scene if mesh found
  12962. this.cameras.splice(index, 1);
  12963. }
  12964. // Remove from activeCameras
  12965. var index2 = this.activeCameras.indexOf(toRemove);
  12966. if (index2 !== -1) {
  12967. // Remove from the scene if mesh found
  12968. this.activeCameras.splice(index2, 1);
  12969. }
  12970. // Reset the activeCamera
  12971. if (this.activeCamera === toRemove) {
  12972. if (this.cameras.length > 0) {
  12973. this.activeCamera = this.cameras[0];
  12974. }
  12975. else {
  12976. this.activeCamera = null;
  12977. }
  12978. }
  12979. if (this.onCameraRemoved) {
  12980. this.onCameraRemoved(toRemove);
  12981. }
  12982. return index;
  12983. };
  12984. Scene.prototype.addLight = function (newLight) {
  12985. newLight.uniqueId = this._uniqueIdCounter++;
  12986. var position = this.lights.push(newLight);
  12987. if (this.onNewLightAdded) {
  12988. this.onNewLightAdded(newLight, position, this);
  12989. }
  12990. };
  12991. Scene.prototype.addCamera = function (newCamera) {
  12992. newCamera.uniqueId = this._uniqueIdCounter++;
  12993. var position = this.cameras.push(newCamera);
  12994. if (this.onNewCameraAdded) {
  12995. this.onNewCameraAdded(newCamera, position, this);
  12996. }
  12997. };
  12998. /**
  12999. * sets the active camera of the scene using its ID
  13000. * @param {string} id - the camera's ID
  13001. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13002. * @see activeCamera
  13003. */
  13004. Scene.prototype.setActiveCameraByID = function (id) {
  13005. var camera = this.getCameraByID(id);
  13006. if (camera) {
  13007. this.activeCamera = camera;
  13008. return camera;
  13009. }
  13010. return null;
  13011. };
  13012. /**
  13013. * sets the active camera of the scene using its name
  13014. * @param {string} name - the camera's name
  13015. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  13016. * @see activeCamera
  13017. */
  13018. Scene.prototype.setActiveCameraByName = function (name) {
  13019. var camera = this.getCameraByName(name);
  13020. if (camera) {
  13021. this.activeCamera = camera;
  13022. return camera;
  13023. }
  13024. return null;
  13025. };
  13026. /**
  13027. * get a material using its id
  13028. * @param {string} the material's ID
  13029. * @return {BABYLON.Material|null} the material or null if none found.
  13030. */
  13031. Scene.prototype.getMaterialByID = function (id) {
  13032. for (var index = 0; index < this.materials.length; index++) {
  13033. if (this.materials[index].id === id) {
  13034. return this.materials[index];
  13035. }
  13036. }
  13037. return null;
  13038. };
  13039. /**
  13040. * get a material using its name
  13041. * @param {string} the material's name
  13042. * @return {BABYLON.Material|null} the material or null if none found.
  13043. */
  13044. Scene.prototype.getMaterialByName = function (name) {
  13045. for (var index = 0; index < this.materials.length; index++) {
  13046. if (this.materials[index].name === name) {
  13047. return this.materials[index];
  13048. }
  13049. }
  13050. return null;
  13051. };
  13052. Scene.prototype.getLensFlareSystemByName = function (name) {
  13053. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  13054. if (this.lensFlareSystems[index].name === name) {
  13055. return this.lensFlareSystems[index];
  13056. }
  13057. }
  13058. return null;
  13059. };
  13060. Scene.prototype.getCameraByID = function (id) {
  13061. for (var index = 0; index < this.cameras.length; index++) {
  13062. if (this.cameras[index].id === id) {
  13063. return this.cameras[index];
  13064. }
  13065. }
  13066. return null;
  13067. };
  13068. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  13069. for (var index = 0; index < this.cameras.length; index++) {
  13070. if (this.cameras[index].uniqueId === uniqueId) {
  13071. return this.cameras[index];
  13072. }
  13073. }
  13074. return null;
  13075. };
  13076. /**
  13077. * get a camera using its name
  13078. * @param {string} the camera's name
  13079. * @return {BABYLON.Camera|null} the camera or null if none found.
  13080. */
  13081. Scene.prototype.getCameraByName = function (name) {
  13082. for (var index = 0; index < this.cameras.length; index++) {
  13083. if (this.cameras[index].name === name) {
  13084. return this.cameras[index];
  13085. }
  13086. }
  13087. return null;
  13088. };
  13089. /**
  13090. * get a light node using its name
  13091. * @param {string} the light's name
  13092. * @return {BABYLON.Light|null} the light or null if none found.
  13093. */
  13094. Scene.prototype.getLightByName = function (name) {
  13095. for (var index = 0; index < this.lights.length; index++) {
  13096. if (this.lights[index].name === name) {
  13097. return this.lights[index];
  13098. }
  13099. }
  13100. return null;
  13101. };
  13102. /**
  13103. * get a light node using its ID
  13104. * @param {string} the light's id
  13105. * @return {BABYLON.Light|null} the light or null if none found.
  13106. */
  13107. Scene.prototype.getLightByID = function (id) {
  13108. for (var index = 0; index < this.lights.length; index++) {
  13109. if (this.lights[index].id === id) {
  13110. return this.lights[index];
  13111. }
  13112. }
  13113. return null;
  13114. };
  13115. /**
  13116. * get a light node using its scene-generated unique ID
  13117. * @param {number} the light's unique id
  13118. * @return {BABYLON.Light|null} the light or null if none found.
  13119. */
  13120. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  13121. for (var index = 0; index < this.lights.length; index++) {
  13122. if (this.lights[index].uniqueId === uniqueId) {
  13123. return this.lights[index];
  13124. }
  13125. }
  13126. return null;
  13127. };
  13128. /**
  13129. * get a geometry using its ID
  13130. * @param {string} the geometry's id
  13131. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  13132. */
  13133. Scene.prototype.getGeometryByID = function (id) {
  13134. for (var index = 0; index < this._geometries.length; index++) {
  13135. if (this._geometries[index].id === id) {
  13136. return this._geometries[index];
  13137. }
  13138. }
  13139. return null;
  13140. };
  13141. /**
  13142. * add a new geometry to this scene.
  13143. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  13144. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  13145. * @return {boolean} was the geometry added or not
  13146. */
  13147. Scene.prototype.pushGeometry = function (geometry, force) {
  13148. if (!force && this.getGeometryByID(geometry.id)) {
  13149. return false;
  13150. }
  13151. this._geometries.push(geometry);
  13152. //notify the collision coordinator
  13153. this.collisionCoordinator.onGeometryAdded(geometry);
  13154. if (this.onGeometryAdded) {
  13155. this.onGeometryAdded(geometry);
  13156. }
  13157. return true;
  13158. };
  13159. /**
  13160. * Removes an existing geometry
  13161. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  13162. * @return {boolean} was the geometry removed or not
  13163. */
  13164. Scene.prototype.removeGeometry = function (geometry) {
  13165. var index = this._geometries.indexOf(geometry);
  13166. if (index > -1) {
  13167. this._geometries.splice(index, 1);
  13168. //notify the collision coordinator
  13169. this.collisionCoordinator.onGeometryDeleted(geometry);
  13170. if (this.onGeometryRemoved) {
  13171. this.onGeometryRemoved(geometry);
  13172. }
  13173. return true;
  13174. }
  13175. return false;
  13176. };
  13177. Scene.prototype.getGeometries = function () {
  13178. return this._geometries;
  13179. };
  13180. /**
  13181. * Get the first added mesh found of a given ID
  13182. * @param {string} id - the id to search for
  13183. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13184. */
  13185. Scene.prototype.getMeshByID = function (id) {
  13186. for (var index = 0; index < this.meshes.length; index++) {
  13187. if (this.meshes[index].id === id) {
  13188. return this.meshes[index];
  13189. }
  13190. }
  13191. return null;
  13192. };
  13193. /**
  13194. * Get a mesh with its auto-generated unique id
  13195. * @param {number} uniqueId - the unique id to search for
  13196. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13197. */
  13198. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  13199. for (var index = 0; index < this.meshes.length; index++) {
  13200. if (this.meshes[index].uniqueId === uniqueId) {
  13201. return this.meshes[index];
  13202. }
  13203. }
  13204. return null;
  13205. };
  13206. /**
  13207. * Get a the last added mesh found of a given ID
  13208. * @param {string} id - the id to search for
  13209. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  13210. */
  13211. Scene.prototype.getLastMeshByID = function (id) {
  13212. for (var index = this.meshes.length - 1; index >= 0; index--) {
  13213. if (this.meshes[index].id === id) {
  13214. return this.meshes[index];
  13215. }
  13216. }
  13217. return null;
  13218. };
  13219. /**
  13220. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  13221. * @param {string} id - the id to search for
  13222. * @return {BABYLON.Node|null} the node found or null if not found at all.
  13223. */
  13224. Scene.prototype.getLastEntryByID = function (id) {
  13225. var index;
  13226. for (index = this.meshes.length - 1; index >= 0; index--) {
  13227. if (this.meshes[index].id === id) {
  13228. return this.meshes[index];
  13229. }
  13230. }
  13231. for (index = this.cameras.length - 1; index >= 0; index--) {
  13232. if (this.cameras[index].id === id) {
  13233. return this.cameras[index];
  13234. }
  13235. }
  13236. for (index = this.lights.length - 1; index >= 0; index--) {
  13237. if (this.lights[index].id === id) {
  13238. return this.lights[index];
  13239. }
  13240. }
  13241. return null;
  13242. };
  13243. Scene.prototype.getNodeByID = function (id) {
  13244. var mesh = this.getMeshByID(id);
  13245. if (mesh) {
  13246. return mesh;
  13247. }
  13248. var light = this.getLightByID(id);
  13249. if (light) {
  13250. return light;
  13251. }
  13252. return this.getCameraByID(id);
  13253. };
  13254. Scene.prototype.getNodeByName = function (name) {
  13255. var mesh = this.getMeshByName(name);
  13256. if (mesh) {
  13257. return mesh;
  13258. }
  13259. var light = this.getLightByName(name);
  13260. if (light) {
  13261. return light;
  13262. }
  13263. return this.getCameraByName(name);
  13264. };
  13265. Scene.prototype.getMeshByName = function (name) {
  13266. for (var index = 0; index < this.meshes.length; index++) {
  13267. if (this.meshes[index].name === name) {
  13268. return this.meshes[index];
  13269. }
  13270. }
  13271. return null;
  13272. };
  13273. Scene.prototype.getSoundByName = function (name) {
  13274. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  13275. if (this.mainSoundTrack.soundCollection[index].name === name) {
  13276. return this.mainSoundTrack.soundCollection[index];
  13277. }
  13278. }
  13279. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  13280. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  13281. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  13282. return this.soundTracks[sdIndex].soundCollection[index];
  13283. }
  13284. }
  13285. }
  13286. return null;
  13287. };
  13288. Scene.prototype.getLastSkeletonByID = function (id) {
  13289. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  13290. if (this.skeletons[index].id === id) {
  13291. return this.skeletons[index];
  13292. }
  13293. }
  13294. return null;
  13295. };
  13296. Scene.prototype.getSkeletonById = function (id) {
  13297. for (var index = 0; index < this.skeletons.length; index++) {
  13298. if (this.skeletons[index].id === id) {
  13299. return this.skeletons[index];
  13300. }
  13301. }
  13302. return null;
  13303. };
  13304. Scene.prototype.getSkeletonByName = function (name) {
  13305. for (var index = 0; index < this.skeletons.length; index++) {
  13306. if (this.skeletons[index].name === name) {
  13307. return this.skeletons[index];
  13308. }
  13309. }
  13310. return null;
  13311. };
  13312. Scene.prototype.isActiveMesh = function (mesh) {
  13313. return (this._activeMeshes.indexOf(mesh) !== -1);
  13314. };
  13315. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  13316. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  13317. var material = subMesh.getMaterial();
  13318. if (mesh.showSubMeshesBoundingBox) {
  13319. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  13320. }
  13321. if (material) {
  13322. // Render targets
  13323. if (material.getRenderTargetTextures) {
  13324. if (this._processedMaterials.indexOf(material) === -1) {
  13325. this._processedMaterials.push(material);
  13326. this._renderTargets.concat(material.getRenderTargetTextures());
  13327. }
  13328. }
  13329. // Dispatch
  13330. this._activeIndices += subMesh.indexCount;
  13331. this._renderingManager.dispatch(subMesh);
  13332. }
  13333. }
  13334. };
  13335. Scene.prototype._evaluateActiveMeshes = function () {
  13336. this.activeCamera._activeMeshes.reset();
  13337. this._activeMeshes.reset();
  13338. this._renderingManager.reset();
  13339. this._processedMaterials.reset();
  13340. this._activeParticleSystems.reset();
  13341. this._activeSkeletons.reset();
  13342. this._softwareSkinnedMeshes.reset();
  13343. this._boundingBoxRenderer.reset();
  13344. this._edgesRenderers.reset();
  13345. if (!this._frustumPlanes) {
  13346. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13347. }
  13348. else {
  13349. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13350. }
  13351. // Meshes
  13352. var meshes;
  13353. var len;
  13354. if (this._selectionOctree) {
  13355. var selection = this._selectionOctree.select(this._frustumPlanes);
  13356. meshes = selection.data;
  13357. len = selection.length;
  13358. }
  13359. else {
  13360. len = this.meshes.length;
  13361. meshes = this.meshes;
  13362. }
  13363. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  13364. var mesh = meshes[meshIndex];
  13365. if (mesh.isBlocked) {
  13366. continue;
  13367. }
  13368. this._totalVertices += mesh.getTotalVertices();
  13369. if (!mesh.isReady() || !mesh.isEnabled()) {
  13370. continue;
  13371. }
  13372. mesh.computeWorldMatrix();
  13373. // Intersections
  13374. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13375. this._meshesForIntersections.pushNoDuplicate(mesh);
  13376. }
  13377. // Switch to current LOD
  13378. var meshLOD = mesh.getLOD(this.activeCamera);
  13379. if (!meshLOD) {
  13380. continue;
  13381. }
  13382. mesh._preActivate();
  13383. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13384. this._activeMeshes.push(mesh);
  13385. this.activeCamera._activeMeshes.push(mesh);
  13386. mesh._activate(this._renderId);
  13387. this._activeMesh(meshLOD);
  13388. }
  13389. }
  13390. // Particle systems
  13391. var beforeParticlesDate = BABYLON.Tools.Now;
  13392. if (this.particlesEnabled) {
  13393. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13394. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13395. var particleSystem = this.particleSystems[particleIndex];
  13396. if (!particleSystem.isStarted()) {
  13397. continue;
  13398. }
  13399. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13400. this._activeParticleSystems.push(particleSystem);
  13401. particleSystem.animate();
  13402. }
  13403. }
  13404. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13405. }
  13406. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13407. };
  13408. Scene.prototype._activeMesh = function (mesh) {
  13409. if (mesh.skeleton && this.skeletonsEnabled) {
  13410. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13411. if (!mesh.computeBonesUsingShaders) {
  13412. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  13413. }
  13414. }
  13415. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13416. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13417. }
  13418. if (mesh._edgesRenderer) {
  13419. this._edgesRenderers.push(mesh._edgesRenderer);
  13420. }
  13421. if (mesh && mesh.subMeshes) {
  13422. // Submeshes Octrees
  13423. var len;
  13424. var subMeshes;
  13425. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13426. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13427. len = intersections.length;
  13428. subMeshes = intersections.data;
  13429. }
  13430. else {
  13431. subMeshes = mesh.subMeshes;
  13432. len = subMeshes.length;
  13433. }
  13434. for (var subIndex = 0; subIndex < len; subIndex++) {
  13435. var subMesh = subMeshes[subIndex];
  13436. this._evaluateSubMesh(subMesh, mesh);
  13437. }
  13438. }
  13439. };
  13440. Scene.prototype.updateTransformMatrix = function (force) {
  13441. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13442. };
  13443. Scene.prototype._renderForCamera = function (camera) {
  13444. var engine = this._engine;
  13445. this.activeCamera = camera;
  13446. if (!this.activeCamera)
  13447. throw new Error("Active camera not set");
  13448. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13449. // Viewport
  13450. engine.setViewport(this.activeCamera.viewport);
  13451. // Camera
  13452. this.resetCachedMaterial();
  13453. this._renderId++;
  13454. this.updateTransformMatrix();
  13455. if (this.beforeCameraRender) {
  13456. this.beforeCameraRender(this.activeCamera);
  13457. }
  13458. // Meshes
  13459. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13460. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13461. this._evaluateActiveMeshes();
  13462. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13463. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13464. // Skeletons
  13465. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13466. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13467. skeleton.prepare();
  13468. }
  13469. // Software skinning
  13470. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  13471. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  13472. mesh.applySkeleton(mesh.skeleton);
  13473. }
  13474. // Render targets
  13475. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13476. if (this.renderTargetsEnabled) {
  13477. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13478. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13479. var renderTarget = this._renderTargets.data[renderIndex];
  13480. if (renderTarget._shouldRender()) {
  13481. this._renderId++;
  13482. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13483. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13484. }
  13485. }
  13486. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13487. this._renderId++;
  13488. }
  13489. if (this._renderTargets.length > 0) {
  13490. engine.restoreDefaultFramebuffer();
  13491. }
  13492. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13493. // Prepare Frame
  13494. this.postProcessManager._prepareFrame();
  13495. var beforeRenderDate = BABYLON.Tools.Now;
  13496. // Backgrounds
  13497. var layerIndex;
  13498. if (this.layers.length) {
  13499. engine.setDepthBuffer(false);
  13500. var layer;
  13501. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13502. layer = this.layers[layerIndex];
  13503. if (layer.isBackground) {
  13504. layer.render();
  13505. }
  13506. }
  13507. engine.setDepthBuffer(true);
  13508. }
  13509. // Render
  13510. BABYLON.Tools.StartPerformanceCounter("Main render");
  13511. this._renderingManager.render(null, null, true, true);
  13512. BABYLON.Tools.EndPerformanceCounter("Main render");
  13513. // Bounding boxes
  13514. this._boundingBoxRenderer.render();
  13515. // Edges
  13516. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  13517. this._edgesRenderers.data[edgesRendererIndex].render();
  13518. }
  13519. // Lens flares
  13520. if (this.lensFlaresEnabled) {
  13521. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13522. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13523. this.lensFlareSystems[lensFlareSystemIndex].render();
  13524. }
  13525. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13526. }
  13527. // Foregrounds
  13528. if (this.layers.length) {
  13529. engine.setDepthBuffer(false);
  13530. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13531. layer = this.layers[layerIndex];
  13532. if (!layer.isBackground) {
  13533. layer.render();
  13534. }
  13535. }
  13536. engine.setDepthBuffer(true);
  13537. }
  13538. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13539. // Finalize frame
  13540. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13541. // Update camera
  13542. this.activeCamera._updateFromScene();
  13543. // Reset some special arrays
  13544. this._renderTargets.reset();
  13545. if (this.afterCameraRender) {
  13546. this.afterCameraRender(this.activeCamera);
  13547. }
  13548. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13549. };
  13550. Scene.prototype._processSubCameras = function (camera) {
  13551. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13552. this._renderForCamera(camera);
  13553. return;
  13554. }
  13555. // rig cameras
  13556. for (var index = 0; index < camera._rigCameras.length; index++) {
  13557. this._renderForCamera(camera._rigCameras[index]);
  13558. }
  13559. this.activeCamera = camera;
  13560. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13561. // Update camera
  13562. this.activeCamera._updateFromScene();
  13563. };
  13564. Scene.prototype._checkIntersections = function () {
  13565. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13566. var sourceMesh = this._meshesForIntersections.data[index];
  13567. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13568. var action = sourceMesh.actionManager.actions[actionIndex];
  13569. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13570. var parameters = action.getTriggerParameter();
  13571. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13572. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13573. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13574. if (areIntersecting && currentIntersectionInProgress === -1) {
  13575. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13576. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13577. sourceMesh._intersectionsInProgress.push(otherMesh);
  13578. }
  13579. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13580. sourceMesh._intersectionsInProgress.push(otherMesh);
  13581. }
  13582. }
  13583. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13584. //They intersected, and now they don't.
  13585. //is this trigger an exit trigger? execute an event.
  13586. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13587. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  13588. }
  13589. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13590. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13591. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13592. }
  13593. }
  13594. }
  13595. }
  13596. }
  13597. };
  13598. Scene.prototype.render = function () {
  13599. var startDate = BABYLON.Tools.Now;
  13600. this._particlesDuration = 0;
  13601. this._spritesDuration = 0;
  13602. this._activeParticles = 0;
  13603. this._renderDuration = 0;
  13604. this._renderTargetsDuration = 0;
  13605. this._evaluateActiveMeshesDuration = 0;
  13606. this._totalVertices = 0;
  13607. this._activeIndices = 0;
  13608. this._activeBones = 0;
  13609. this.getEngine().resetDrawCalls();
  13610. this._meshesForIntersections.reset();
  13611. this.resetCachedMaterial();
  13612. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13613. // Actions
  13614. if (this.actionManager) {
  13615. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13616. }
  13617. //Simplification Queue
  13618. if (!this.simplificationQueue.running) {
  13619. this.simplificationQueue.executeNext();
  13620. }
  13621. // Before render
  13622. if (this.beforeRender) {
  13623. this.beforeRender();
  13624. }
  13625. var callbackIndex;
  13626. for (callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13627. this._onBeforeRenderCallbacks[callbackIndex]();
  13628. }
  13629. // Animations
  13630. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13631. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13632. this._animate();
  13633. // Physics
  13634. if (this._physicsEngine) {
  13635. BABYLON.Tools.StartPerformanceCounter("Physics");
  13636. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13637. BABYLON.Tools.EndPerformanceCounter("Physics");
  13638. }
  13639. // Customs render targets
  13640. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13641. var engine = this.getEngine();
  13642. var currentActiveCamera = this.activeCamera;
  13643. if (this.renderTargetsEnabled) {
  13644. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13645. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13646. var renderTarget = this.customRenderTargets[customIndex];
  13647. if (renderTarget._shouldRender()) {
  13648. this._renderId++;
  13649. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13650. if (!this.activeCamera)
  13651. throw new Error("Active camera not set");
  13652. // Viewport
  13653. engine.setViewport(this.activeCamera.viewport);
  13654. // Camera
  13655. this.updateTransformMatrix();
  13656. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13657. }
  13658. }
  13659. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13660. this._renderId++;
  13661. }
  13662. if (this.customRenderTargets.length > 0) {
  13663. engine.restoreDefaultFramebuffer();
  13664. }
  13665. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13666. this.activeCamera = currentActiveCamera;
  13667. // Procedural textures
  13668. if (this.proceduralTexturesEnabled) {
  13669. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13670. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13671. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13672. if (proceduralTexture._shouldRender()) {
  13673. proceduralTexture.render();
  13674. }
  13675. }
  13676. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13677. }
  13678. // Clear
  13679. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13680. // Shadows
  13681. if (this.shadowsEnabled) {
  13682. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13683. var light = this.lights[lightIndex];
  13684. var shadowGenerator = light.getShadowGenerator();
  13685. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13686. this._renderTargets.push(shadowGenerator.getShadowMap());
  13687. }
  13688. }
  13689. }
  13690. // Depth renderer
  13691. if (this._depthRenderer) {
  13692. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13693. }
  13694. // RenderPipeline
  13695. this.postProcessRenderPipelineManager.update();
  13696. // Multi-cameras?
  13697. if (this.activeCameras.length > 0) {
  13698. var currentRenderId = this._renderId;
  13699. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13700. this._renderId = currentRenderId;
  13701. this._processSubCameras(this.activeCameras[cameraIndex]);
  13702. }
  13703. }
  13704. else {
  13705. if (!this.activeCamera) {
  13706. throw new Error("No camera defined");
  13707. }
  13708. this._processSubCameras(this.activeCamera);
  13709. }
  13710. // Intersection checks
  13711. this._checkIntersections();
  13712. // Update the audio listener attached to the camera
  13713. this._updateAudioParameters();
  13714. // After render
  13715. if (this.afterRender) {
  13716. this.afterRender();
  13717. }
  13718. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13719. this._onAfterRenderCallbacks[callbackIndex]();
  13720. }
  13721. // Cleaning
  13722. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13723. this._toBeDisposed.data[index].dispose();
  13724. this._toBeDisposed[index] = null;
  13725. }
  13726. this._toBeDisposed.reset();
  13727. if (this.dumpNextRenderTargets) {
  13728. this.dumpNextRenderTargets = false;
  13729. }
  13730. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13731. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13732. };
  13733. Scene.prototype._updateAudioParameters = function () {
  13734. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13735. return;
  13736. }
  13737. var listeningCamera;
  13738. var audioEngine = BABYLON.Engine.audioEngine;
  13739. if (this.activeCameras.length > 0) {
  13740. listeningCamera = this.activeCameras[0];
  13741. }
  13742. else {
  13743. listeningCamera = this.activeCamera;
  13744. }
  13745. if (listeningCamera && audioEngine.canUseWebAudio) {
  13746. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13747. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13748. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13749. cameraDirection.normalize();
  13750. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13751. var i;
  13752. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13753. var sound = this.mainSoundTrack.soundCollection[i];
  13754. if (sound.useCustomAttenuation) {
  13755. sound.updateDistanceFromListener();
  13756. }
  13757. }
  13758. for (i = 0; i < this.soundTracks.length; i++) {
  13759. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13760. sound = this.soundTracks[i].soundCollection[j];
  13761. if (sound.useCustomAttenuation) {
  13762. sound.updateDistanceFromListener();
  13763. }
  13764. }
  13765. }
  13766. }
  13767. };
  13768. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13769. // Audio
  13770. get: function () {
  13771. return this._audioEnabled;
  13772. },
  13773. set: function (value) {
  13774. this._audioEnabled = value;
  13775. if (this._audioEnabled) {
  13776. this._enableAudio();
  13777. }
  13778. else {
  13779. this._disableAudio();
  13780. }
  13781. },
  13782. enumerable: true,
  13783. configurable: true
  13784. });
  13785. Scene.prototype._disableAudio = function () {
  13786. var i;
  13787. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13788. this.mainSoundTrack.soundCollection[i].pause();
  13789. }
  13790. for (i = 0; i < this.soundTracks.length; i++) {
  13791. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13792. this.soundTracks[i].soundCollection[j].pause();
  13793. }
  13794. }
  13795. };
  13796. Scene.prototype._enableAudio = function () {
  13797. var i;
  13798. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13799. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13800. this.mainSoundTrack.soundCollection[i].play();
  13801. }
  13802. }
  13803. for (i = 0; i < this.soundTracks.length; i++) {
  13804. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13805. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13806. this.soundTracks[i].soundCollection[j].play();
  13807. }
  13808. }
  13809. }
  13810. };
  13811. Object.defineProperty(Scene.prototype, "headphone", {
  13812. get: function () {
  13813. return this._headphone;
  13814. },
  13815. set: function (value) {
  13816. this._headphone = value;
  13817. if (this._headphone) {
  13818. this._switchAudioModeForHeadphones();
  13819. }
  13820. else {
  13821. this._switchAudioModeForNormalSpeakers();
  13822. }
  13823. },
  13824. enumerable: true,
  13825. configurable: true
  13826. });
  13827. Scene.prototype._switchAudioModeForHeadphones = function () {
  13828. this.mainSoundTrack.switchPanningModelToHRTF();
  13829. for (var i = 0; i < this.soundTracks.length; i++) {
  13830. this.soundTracks[i].switchPanningModelToHRTF();
  13831. }
  13832. };
  13833. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13834. this.mainSoundTrack.switchPanningModelToEqualPower();
  13835. for (var i = 0; i < this.soundTracks.length; i++) {
  13836. this.soundTracks[i].switchPanningModelToEqualPower();
  13837. }
  13838. };
  13839. Scene.prototype.enableDepthRenderer = function () {
  13840. if (this._depthRenderer) {
  13841. return this._depthRenderer;
  13842. }
  13843. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13844. return this._depthRenderer;
  13845. };
  13846. Scene.prototype.disableDepthRenderer = function () {
  13847. if (!this._depthRenderer) {
  13848. return;
  13849. }
  13850. this._depthRenderer.dispose();
  13851. this._depthRenderer = null;
  13852. };
  13853. Scene.prototype.dispose = function () {
  13854. this.beforeRender = null;
  13855. this.afterRender = null;
  13856. this.skeletons = [];
  13857. this._boundingBoxRenderer.dispose();
  13858. if (this._depthRenderer) {
  13859. this._depthRenderer.dispose();
  13860. }
  13861. // Debug layer
  13862. this.debugLayer.hide();
  13863. // Events
  13864. if (this.onDispose) {
  13865. this.onDispose();
  13866. }
  13867. this._onBeforeRenderCallbacks = [];
  13868. this._onAfterRenderCallbacks = [];
  13869. this.detachControl();
  13870. // Release sounds & sounds tracks
  13871. this.disposeSounds();
  13872. // Detach cameras
  13873. var canvas = this._engine.getRenderingCanvas();
  13874. var index;
  13875. for (index = 0; index < this.cameras.length; index++) {
  13876. this.cameras[index].detachControl(canvas);
  13877. }
  13878. // Release lights
  13879. while (this.lights.length) {
  13880. this.lights[0].dispose();
  13881. }
  13882. // Release meshes
  13883. while (this.meshes.length) {
  13884. this.meshes[0].dispose(true);
  13885. }
  13886. // Release cameras
  13887. while (this.cameras.length) {
  13888. this.cameras[0].dispose();
  13889. }
  13890. // Release materials
  13891. while (this.materials.length) {
  13892. this.materials[0].dispose();
  13893. }
  13894. // Release particles
  13895. while (this.particleSystems.length) {
  13896. this.particleSystems[0].dispose();
  13897. }
  13898. // Release sprites
  13899. while (this.spriteManagers.length) {
  13900. this.spriteManagers[0].dispose();
  13901. }
  13902. // Release layers
  13903. while (this.layers.length) {
  13904. this.layers[0].dispose();
  13905. }
  13906. // Release textures
  13907. while (this.textures.length) {
  13908. this.textures[0].dispose();
  13909. }
  13910. // Post-processes
  13911. this.postProcessManager.dispose();
  13912. // Physics
  13913. if (this._physicsEngine) {
  13914. this.disablePhysicsEngine();
  13915. }
  13916. // Remove from engine
  13917. index = this._engine.scenes.indexOf(this);
  13918. if (index > -1) {
  13919. this._engine.scenes.splice(index, 1);
  13920. }
  13921. this._engine.wipeCaches();
  13922. };
  13923. // Release sounds & sounds tracks
  13924. Scene.prototype.disposeSounds = function () {
  13925. this.mainSoundTrack.dispose();
  13926. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13927. this.soundTracks[scIndex].dispose();
  13928. }
  13929. };
  13930. // Octrees
  13931. Scene.prototype.getWorldExtends = function () {
  13932. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13933. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13934. for (var index = 0; index < this.meshes.length; index++) {
  13935. var mesh = this.meshes[index];
  13936. mesh.computeWorldMatrix(true);
  13937. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13938. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13939. BABYLON.Tools.CheckExtends(minBox, min, max);
  13940. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13941. }
  13942. return {
  13943. min: min,
  13944. max: max
  13945. };
  13946. };
  13947. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13948. if (maxCapacity === void 0) { maxCapacity = 64; }
  13949. if (maxDepth === void 0) { maxDepth = 2; }
  13950. if (!this._selectionOctree) {
  13951. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13952. }
  13953. var worldExtends = this.getWorldExtends();
  13954. // Update octree
  13955. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13956. return this._selectionOctree;
  13957. };
  13958. // Picking
  13959. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13960. var engine = this._engine;
  13961. if (!camera) {
  13962. if (!this.activeCamera)
  13963. throw new Error("Active camera not set");
  13964. camera = this.activeCamera;
  13965. }
  13966. var cameraViewport = camera.viewport;
  13967. var viewport = cameraViewport.toGlobal(engine);
  13968. // Moving coordinates to local viewport world
  13969. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13970. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13971. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13972. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13973. };
  13974. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13975. var pickingInfo = null;
  13976. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13977. var mesh = this.meshes[meshIndex];
  13978. if (predicate) {
  13979. if (!predicate(mesh)) {
  13980. continue;
  13981. }
  13982. }
  13983. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13984. continue;
  13985. }
  13986. var world = mesh.getWorldMatrix();
  13987. var ray = rayFunction(world);
  13988. var result = mesh.intersects(ray, fastCheck);
  13989. if (!result || !result.hit)
  13990. continue;
  13991. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13992. continue;
  13993. pickingInfo = result;
  13994. if (fastCheck) {
  13995. break;
  13996. }
  13997. }
  13998. return pickingInfo || new BABYLON.PickingInfo();
  13999. };
  14000. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  14001. var _this = this;
  14002. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  14003. /// <param name="x">X position on screen</param>
  14004. /// <param name="y">Y position on screen</param>
  14005. /// <param name="predicate">Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true</param>
  14006. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  14007. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  14008. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  14009. };
  14010. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  14011. var _this = this;
  14012. return this._internalPick(function (world) {
  14013. if (!_this._pickWithRayInverseMatrix) {
  14014. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  14015. }
  14016. world.invertToRef(_this._pickWithRayInverseMatrix);
  14017. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  14018. }, predicate, fastCheck);
  14019. };
  14020. Scene.prototype.setPointerOverMesh = function (mesh) {
  14021. if (this._pointerOverMesh === mesh) {
  14022. return;
  14023. }
  14024. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14025. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14026. }
  14027. this._pointerOverMesh = mesh;
  14028. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  14029. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  14030. }
  14031. };
  14032. Scene.prototype.getPointerOverMesh = function () {
  14033. return this._pointerOverMesh;
  14034. };
  14035. // Physics
  14036. Scene.prototype.getPhysicsEngine = function () {
  14037. return this._physicsEngine;
  14038. };
  14039. Scene.prototype.enablePhysics = function (gravity, plugin) {
  14040. if (this._physicsEngine) {
  14041. return true;
  14042. }
  14043. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  14044. if (!this._physicsEngine.isSupported()) {
  14045. this._physicsEngine = null;
  14046. return false;
  14047. }
  14048. this._physicsEngine._initialize(gravity);
  14049. return true;
  14050. };
  14051. Scene.prototype.disablePhysicsEngine = function () {
  14052. if (!this._physicsEngine) {
  14053. return;
  14054. }
  14055. this._physicsEngine.dispose();
  14056. this._physicsEngine = undefined;
  14057. };
  14058. Scene.prototype.isPhysicsEnabled = function () {
  14059. return this._physicsEngine !== undefined;
  14060. };
  14061. Scene.prototype.setGravity = function (gravity) {
  14062. if (!this._physicsEngine) {
  14063. return;
  14064. }
  14065. this._physicsEngine._setGravity(gravity);
  14066. };
  14067. Scene.prototype.createCompoundImpostor = function (parts, options) {
  14068. if (parts.parts) {
  14069. options = parts;
  14070. parts = parts.parts;
  14071. }
  14072. if (!this._physicsEngine) {
  14073. return null;
  14074. }
  14075. for (var index = 0; index < parts.length; index++) {
  14076. var mesh = parts[index].mesh;
  14077. mesh._physicImpostor = parts[index].impostor;
  14078. mesh._physicsMass = options.mass / parts.length;
  14079. mesh._physicsFriction = options.friction;
  14080. mesh._physicRestitution = options.restitution;
  14081. }
  14082. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  14083. };
  14084. Scene.prototype.deleteCompoundImpostor = function (compound) {
  14085. for (var index = 0; index < compound.parts.length; index++) {
  14086. var mesh = compound.parts[index].mesh;
  14087. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  14088. this._physicsEngine._unregisterMesh(mesh);
  14089. }
  14090. };
  14091. // Misc.
  14092. Scene.prototype.createDefaultCameraOrLight = function () {
  14093. // Light
  14094. if (this.lights.length === 0) {
  14095. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  14096. }
  14097. // Camera
  14098. if (!this.activeCamera) {
  14099. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  14100. // Compute position
  14101. var worldExtends = this.getWorldExtends();
  14102. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  14103. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  14104. camera.setTarget(worldCenter);
  14105. this.activeCamera = camera;
  14106. }
  14107. };
  14108. // Tags
  14109. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  14110. if (tagsQuery === undefined) {
  14111. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  14112. return list;
  14113. }
  14114. var listByTags = [];
  14115. forEach = forEach || (function (item) { return; });
  14116. for (var i in list) {
  14117. var item = list[i];
  14118. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  14119. listByTags.push(item);
  14120. forEach(item);
  14121. }
  14122. }
  14123. return listByTags;
  14124. };
  14125. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  14126. return this._getByTags(this.meshes, tagsQuery, forEach);
  14127. };
  14128. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  14129. return this._getByTags(this.cameras, tagsQuery, forEach);
  14130. };
  14131. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  14132. return this._getByTags(this.lights, tagsQuery, forEach);
  14133. };
  14134. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  14135. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  14136. };
  14137. // Statics
  14138. Scene._FOGMODE_NONE = 0;
  14139. Scene._FOGMODE_EXP = 1;
  14140. Scene._FOGMODE_EXP2 = 2;
  14141. Scene._FOGMODE_LINEAR = 3;
  14142. Scene.MinDeltaTime = 1.0;
  14143. Scene.MaxDeltaTime = 1000.0;
  14144. return Scene;
  14145. })();
  14146. BABYLON.Scene = Scene;
  14147. })(BABYLON || (BABYLON = {}));
  14148. var BABYLON;
  14149. (function (BABYLON) {
  14150. var VertexBuffer = (function () {
  14151. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  14152. if (engine instanceof BABYLON.Mesh) {
  14153. this._engine = engine.getScene().getEngine();
  14154. }
  14155. else {
  14156. this._engine = engine;
  14157. }
  14158. this._updatable = updatable;
  14159. this._data = data;
  14160. if (!postponeInternalCreation) {
  14161. this.create();
  14162. }
  14163. this._kind = kind;
  14164. if (stride) {
  14165. this._strideSize = stride;
  14166. return;
  14167. }
  14168. // Deduce stride from kind
  14169. switch (kind) {
  14170. case VertexBuffer.PositionKind:
  14171. this._strideSize = 3;
  14172. break;
  14173. case VertexBuffer.NormalKind:
  14174. this._strideSize = 3;
  14175. break;
  14176. case VertexBuffer.UVKind:
  14177. case VertexBuffer.UV2Kind:
  14178. case VertexBuffer.UV3Kind:
  14179. case VertexBuffer.UV4Kind:
  14180. case VertexBuffer.UV5Kind:
  14181. case VertexBuffer.UV6Kind:
  14182. this._strideSize = 2;
  14183. break;
  14184. case VertexBuffer.ColorKind:
  14185. this._strideSize = 4;
  14186. break;
  14187. case VertexBuffer.MatricesIndicesKind:
  14188. this._strideSize = 4;
  14189. break;
  14190. case VertexBuffer.MatricesWeightsKind:
  14191. this._strideSize = 4;
  14192. break;
  14193. }
  14194. }
  14195. // Properties
  14196. VertexBuffer.prototype.isUpdatable = function () {
  14197. return this._updatable;
  14198. };
  14199. VertexBuffer.prototype.getData = function () {
  14200. return this._data;
  14201. };
  14202. VertexBuffer.prototype.getBuffer = function () {
  14203. return this._buffer;
  14204. };
  14205. VertexBuffer.prototype.getStrideSize = function () {
  14206. return this._strideSize;
  14207. };
  14208. // Methods
  14209. VertexBuffer.prototype.create = function (data) {
  14210. if (!data && this._buffer) {
  14211. return; // nothing to do
  14212. }
  14213. data = data || this._data;
  14214. if (!this._buffer) {
  14215. if (this._updatable) {
  14216. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  14217. }
  14218. else {
  14219. this._buffer = this._engine.createVertexBuffer(data);
  14220. }
  14221. }
  14222. if (this._updatable) {
  14223. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  14224. this._data = data;
  14225. }
  14226. };
  14227. VertexBuffer.prototype.update = function (data) {
  14228. this.create(data);
  14229. };
  14230. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  14231. if (!this._buffer) {
  14232. return;
  14233. }
  14234. if (this._updatable) {
  14235. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  14236. this._data = null;
  14237. }
  14238. };
  14239. VertexBuffer.prototype.dispose = function () {
  14240. if (!this._buffer) {
  14241. return;
  14242. }
  14243. if (this._engine._releaseBuffer(this._buffer)) {
  14244. this._buffer = null;
  14245. }
  14246. };
  14247. Object.defineProperty(VertexBuffer, "PositionKind", {
  14248. get: function () {
  14249. return VertexBuffer._PositionKind;
  14250. },
  14251. enumerable: true,
  14252. configurable: true
  14253. });
  14254. Object.defineProperty(VertexBuffer, "NormalKind", {
  14255. get: function () {
  14256. return VertexBuffer._NormalKind;
  14257. },
  14258. enumerable: true,
  14259. configurable: true
  14260. });
  14261. Object.defineProperty(VertexBuffer, "UVKind", {
  14262. get: function () {
  14263. return VertexBuffer._UVKind;
  14264. },
  14265. enumerable: true,
  14266. configurable: true
  14267. });
  14268. Object.defineProperty(VertexBuffer, "UV2Kind", {
  14269. get: function () {
  14270. return VertexBuffer._UV2Kind;
  14271. },
  14272. enumerable: true,
  14273. configurable: true
  14274. });
  14275. Object.defineProperty(VertexBuffer, "UV3Kind", {
  14276. get: function () {
  14277. return VertexBuffer._UV3Kind;
  14278. },
  14279. enumerable: true,
  14280. configurable: true
  14281. });
  14282. Object.defineProperty(VertexBuffer, "UV4Kind", {
  14283. get: function () {
  14284. return VertexBuffer._UV4Kind;
  14285. },
  14286. enumerable: true,
  14287. configurable: true
  14288. });
  14289. Object.defineProperty(VertexBuffer, "UV5Kind", {
  14290. get: function () {
  14291. return VertexBuffer._UV5Kind;
  14292. },
  14293. enumerable: true,
  14294. configurable: true
  14295. });
  14296. Object.defineProperty(VertexBuffer, "UV6Kind", {
  14297. get: function () {
  14298. return VertexBuffer._UV6Kind;
  14299. },
  14300. enumerable: true,
  14301. configurable: true
  14302. });
  14303. Object.defineProperty(VertexBuffer, "ColorKind", {
  14304. get: function () {
  14305. return VertexBuffer._ColorKind;
  14306. },
  14307. enumerable: true,
  14308. configurable: true
  14309. });
  14310. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  14311. get: function () {
  14312. return VertexBuffer._MatricesIndicesKind;
  14313. },
  14314. enumerable: true,
  14315. configurable: true
  14316. });
  14317. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  14318. get: function () {
  14319. return VertexBuffer._MatricesWeightsKind;
  14320. },
  14321. enumerable: true,
  14322. configurable: true
  14323. });
  14324. // Enums
  14325. VertexBuffer._PositionKind = "position";
  14326. VertexBuffer._NormalKind = "normal";
  14327. VertexBuffer._UVKind = "uv";
  14328. VertexBuffer._UV2Kind = "uv2";
  14329. VertexBuffer._UV3Kind = "uv3";
  14330. VertexBuffer._UV4Kind = "uv4";
  14331. VertexBuffer._UV5Kind = "uv5";
  14332. VertexBuffer._UV6Kind = "uv6";
  14333. VertexBuffer._ColorKind = "color";
  14334. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  14335. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  14336. return VertexBuffer;
  14337. })();
  14338. BABYLON.VertexBuffer = VertexBuffer;
  14339. })(BABYLON || (BABYLON = {}));
  14340. var BABYLON;
  14341. (function (BABYLON) {
  14342. /**
  14343. * Creates an instance based on a source mesh.
  14344. */
  14345. var InstancedMesh = (function (_super) {
  14346. __extends(InstancedMesh, _super);
  14347. function InstancedMesh(name, source) {
  14348. _super.call(this, name, source.getScene());
  14349. source.instances.push(this);
  14350. this._sourceMesh = source;
  14351. this.position.copyFrom(source.position);
  14352. this.rotation.copyFrom(source.rotation);
  14353. this.scaling.copyFrom(source.scaling);
  14354. if (source.rotationQuaternion) {
  14355. this.rotationQuaternion = source.rotationQuaternion.clone();
  14356. }
  14357. this.infiniteDistance = source.infiniteDistance;
  14358. this.setPivotMatrix(source.getPivotMatrix());
  14359. this.refreshBoundingInfo();
  14360. this._syncSubMeshes();
  14361. }
  14362. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  14363. // Methods
  14364. get: function () {
  14365. return this._sourceMesh.receiveShadows;
  14366. },
  14367. enumerable: true,
  14368. configurable: true
  14369. });
  14370. Object.defineProperty(InstancedMesh.prototype, "material", {
  14371. get: function () {
  14372. return this._sourceMesh.material;
  14373. },
  14374. enumerable: true,
  14375. configurable: true
  14376. });
  14377. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  14378. get: function () {
  14379. return this._sourceMesh.visibility;
  14380. },
  14381. enumerable: true,
  14382. configurable: true
  14383. });
  14384. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  14385. get: function () {
  14386. return this._sourceMesh.skeleton;
  14387. },
  14388. enumerable: true,
  14389. configurable: true
  14390. });
  14391. InstancedMesh.prototype.getTotalVertices = function () {
  14392. return this._sourceMesh.getTotalVertices();
  14393. };
  14394. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  14395. get: function () {
  14396. return this._sourceMesh;
  14397. },
  14398. enumerable: true,
  14399. configurable: true
  14400. });
  14401. InstancedMesh.prototype.getVerticesData = function (kind) {
  14402. return this._sourceMesh.getVerticesData(kind);
  14403. };
  14404. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  14405. return this._sourceMesh.isVerticesDataPresent(kind);
  14406. };
  14407. InstancedMesh.prototype.getIndices = function () {
  14408. return this._sourceMesh.getIndices();
  14409. };
  14410. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  14411. get: function () {
  14412. return this._sourceMesh._positions;
  14413. },
  14414. enumerable: true,
  14415. configurable: true
  14416. });
  14417. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14418. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14419. if (data) {
  14420. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14421. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14422. }
  14423. this._updateBoundingInfo();
  14424. };
  14425. InstancedMesh.prototype._preActivate = function () {
  14426. if (this._currentLOD) {
  14427. this._currentLOD._preActivate();
  14428. }
  14429. };
  14430. InstancedMesh.prototype._activate = function (renderId) {
  14431. if (this._currentLOD) {
  14432. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14433. }
  14434. };
  14435. InstancedMesh.prototype.getLOD = function (camera) {
  14436. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14437. if (this._currentLOD === this.sourceMesh) {
  14438. return this;
  14439. }
  14440. return this._currentLOD;
  14441. };
  14442. InstancedMesh.prototype._syncSubMeshes = function () {
  14443. this.releaseSubMeshes();
  14444. if (this._sourceMesh.subMeshes) {
  14445. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14446. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14447. }
  14448. }
  14449. };
  14450. InstancedMesh.prototype._generatePointsArray = function () {
  14451. return this._sourceMesh._generatePointsArray();
  14452. };
  14453. // Clone
  14454. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14455. var result = this._sourceMesh.createInstance(name);
  14456. // Deep copy
  14457. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14458. // Bounding info
  14459. this.refreshBoundingInfo();
  14460. // Parent
  14461. if (newParent) {
  14462. result.parent = newParent;
  14463. }
  14464. if (!doNotCloneChildren) {
  14465. // Children
  14466. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14467. var mesh = this.getScene().meshes[index];
  14468. if (mesh.parent === this) {
  14469. mesh.clone(mesh.name, result);
  14470. }
  14471. }
  14472. }
  14473. result.computeWorldMatrix(true);
  14474. return result;
  14475. };
  14476. // Dispoe
  14477. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14478. // Remove from mesh
  14479. var index = this._sourceMesh.instances.indexOf(this);
  14480. this._sourceMesh.instances.splice(index, 1);
  14481. _super.prototype.dispose.call(this, doNotRecurse);
  14482. };
  14483. return InstancedMesh;
  14484. })(BABYLON.AbstractMesh);
  14485. BABYLON.InstancedMesh = InstancedMesh;
  14486. })(BABYLON || (BABYLON = {}));
  14487. var BABYLON;
  14488. (function (BABYLON) {
  14489. var _InstancesBatch = (function () {
  14490. function _InstancesBatch() {
  14491. this.mustReturn = false;
  14492. this.visibleInstances = new Array();
  14493. this.renderSelf = new Array();
  14494. }
  14495. return _InstancesBatch;
  14496. })();
  14497. BABYLON._InstancesBatch = _InstancesBatch;
  14498. var Mesh = (function (_super) {
  14499. __extends(Mesh, _super);
  14500. /**
  14501. * @constructor
  14502. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14503. * @param {Scene} scene - The scene to add this mesh to.
  14504. * @param {Node} parent - The parent of this mesh, if it has one
  14505. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14506. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14507. * When false, achieved by calling a clone(), also passing False.
  14508. * This will make creation of children, recursive.
  14509. */
  14510. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14511. if (parent === void 0) { parent = null; }
  14512. _super.call(this, name, scene);
  14513. // Members
  14514. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14515. this.instances = new Array();
  14516. this._LODLevels = new Array();
  14517. this._onBeforeRenderCallbacks = new Array();
  14518. this._onAfterRenderCallbacks = new Array();
  14519. this._visibleInstances = {};
  14520. this._renderIdForInstances = new Array();
  14521. this._batchCache = new _InstancesBatch();
  14522. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14523. this._sideOrientation = Mesh._DEFAULTSIDE;
  14524. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14525. if (source) {
  14526. // Geometry
  14527. if (source._geometry) {
  14528. source._geometry.applyToMesh(this);
  14529. }
  14530. // Deep copy
  14531. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14532. // Material
  14533. this.material = source.material;
  14534. if (!doNotCloneChildren) {
  14535. // Children
  14536. for (var index = 0; index < scene.meshes.length; index++) {
  14537. var mesh = scene.meshes[index];
  14538. if (mesh.parent === source) {
  14539. // doNotCloneChildren is always going to be False
  14540. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14541. }
  14542. }
  14543. }
  14544. // Particles
  14545. for (index = 0; index < scene.particleSystems.length; index++) {
  14546. var system = scene.particleSystems[index];
  14547. if (system.emitter === source) {
  14548. system.clone(system.name, this);
  14549. }
  14550. }
  14551. this.computeWorldMatrix(true);
  14552. }
  14553. // Parent
  14554. if (parent !== null) {
  14555. this.parent = parent;
  14556. }
  14557. }
  14558. Object.defineProperty(Mesh, "FRONTSIDE", {
  14559. get: function () {
  14560. return Mesh._FRONTSIDE;
  14561. },
  14562. enumerable: true,
  14563. configurable: true
  14564. });
  14565. Object.defineProperty(Mesh, "BACKSIDE", {
  14566. get: function () {
  14567. return Mesh._BACKSIDE;
  14568. },
  14569. enumerable: true,
  14570. configurable: true
  14571. });
  14572. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14573. get: function () {
  14574. return Mesh._DOUBLESIDE;
  14575. },
  14576. enumerable: true,
  14577. configurable: true
  14578. });
  14579. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14580. get: function () {
  14581. return Mesh._DEFAULTSIDE;
  14582. },
  14583. enumerable: true,
  14584. configurable: true
  14585. });
  14586. Object.defineProperty(Mesh, "NO_CAP", {
  14587. get: function () {
  14588. return Mesh._NO_CAP;
  14589. },
  14590. enumerable: true,
  14591. configurable: true
  14592. });
  14593. Object.defineProperty(Mesh, "CAP_START", {
  14594. get: function () {
  14595. return Mesh._CAP_START;
  14596. },
  14597. enumerable: true,
  14598. configurable: true
  14599. });
  14600. Object.defineProperty(Mesh, "CAP_END", {
  14601. get: function () {
  14602. return Mesh._CAP_END;
  14603. },
  14604. enumerable: true,
  14605. configurable: true
  14606. });
  14607. Object.defineProperty(Mesh, "CAP_ALL", {
  14608. get: function () {
  14609. return Mesh._CAP_ALL;
  14610. },
  14611. enumerable: true,
  14612. configurable: true
  14613. });
  14614. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14615. // Methods
  14616. get: function () {
  14617. return this._LODLevels.length > 0;
  14618. },
  14619. enumerable: true,
  14620. configurable: true
  14621. });
  14622. Mesh.prototype._sortLODLevels = function () {
  14623. this._LODLevels.sort(function (a, b) {
  14624. if (a.distance < b.distance) {
  14625. return 1;
  14626. }
  14627. if (a.distance > b.distance) {
  14628. return -1;
  14629. }
  14630. return 0;
  14631. });
  14632. };
  14633. /**
  14634. * Add a mesh as LOD level triggered at the given distance.
  14635. * @param {number} distance - the distance from the center of the object to show this level
  14636. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14637. * @return {BABYLON.Mesh} this mesh (for chaining)
  14638. */
  14639. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14640. if (mesh && mesh._masterMesh) {
  14641. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14642. return this;
  14643. }
  14644. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14645. this._LODLevels.push(level);
  14646. if (mesh) {
  14647. mesh._masterMesh = this;
  14648. }
  14649. this._sortLODLevels();
  14650. return this;
  14651. };
  14652. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14653. for (var index = 0; index < this._LODLevels.length; index++) {
  14654. var level = this._LODLevels[index];
  14655. if (level.distance === distance) {
  14656. return level.mesh;
  14657. }
  14658. }
  14659. return null;
  14660. };
  14661. /**
  14662. * Remove a mesh from the LOD array
  14663. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14664. * @return {BABYLON.Mesh} this mesh (for chaining)
  14665. */
  14666. Mesh.prototype.removeLODLevel = function (mesh) {
  14667. for (var index = 0; index < this._LODLevels.length; index++) {
  14668. if (this._LODLevels[index].mesh === mesh) {
  14669. this._LODLevels.splice(index, 1);
  14670. if (mesh) {
  14671. mesh._masterMesh = null;
  14672. }
  14673. }
  14674. }
  14675. this._sortLODLevels();
  14676. return this;
  14677. };
  14678. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14679. if (!this._LODLevels || this._LODLevels.length === 0) {
  14680. return this;
  14681. }
  14682. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14683. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14684. if (this.onLODLevelSelection) {
  14685. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14686. }
  14687. return this;
  14688. }
  14689. for (var index = 0; index < this._LODLevels.length; index++) {
  14690. var level = this._LODLevels[index];
  14691. if (level.distance < distanceToCamera) {
  14692. if (level.mesh) {
  14693. level.mesh._preActivate();
  14694. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14695. }
  14696. if (this.onLODLevelSelection) {
  14697. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14698. }
  14699. return level.mesh;
  14700. }
  14701. }
  14702. if (this.onLODLevelSelection) {
  14703. this.onLODLevelSelection(distanceToCamera, this, this);
  14704. }
  14705. return this;
  14706. };
  14707. Object.defineProperty(Mesh.prototype, "geometry", {
  14708. get: function () {
  14709. return this._geometry;
  14710. },
  14711. enumerable: true,
  14712. configurable: true
  14713. });
  14714. Mesh.prototype.getTotalVertices = function () {
  14715. if (!this._geometry) {
  14716. return 0;
  14717. }
  14718. return this._geometry.getTotalVertices();
  14719. };
  14720. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14721. if (!this._geometry) {
  14722. return null;
  14723. }
  14724. return this._geometry.getVerticesData(kind, copyWhenShared);
  14725. };
  14726. Mesh.prototype.getVertexBuffer = function (kind) {
  14727. if (!this._geometry) {
  14728. return undefined;
  14729. }
  14730. return this._geometry.getVertexBuffer(kind);
  14731. };
  14732. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14733. if (!this._geometry) {
  14734. if (this._delayInfo) {
  14735. return this._delayInfo.indexOf(kind) !== -1;
  14736. }
  14737. return false;
  14738. }
  14739. return this._geometry.isVerticesDataPresent(kind);
  14740. };
  14741. Mesh.prototype.getVerticesDataKinds = function () {
  14742. if (!this._geometry) {
  14743. var result = [];
  14744. if (this._delayInfo) {
  14745. for (var kind in this._delayInfo) {
  14746. result.push(kind);
  14747. }
  14748. }
  14749. return result;
  14750. }
  14751. return this._geometry.getVerticesDataKinds();
  14752. };
  14753. Mesh.prototype.getTotalIndices = function () {
  14754. if (!this._geometry) {
  14755. return 0;
  14756. }
  14757. return this._geometry.getTotalIndices();
  14758. };
  14759. Mesh.prototype.getIndices = function (copyWhenShared) {
  14760. if (!this._geometry) {
  14761. return [];
  14762. }
  14763. return this._geometry.getIndices(copyWhenShared);
  14764. };
  14765. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14766. get: function () {
  14767. return this._masterMesh !== null && this._masterMesh !== undefined;
  14768. },
  14769. enumerable: true,
  14770. configurable: true
  14771. });
  14772. Mesh.prototype.isReady = function () {
  14773. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14774. return false;
  14775. }
  14776. return _super.prototype.isReady.call(this);
  14777. };
  14778. Mesh.prototype.isDisposed = function () {
  14779. return this._isDisposed;
  14780. };
  14781. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14782. get: function () {
  14783. return this._sideOrientation;
  14784. },
  14785. set: function (sideO) {
  14786. this._sideOrientation = sideO;
  14787. },
  14788. enumerable: true,
  14789. configurable: true
  14790. });
  14791. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14792. get: function () {
  14793. return this._areNormalsFrozen;
  14794. },
  14795. enumerable: true,
  14796. configurable: true
  14797. });
  14798. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14799. Mesh.prototype.freezeNormals = function () {
  14800. this._areNormalsFrozen = true;
  14801. };
  14802. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14803. Mesh.prototype.unfreezeNormals = function () {
  14804. this._areNormalsFrozen = false;
  14805. };
  14806. // Methods
  14807. Mesh.prototype._preActivate = function () {
  14808. var sceneRenderId = this.getScene().getRenderId();
  14809. if (this._preActivateId === sceneRenderId) {
  14810. return;
  14811. }
  14812. this._preActivateId = sceneRenderId;
  14813. this._visibleInstances = null;
  14814. };
  14815. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14816. if (!this._visibleInstances) {
  14817. this._visibleInstances = {};
  14818. this._visibleInstances.defaultRenderId = renderId;
  14819. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14820. }
  14821. if (!this._visibleInstances[renderId]) {
  14822. this._visibleInstances[renderId] = new Array();
  14823. }
  14824. this._visibleInstances[renderId].push(instance);
  14825. };
  14826. Mesh.prototype.refreshBoundingInfo = function () {
  14827. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14828. if (data) {
  14829. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14830. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14831. }
  14832. if (this.subMeshes) {
  14833. for (var index = 0; index < this.subMeshes.length; index++) {
  14834. this.subMeshes[index].refreshBoundingInfo();
  14835. }
  14836. }
  14837. this._updateBoundingInfo();
  14838. };
  14839. Mesh.prototype._createGlobalSubMesh = function () {
  14840. var totalVertices = this.getTotalVertices();
  14841. if (!totalVertices || !this.getIndices()) {
  14842. return null;
  14843. }
  14844. this.releaseSubMeshes();
  14845. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14846. };
  14847. Mesh.prototype.subdivide = function (count) {
  14848. if (count < 1) {
  14849. return;
  14850. }
  14851. var totalIndices = this.getTotalIndices();
  14852. var subdivisionSize = (totalIndices / count) | 0;
  14853. var offset = 0;
  14854. // Ensure that subdivisionSize is a multiple of 3
  14855. while (subdivisionSize % 3 !== 0) {
  14856. subdivisionSize++;
  14857. }
  14858. this.releaseSubMeshes();
  14859. for (var index = 0; index < count; index++) {
  14860. if (offset >= totalIndices) {
  14861. break;
  14862. }
  14863. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14864. offset += subdivisionSize;
  14865. }
  14866. this.synchronizeInstances();
  14867. };
  14868. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14869. if (kind instanceof Array) {
  14870. var temp = data;
  14871. data = kind;
  14872. kind = temp;
  14873. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14874. }
  14875. if (!this._geometry) {
  14876. var vertexData = new BABYLON.VertexData();
  14877. vertexData.set(data, kind);
  14878. var scene = this.getScene();
  14879. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14880. }
  14881. else {
  14882. this._geometry.setVerticesData(kind, data, updatable, stride);
  14883. }
  14884. };
  14885. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14886. if (!this._geometry) {
  14887. return;
  14888. }
  14889. if (!makeItUnique) {
  14890. this._geometry.updateVerticesData(kind, data, updateExtends);
  14891. }
  14892. else {
  14893. this.makeGeometryUnique();
  14894. this.updateVerticesData(kind, data, updateExtends, false);
  14895. }
  14896. };
  14897. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14898. if (!this._geometry) {
  14899. return;
  14900. }
  14901. if (!makeItUnique) {
  14902. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14903. }
  14904. else {
  14905. this.makeGeometryUnique();
  14906. this.updateVerticesDataDirectly(kind, data, offset, false);
  14907. }
  14908. };
  14909. // Mesh positions update function :
  14910. // updates the mesh positions according to the positionFunction returned values.
  14911. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14912. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14913. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14914. if (computeNormals === void 0) { computeNormals = true; }
  14915. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14916. positionFunction(positions);
  14917. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14918. if (computeNormals) {
  14919. var indices = this.getIndices();
  14920. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14921. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14922. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14923. }
  14924. };
  14925. Mesh.prototype.makeGeometryUnique = function () {
  14926. if (!this._geometry) {
  14927. return;
  14928. }
  14929. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14930. geometry.applyToMesh(this);
  14931. };
  14932. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14933. if (!this._geometry) {
  14934. var vertexData = new BABYLON.VertexData();
  14935. vertexData.indices = indices;
  14936. var scene = this.getScene();
  14937. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14938. }
  14939. else {
  14940. this._geometry.setIndices(indices, totalVertices);
  14941. }
  14942. };
  14943. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14944. var engine = this.getScene().getEngine();
  14945. // Wireframe
  14946. var indexToBind;
  14947. switch (fillMode) {
  14948. case BABYLON.Material.PointFillMode:
  14949. indexToBind = null;
  14950. break;
  14951. case BABYLON.Material.WireFrameFillMode:
  14952. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14953. break;
  14954. default:
  14955. case BABYLON.Material.TriangleFillMode:
  14956. indexToBind = this._geometry.getIndexBuffer();
  14957. break;
  14958. }
  14959. // VBOs
  14960. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14961. };
  14962. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14963. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14964. return;
  14965. }
  14966. var engine = this.getScene().getEngine();
  14967. // Draw order
  14968. switch (fillMode) {
  14969. case BABYLON.Material.PointFillMode:
  14970. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14971. break;
  14972. case BABYLON.Material.WireFrameFillMode:
  14973. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14974. break;
  14975. default:
  14976. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14977. }
  14978. };
  14979. Mesh.prototype.registerBeforeRender = function (func) {
  14980. this._onBeforeRenderCallbacks.push(func);
  14981. };
  14982. Mesh.prototype.unregisterBeforeRender = function (func) {
  14983. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14984. if (index > -1) {
  14985. this._onBeforeRenderCallbacks.splice(index, 1);
  14986. }
  14987. };
  14988. Mesh.prototype.registerAfterRender = function (func) {
  14989. this._onAfterRenderCallbacks.push(func);
  14990. };
  14991. Mesh.prototype.unregisterAfterRender = function (func) {
  14992. var index = this._onAfterRenderCallbacks.indexOf(func);
  14993. if (index > -1) {
  14994. this._onAfterRenderCallbacks.splice(index, 1);
  14995. }
  14996. };
  14997. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14998. var scene = this.getScene();
  14999. this._batchCache.mustReturn = false;
  15000. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  15001. this._batchCache.visibleInstances[subMeshId] = null;
  15002. if (this._visibleInstances) {
  15003. var currentRenderId = scene.getRenderId();
  15004. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  15005. var selfRenderId = this._renderId;
  15006. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  15007. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  15008. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  15009. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  15010. }
  15011. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  15012. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  15013. this._batchCache.mustReturn = true;
  15014. return this._batchCache;
  15015. }
  15016. if (currentRenderId !== selfRenderId) {
  15017. this._batchCache.renderSelf[subMeshId] = false;
  15018. }
  15019. }
  15020. this._renderIdForInstances[subMeshId] = currentRenderId;
  15021. }
  15022. return this._batchCache;
  15023. };
  15024. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  15025. var visibleInstances = batch.visibleInstances[subMesh._id];
  15026. var matricesCount = visibleInstances.length + 1;
  15027. var bufferSize = matricesCount * 16 * 4;
  15028. while (this._instancesBufferSize < bufferSize) {
  15029. this._instancesBufferSize *= 2;
  15030. }
  15031. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  15032. if (this._worldMatricesInstancesBuffer) {
  15033. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15034. }
  15035. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  15036. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  15037. }
  15038. var offset = 0;
  15039. var instancesCount = 0;
  15040. var world = this.getWorldMatrix();
  15041. if (batch.renderSelf[subMesh._id]) {
  15042. world.copyToArray(this._worldMatricesInstancesArray, offset);
  15043. offset += 16;
  15044. instancesCount++;
  15045. }
  15046. if (visibleInstances) {
  15047. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  15048. var instance = visibleInstances[instanceIndex];
  15049. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  15050. offset += 16;
  15051. instancesCount++;
  15052. }
  15053. }
  15054. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  15055. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  15056. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  15057. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  15058. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  15059. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  15060. this._draw(subMesh, fillMode, instancesCount);
  15061. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  15062. };
  15063. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  15064. var scene = this.getScene();
  15065. var engine = scene.getEngine();
  15066. if (hardwareInstancedRendering) {
  15067. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  15068. }
  15069. else {
  15070. if (batch.renderSelf[subMesh._id]) {
  15071. // Draw
  15072. if (onBeforeDraw) {
  15073. onBeforeDraw(false, this.getWorldMatrix());
  15074. }
  15075. this._draw(subMesh, fillMode);
  15076. }
  15077. if (batch.visibleInstances[subMesh._id]) {
  15078. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  15079. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  15080. // World
  15081. var world = instance.getWorldMatrix();
  15082. if (onBeforeDraw) {
  15083. onBeforeDraw(true, world);
  15084. }
  15085. // Draw
  15086. this._draw(subMesh, fillMode);
  15087. }
  15088. }
  15089. }
  15090. };
  15091. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  15092. var scene = this.getScene();
  15093. // Managing instances
  15094. var batch = this._getInstancesRenderList(subMesh._id);
  15095. if (batch.mustReturn) {
  15096. return;
  15097. }
  15098. // Checking geometry state
  15099. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  15100. return;
  15101. }
  15102. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  15103. this._onBeforeRenderCallbacks[callbackIndex](this);
  15104. }
  15105. var engine = scene.getEngine();
  15106. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  15107. // Material
  15108. var effectiveMaterial = subMesh.getMaterial();
  15109. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  15110. return;
  15111. }
  15112. // Outline - step 1
  15113. var savedDepthWrite = engine.getDepthWrite();
  15114. if (this.renderOutline) {
  15115. engine.setDepthWrite(false);
  15116. scene.getOutlineRenderer().render(subMesh, batch);
  15117. engine.setDepthWrite(savedDepthWrite);
  15118. }
  15119. effectiveMaterial._preBind();
  15120. var effect = effectiveMaterial.getEffect();
  15121. // Bind
  15122. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  15123. this._bind(subMesh, effect, fillMode);
  15124. var world = this.getWorldMatrix();
  15125. effectiveMaterial.bind(world, this);
  15126. // Alpha mode
  15127. if (enableAlphaMode) {
  15128. engine.setAlphaMode(effectiveMaterial.alphaMode);
  15129. }
  15130. // Draw
  15131. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  15132. if (isInstance) {
  15133. effectiveMaterial.bindOnlyWorldMatrix(world);
  15134. }
  15135. });
  15136. // Unbind
  15137. effectiveMaterial.unbind();
  15138. // Outline - step 2
  15139. if (this.renderOutline && savedDepthWrite) {
  15140. engine.setDepthWrite(true);
  15141. engine.setColorWrite(false);
  15142. scene.getOutlineRenderer().render(subMesh, batch);
  15143. engine.setColorWrite(true);
  15144. }
  15145. // Overlay
  15146. if (this.renderOverlay) {
  15147. var currentMode = engine.getAlphaMode();
  15148. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15149. scene.getOutlineRenderer().render(subMesh, batch, true);
  15150. engine.setAlphaMode(currentMode);
  15151. }
  15152. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  15153. this._onAfterRenderCallbacks[callbackIndex](this);
  15154. }
  15155. };
  15156. Mesh.prototype.getEmittedParticleSystems = function () {
  15157. var results = new Array();
  15158. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15159. var particleSystem = this.getScene().particleSystems[index];
  15160. if (particleSystem.emitter === this) {
  15161. results.push(particleSystem);
  15162. }
  15163. }
  15164. return results;
  15165. };
  15166. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  15167. var results = new Array();
  15168. var descendants = this.getDescendants();
  15169. descendants.push(this);
  15170. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  15171. var particleSystem = this.getScene().particleSystems[index];
  15172. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  15173. results.push(particleSystem);
  15174. }
  15175. }
  15176. return results;
  15177. };
  15178. Mesh.prototype.getChildren = function () {
  15179. var results = [];
  15180. for (var index = 0; index < this.getScene().meshes.length; index++) {
  15181. var mesh = this.getScene().meshes[index];
  15182. if (mesh.parent === this) {
  15183. results.push(mesh);
  15184. }
  15185. }
  15186. return results;
  15187. };
  15188. Mesh.prototype._checkDelayState = function () {
  15189. var _this = this;
  15190. var that = this;
  15191. var scene = this.getScene();
  15192. if (this._geometry) {
  15193. this._geometry.load(scene);
  15194. }
  15195. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15196. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  15197. scene._addPendingData(that);
  15198. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  15199. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  15200. if (data instanceof ArrayBuffer) {
  15201. _this._delayLoadingFunction(data, _this);
  15202. }
  15203. else {
  15204. _this._delayLoadingFunction(JSON.parse(data), _this);
  15205. }
  15206. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  15207. scene._removePendingData(_this);
  15208. }, function () { }, scene.database, getBinaryData);
  15209. }
  15210. };
  15211. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  15212. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15213. return false;
  15214. }
  15215. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  15216. return false;
  15217. }
  15218. this._checkDelayState();
  15219. return true;
  15220. };
  15221. Mesh.prototype.setMaterialByID = function (id) {
  15222. var materials = this.getScene().materials;
  15223. for (var index = 0; index < materials.length; index++) {
  15224. if (materials[index].id === id) {
  15225. this.material = materials[index];
  15226. return;
  15227. }
  15228. }
  15229. // Multi
  15230. var multiMaterials = this.getScene().multiMaterials;
  15231. for (index = 0; index < multiMaterials.length; index++) {
  15232. if (multiMaterials[index].id === id) {
  15233. this.material = multiMaterials[index];
  15234. return;
  15235. }
  15236. }
  15237. };
  15238. Mesh.prototype.getAnimatables = function () {
  15239. var results = [];
  15240. if (this.material) {
  15241. results.push(this.material);
  15242. }
  15243. if (this.skeleton) {
  15244. results.push(this.skeleton);
  15245. }
  15246. return results;
  15247. };
  15248. // Geometry
  15249. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  15250. // Position
  15251. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  15252. return;
  15253. }
  15254. this._resetPointsArrayCache();
  15255. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15256. var temp = [];
  15257. for (var index = 0; index < data.length; index += 3) {
  15258. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  15259. }
  15260. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  15261. // Normals
  15262. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15263. return;
  15264. }
  15265. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15266. temp = [];
  15267. for (index = 0; index < data.length; index += 3) {
  15268. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  15269. }
  15270. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  15271. // flip faces?
  15272. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  15273. this.flipFaces();
  15274. }
  15275. };
  15276. // Will apply current transform to mesh and reset world matrix
  15277. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  15278. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  15279. this.scaling.copyFromFloats(1, 1, 1);
  15280. this.position.copyFromFloats(0, 0, 0);
  15281. this.rotation.copyFromFloats(0, 0, 0);
  15282. //only if quaternion is already set
  15283. if (this.rotationQuaternion) {
  15284. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  15285. }
  15286. this._worldMatrix = BABYLON.Matrix.Identity();
  15287. };
  15288. // Cache
  15289. Mesh.prototype._resetPointsArrayCache = function () {
  15290. this._positions = null;
  15291. };
  15292. Mesh.prototype._generatePointsArray = function () {
  15293. if (this._positions)
  15294. return true;
  15295. this._positions = [];
  15296. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15297. if (!data) {
  15298. return false;
  15299. }
  15300. for (var index = 0; index < data.length; index += 3) {
  15301. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  15302. }
  15303. return true;
  15304. };
  15305. // Clone
  15306. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15307. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  15308. };
  15309. // Dispose
  15310. Mesh.prototype.dispose = function (doNotRecurse) {
  15311. if (this._geometry) {
  15312. this._geometry.releaseForMesh(this, true);
  15313. }
  15314. // Instances
  15315. if (this._worldMatricesInstancesBuffer) {
  15316. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  15317. this._worldMatricesInstancesBuffer = null;
  15318. }
  15319. while (this.instances.length) {
  15320. this.instances[0].dispose();
  15321. }
  15322. _super.prototype.dispose.call(this, doNotRecurse);
  15323. };
  15324. // Geometric tools
  15325. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  15326. var _this = this;
  15327. var scene = this.getScene();
  15328. var onload = function (img) {
  15329. // Getting height map data
  15330. var canvas = document.createElement("canvas");
  15331. var context = canvas.getContext("2d");
  15332. var heightMapWidth = img.width;
  15333. var heightMapHeight = img.height;
  15334. canvas.width = heightMapWidth;
  15335. canvas.height = heightMapHeight;
  15336. context.drawImage(img, 0, 0);
  15337. // Create VertexData from map data
  15338. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15339. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15340. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  15341. //execute success callback, if set
  15342. if (onSuccess) {
  15343. onSuccess(_this);
  15344. }
  15345. };
  15346. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15347. };
  15348. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  15349. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  15350. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  15351. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15352. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  15353. return;
  15354. }
  15355. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15356. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15357. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15358. var position = BABYLON.Vector3.Zero();
  15359. var normal = BABYLON.Vector3.Zero();
  15360. var uv = BABYLON.Vector2.Zero();
  15361. for (var index = 0; index < positions.length; index += 3) {
  15362. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  15363. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  15364. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  15365. // Compute height
  15366. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  15367. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  15368. var pos = (u + v * heightMapWidth) * 4;
  15369. var r = buffer[pos] / 255.0;
  15370. var g = buffer[pos + 1] / 255.0;
  15371. var b = buffer[pos + 2] / 255.0;
  15372. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  15373. normal.normalize();
  15374. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  15375. position = position.add(normal);
  15376. position.toArray(positions, index);
  15377. }
  15378. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  15379. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  15380. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  15381. };
  15382. Mesh.prototype.convertToFlatShadedMesh = function () {
  15383. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  15384. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  15385. var kinds = this.getVerticesDataKinds();
  15386. var vbs = [];
  15387. var data = [];
  15388. var newdata = [];
  15389. var updatableNormals = false;
  15390. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15391. var kind = kinds[kindIndex];
  15392. var vertexBuffer = this.getVertexBuffer(kind);
  15393. if (kind === BABYLON.VertexBuffer.NormalKind) {
  15394. updatableNormals = vertexBuffer.isUpdatable();
  15395. kinds.splice(kindIndex, 1);
  15396. kindIndex--;
  15397. continue;
  15398. }
  15399. vbs[kind] = vertexBuffer;
  15400. data[kind] = vbs[kind].getData();
  15401. newdata[kind] = [];
  15402. }
  15403. // Save previous submeshes
  15404. var previousSubmeshes = this.subMeshes.slice(0);
  15405. var indices = this.getIndices();
  15406. var totalIndices = this.getTotalIndices();
  15407. // Generating unique vertices per face
  15408. for (var index = 0; index < totalIndices; index++) {
  15409. var vertexIndex = indices[index];
  15410. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15411. kind = kinds[kindIndex];
  15412. var stride = vbs[kind].getStrideSize();
  15413. for (var offset = 0; offset < stride; offset++) {
  15414. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  15415. }
  15416. }
  15417. }
  15418. // Updating faces & normal
  15419. var normals = [];
  15420. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  15421. for (index = 0; index < totalIndices; index += 3) {
  15422. indices[index] = index;
  15423. indices[index + 1] = index + 1;
  15424. indices[index + 2] = index + 2;
  15425. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  15426. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  15427. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  15428. var p1p2 = p1.subtract(p2);
  15429. var p3p2 = p3.subtract(p2);
  15430. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  15431. // Store same normals for every vertex
  15432. for (var localIndex = 0; localIndex < 3; localIndex++) {
  15433. normals.push(normal.x);
  15434. normals.push(normal.y);
  15435. normals.push(normal.z);
  15436. }
  15437. }
  15438. this.setIndices(indices);
  15439. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15440. // Updating vertex buffers
  15441. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15442. kind = kinds[kindIndex];
  15443. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15444. }
  15445. // Updating submeshes
  15446. this.releaseSubMeshes();
  15447. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15448. var previousOne = previousSubmeshes[submeshIndex];
  15449. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15450. }
  15451. this.synchronizeInstances();
  15452. };
  15453. // will inverse faces orientations, and invert normals too if specified
  15454. Mesh.prototype.flipFaces = function (flipNormals) {
  15455. if (flipNormals === void 0) { flipNormals = false; }
  15456. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  15457. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15458. for (var i = 0; i < vertex_data.normals.length; i++) {
  15459. vertex_data.normals[i] *= -1;
  15460. }
  15461. }
  15462. var temp;
  15463. for (var i = 0; i < vertex_data.indices.length; i += 3) {
  15464. // reassign indices
  15465. temp = vertex_data.indices[i + 1];
  15466. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  15467. vertex_data.indices[i + 2] = temp;
  15468. }
  15469. vertex_data.applyToMesh(this);
  15470. };
  15471. // Instances
  15472. Mesh.prototype.createInstance = function (name) {
  15473. return new BABYLON.InstancedMesh(name, this);
  15474. };
  15475. Mesh.prototype.synchronizeInstances = function () {
  15476. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15477. var instance = this.instances[instanceIndex];
  15478. instance._syncSubMeshes();
  15479. }
  15480. };
  15481. /**
  15482. * Simplify the mesh according to the given array of settings.
  15483. * Function will return immediately and will simplify async.
  15484. * @param settings a collection of simplification settings.
  15485. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15486. * @param type the type of simplification to run.
  15487. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15488. */
  15489. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15490. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15491. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15492. this.getScene().simplificationQueue.addTask({
  15493. settings: settings,
  15494. parallelProcessing: parallelProcessing,
  15495. mesh: this,
  15496. simplificationType: simplificationType,
  15497. successCallback: successCallback
  15498. });
  15499. };
  15500. /**
  15501. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15502. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15503. * This should be used together with the simplification to avoid disappearing triangles.
  15504. * @param successCallback an optional success callback to be called after the optimization finished.
  15505. */
  15506. Mesh.prototype.optimizeIndices = function (successCallback) {
  15507. var _this = this;
  15508. var indices = this.getIndices();
  15509. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15510. var vectorPositions = [];
  15511. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15512. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15513. }
  15514. var dupes = [];
  15515. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15516. var realPos = vectorPositions.length - 1 - iteration;
  15517. var testedPosition = vectorPositions[realPos];
  15518. for (var j = 0; j < realPos; ++j) {
  15519. var againstPosition = vectorPositions[j];
  15520. if (testedPosition.equals(againstPosition)) {
  15521. dupes[realPos] = j;
  15522. break;
  15523. }
  15524. }
  15525. }, function () {
  15526. for (var i = 0; i < indices.length; ++i) {
  15527. indices[i] = dupes[indices[i]] || indices[i];
  15528. }
  15529. //indices are now reordered
  15530. var originalSubMeshes = _this.subMeshes.slice(0);
  15531. _this.setIndices(indices);
  15532. _this.subMeshes = originalSubMeshes;
  15533. if (successCallback) {
  15534. successCallback(_this);
  15535. }
  15536. });
  15537. };
  15538. // Statics
  15539. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15540. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15541. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15542. if (ribbonInstance) {
  15543. // positionFunction : ribbon case
  15544. // only pathArray and sideOrientation parameters are taken into account for positions update
  15545. var positionFunction = function (positions) {
  15546. var minlg = pathArray[0].length;
  15547. var i = 0;
  15548. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15549. for (var si = 1; si <= ns; si++) {
  15550. for (var p = 0; p < pathArray.length; p++) {
  15551. var path = pathArray[p];
  15552. var l = path.length;
  15553. minlg = (minlg < l) ? minlg : l;
  15554. var j = 0;
  15555. while (j < minlg) {
  15556. positions[i] = path[j].x;
  15557. positions[i + 1] = path[j].y;
  15558. positions[i + 2] = path[j].z;
  15559. j++;
  15560. i += 3;
  15561. }
  15562. if (ribbonInstance._closePath) {
  15563. positions[i] = path[0].x;
  15564. positions[i + 1] = path[0].y;
  15565. positions[i + 2] = path[0].z;
  15566. i += 3;
  15567. }
  15568. }
  15569. }
  15570. };
  15571. var positions = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15572. positionFunction(positions);
  15573. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  15574. if (!(ribbonInstance.areNormalsFrozen)) {
  15575. var indices = ribbonInstance.getIndices();
  15576. var normals = ribbonInstance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15577. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  15578. if (ribbonInstance._closePath) {
  15579. var indexFirst = 0;
  15580. var indexLast = 0;
  15581. for (var p = 0; p < pathArray.length; p++) {
  15582. indexFirst = ribbonInstance._idx[p] * 3;
  15583. if (p + 1 < pathArray.length) {
  15584. indexLast = (ribbonInstance._idx[p + 1] - 1) * 3;
  15585. }
  15586. else {
  15587. indexLast = normals.length - 3;
  15588. }
  15589. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  15590. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  15591. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  15592. normals[indexLast] = normals[indexFirst];
  15593. normals[indexLast + 1] = normals[indexFirst + 1];
  15594. normals[indexLast + 2] = normals[indexFirst + 2];
  15595. }
  15596. }
  15597. ribbonInstance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  15598. }
  15599. return ribbonInstance;
  15600. }
  15601. else {
  15602. var ribbon = new Mesh(name, scene);
  15603. ribbon.sideOrientation = sideOrientation;
  15604. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15605. if (closePath) {
  15606. ribbon._idx = vertexData._idx;
  15607. }
  15608. ribbon._closePath = closePath;
  15609. vertexData.applyToMesh(ribbon, updatable);
  15610. return ribbon;
  15611. }
  15612. };
  15613. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15614. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15615. var disc = new Mesh(name, scene);
  15616. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15617. vertexData.applyToMesh(disc, updatable);
  15618. return disc;
  15619. };
  15620. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15621. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15622. var box = new Mesh(name, scene);
  15623. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15624. vertexData.applyToMesh(box, updatable);
  15625. return box;
  15626. };
  15627. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15628. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15629. var sphere = new Mesh(name, scene);
  15630. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15631. vertexData.applyToMesh(sphere, updatable);
  15632. return sphere;
  15633. };
  15634. // Cylinder and cone
  15635. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15636. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15637. // subdivisions is a new parameter, we need to support old signature
  15638. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15639. if (scene !== undefined) {
  15640. updatable = scene;
  15641. }
  15642. scene = subdivisions;
  15643. subdivisions = 1;
  15644. }
  15645. var cylinder = new Mesh(name, scene);
  15646. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation);
  15647. vertexData.applyToMesh(cylinder, updatable);
  15648. return cylinder;
  15649. };
  15650. // Torus (Code from SharpDX.org)
  15651. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15652. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15653. var torus = new Mesh(name, scene);
  15654. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15655. vertexData.applyToMesh(torus, updatable);
  15656. return torus;
  15657. };
  15658. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15659. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15660. var torusKnot = new Mesh(name, scene);
  15661. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15662. vertexData.applyToMesh(torusKnot, updatable);
  15663. return torusKnot;
  15664. };
  15665. // Lines
  15666. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15667. if (linesInstance === void 0) { linesInstance = null; }
  15668. if (linesInstance) {
  15669. var positionFunction = function (positions) {
  15670. var i = 0;
  15671. for (var p = 0; p < points.length; p++) {
  15672. positions[i] = points[p].x;
  15673. positions[i + 1] = points[p].y;
  15674. positions[i + 2] = points[p].z;
  15675. i += 3;
  15676. }
  15677. };
  15678. linesInstance.updateMeshPositions(positionFunction, false);
  15679. return linesInstance;
  15680. }
  15681. // lines creation
  15682. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15683. var vertexData = BABYLON.VertexData.CreateLines(points);
  15684. vertexData.applyToMesh(lines, updatable);
  15685. return lines;
  15686. };
  15687. // Dashed Lines
  15688. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15689. if (linesInstance === void 0) { linesInstance = null; }
  15690. if (linesInstance) {
  15691. var positionFunction = function (positions) {
  15692. var curvect = BABYLON.Vector3.Zero();
  15693. var nbSeg = positions.length / 6;
  15694. var lg = 0;
  15695. var nb = 0;
  15696. var shft = 0;
  15697. var dashshft = 0;
  15698. var curshft = 0;
  15699. var p = 0;
  15700. var i = 0;
  15701. var j = 0;
  15702. for (i = 0; i < points.length - 1; i++) {
  15703. points[i + 1].subtractToRef(points[i], curvect);
  15704. lg += curvect.length();
  15705. }
  15706. shft = lg / nbSeg;
  15707. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15708. for (i = 0; i < points.length - 1; i++) {
  15709. points[i + 1].subtractToRef(points[i], curvect);
  15710. nb = Math.floor(curvect.length() / shft);
  15711. curvect.normalize();
  15712. j = 0;
  15713. while (j < nb && p < positions.length) {
  15714. curshft = shft * j;
  15715. positions[p] = points[i].x + curshft * curvect.x;
  15716. positions[p + 1] = points[i].y + curshft * curvect.y;
  15717. positions[p + 2] = points[i].z + curshft * curvect.z;
  15718. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15719. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15720. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15721. p += 6;
  15722. j++;
  15723. }
  15724. }
  15725. while (p < positions.length) {
  15726. positions[p] = points[i].x;
  15727. positions[p + 1] = points[i].y;
  15728. positions[p + 2] = points[i].z;
  15729. p += 3;
  15730. }
  15731. };
  15732. linesInstance.updateMeshPositions(positionFunction, false);
  15733. return linesInstance;
  15734. }
  15735. // dashed lines creation
  15736. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15737. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15738. vertexData.applyToMesh(dashedLines, updatable);
  15739. dashedLines.dashSize = dashSize;
  15740. dashedLines.gapSize = gapSize;
  15741. return dashedLines;
  15742. };
  15743. // Extrusion
  15744. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15745. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15746. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15747. scale = scale || 1;
  15748. rotation = rotation || 0;
  15749. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15750. return extruded;
  15751. };
  15752. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15753. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15754. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15755. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15756. return extrudedCustom;
  15757. };
  15758. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15759. // extrusion geometry
  15760. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15761. var tangents = path3D.getTangents();
  15762. var normals = path3D.getNormals();
  15763. var binormals = path3D.getBinormals();
  15764. var distances = path3D.getDistances();
  15765. var angle = 0;
  15766. var returnScale = function (i, distance) { return scale; };
  15767. var returnRotation = function (i, distance) { return rotation; };
  15768. var rotate = custom ? rotateFunction : returnRotation;
  15769. var scl = custom ? scaleFunction : returnScale;
  15770. var index = 0;
  15771. for (var i = 0; i < curve.length; i++) {
  15772. var shapePath = new Array();
  15773. var angleStep = rotate(i, distances[i]);
  15774. var scaleRatio = scl(i, distances[i]);
  15775. for (var p = 0; p < shape.length; p++) {
  15776. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15777. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15778. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15779. shapePath.push(rotated);
  15780. }
  15781. shapePaths[index] = shapePath;
  15782. angle += angleStep;
  15783. index++;
  15784. }
  15785. // cap
  15786. var capPath = function (shapePath) {
  15787. var pointCap = Array();
  15788. var barycenter = BABYLON.Vector3.Zero();
  15789. var i;
  15790. for (i = 0; i < shapePath.length; i++) {
  15791. barycenter.addInPlace(shapePath[i]);
  15792. }
  15793. barycenter.scaleInPlace(1 / shapePath.length);
  15794. for (i = 0; i < shapePath.length; i++) {
  15795. pointCap.push(barycenter);
  15796. }
  15797. return pointCap;
  15798. };
  15799. switch (cap) {
  15800. case Mesh.NO_CAP:
  15801. break;
  15802. case Mesh.CAP_START:
  15803. shapePaths.unshift(capPath(shapePaths[0]));
  15804. break;
  15805. case Mesh.CAP_END:
  15806. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15807. break;
  15808. case Mesh.CAP_ALL:
  15809. shapePaths.unshift(capPath(shapePaths[0]));
  15810. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15811. break;
  15812. default:
  15813. break;
  15814. }
  15815. return shapePaths;
  15816. };
  15817. var path3D;
  15818. var pathArray;
  15819. if (instance) {
  15820. path3D = (instance.path3D).update(curve);
  15821. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15822. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15823. return instance;
  15824. }
  15825. // extruded shape creation
  15826. path3D = new BABYLON.Path3D(curve);
  15827. var newShapePaths = new Array();
  15828. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15829. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15830. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15831. extrudedGeneric.pathArray = pathArray;
  15832. extrudedGeneric.path3D = path3D;
  15833. extrudedGeneric.cap = cap;
  15834. return extrudedGeneric;
  15835. };
  15836. // Lathe
  15837. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15838. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15839. radius = radius || 1;
  15840. tessellation = tessellation || radius * 60;
  15841. var pi2 = Math.PI * 2;
  15842. var Y = BABYLON.Axis.Y;
  15843. var shapeLathe = new Array();
  15844. // first rotatable point
  15845. var i = 0;
  15846. while (shape[i].x === 0) {
  15847. i++;
  15848. }
  15849. var pt = shape[i];
  15850. for (i = 0; i < shape.length; i++) {
  15851. shapeLathe.push(shape[i].subtract(pt));
  15852. }
  15853. // circle path
  15854. var step = pi2 / tessellation;
  15855. var rotated;
  15856. var path = new Array();
  15857. ;
  15858. for (i = 0; i < tessellation; i++) {
  15859. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15860. path.push(rotated);
  15861. }
  15862. path.push(path[0]);
  15863. // extrusion
  15864. var scaleFunction = function () { return 1; };
  15865. var rotateFunction = function () { return 0; };
  15866. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15867. return lathe;
  15868. };
  15869. // Plane & ground
  15870. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15871. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15872. var plane = new Mesh(name, scene);
  15873. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15874. vertexData.applyToMesh(plane, updatable);
  15875. return plane;
  15876. };
  15877. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15878. var ground = new BABYLON.GroundMesh(name, scene);
  15879. ground._setReady(false);
  15880. ground._subdivisions = subdivisions;
  15881. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15882. vertexData.applyToMesh(ground, updatable);
  15883. ground._setReady(true);
  15884. return ground;
  15885. };
  15886. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15887. var tiledGround = new Mesh(name, scene);
  15888. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15889. vertexData.applyToMesh(tiledGround, updatable);
  15890. return tiledGround;
  15891. };
  15892. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15893. var ground = new BABYLON.GroundMesh(name, scene);
  15894. ground._subdivisions = subdivisions;
  15895. ground._setReady(false);
  15896. var onload = function (img) {
  15897. // Getting height map data
  15898. var canvas = document.createElement("canvas");
  15899. var context = canvas.getContext("2d");
  15900. var heightMapWidth = img.width;
  15901. var heightMapHeight = img.height;
  15902. canvas.width = heightMapWidth;
  15903. canvas.height = heightMapHeight;
  15904. context.drawImage(img, 0, 0);
  15905. // Create VertexData from map data
  15906. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15907. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15908. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15909. vertexData.applyToMesh(ground, updatable);
  15910. ground._setReady(true);
  15911. //execute ready callback, if set
  15912. if (onReady) {
  15913. onReady(ground);
  15914. }
  15915. };
  15916. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15917. return ground;
  15918. };
  15919. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15920. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15921. if (tubeInstance === void 0) { tubeInstance = null; }
  15922. // tube geometry
  15923. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15924. var tangents = path3D.getTangents();
  15925. var normals = path3D.getNormals();
  15926. var distances = path3D.getDistances();
  15927. var pi2 = Math.PI * 2;
  15928. var step = pi2 / tessellation;
  15929. var returnRadius = function (i, distance) { return radius; };
  15930. var radiusFunctionFinal = radiusFunction || returnRadius;
  15931. var circlePath;
  15932. var rad;
  15933. var normal;
  15934. var rotated;
  15935. var rotationMatrix;
  15936. var index = 0;
  15937. for (var i = 0; i < path.length; i++) {
  15938. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15939. circlePath = Array(); // current circle array
  15940. normal = normals[i]; // current normal
  15941. for (var t = 0; t < tessellation; t++) {
  15942. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15943. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15944. circlePath.push(rotated);
  15945. }
  15946. circlePaths[index] = circlePath;
  15947. index++;
  15948. }
  15949. // cap
  15950. var capPath = function (nbPoints, pathIndex) {
  15951. var pointCap = Array();
  15952. for (var i = 0; i < nbPoints; i++) {
  15953. pointCap.push(path[pathIndex]);
  15954. }
  15955. return pointCap;
  15956. };
  15957. switch (cap) {
  15958. case Mesh.NO_CAP:
  15959. break;
  15960. case Mesh.CAP_START:
  15961. circlePaths.unshift(capPath(tessellation + 1, 0));
  15962. break;
  15963. case Mesh.CAP_END:
  15964. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15965. break;
  15966. case Mesh.CAP_ALL:
  15967. circlePaths.unshift(capPath(tessellation + 1, 0));
  15968. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15969. break;
  15970. default:
  15971. break;
  15972. }
  15973. return circlePaths;
  15974. };
  15975. var path3D;
  15976. var pathArray;
  15977. if (tubeInstance) {
  15978. path3D = (tubeInstance.path3D).update(path);
  15979. pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15980. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15981. return tubeInstance;
  15982. }
  15983. // tube creation
  15984. path3D = new BABYLON.Path3D(path);
  15985. var newPathArray = new Array();
  15986. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15987. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15988. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15989. tube.pathArray = pathArray;
  15990. tube.path3D = path3D;
  15991. tube.tessellation = tessellation;
  15992. tube.cap = cap;
  15993. return tube;
  15994. };
  15995. // Decals
  15996. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15997. if (angle === void 0) { angle = 0; }
  15998. var indices = sourceMesh.getIndices();
  15999. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16000. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16001. // Getting correct rotation
  16002. if (!normal) {
  16003. var target = new BABYLON.Vector3(0, 0, 1);
  16004. var camera = sourceMesh.getScene().activeCamera;
  16005. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  16006. normal = camera.globalPosition.subtract(cameraWorldTarget);
  16007. }
  16008. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  16009. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  16010. var pitch = Math.atan2(normal.y, len);
  16011. // Matrix
  16012. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  16013. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  16014. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  16015. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  16016. var vertexData = new BABYLON.VertexData();
  16017. vertexData.indices = [];
  16018. vertexData.positions = [];
  16019. vertexData.normals = [];
  16020. vertexData.uvs = [];
  16021. var currentVertexDataIndex = 0;
  16022. var extractDecalVector3 = function (indexId) {
  16023. var vertexId = indices[indexId];
  16024. var result = new BABYLON.PositionNormalVertex();
  16025. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  16026. // Send vector to decal local world
  16027. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  16028. // Get normal
  16029. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  16030. return result;
  16031. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  16032. var clip = function (vertices, axis) {
  16033. if (vertices.length === 0) {
  16034. return vertices;
  16035. }
  16036. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  16037. var clipVertices = function (v0, v1) {
  16038. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  16039. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  16040. };
  16041. var result = new Array();
  16042. for (var index = 0; index < vertices.length; index += 3) {
  16043. var v1Out;
  16044. var v2Out;
  16045. var v3Out;
  16046. var total = 0;
  16047. var nV1, nV2, nV3, nV4;
  16048. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  16049. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  16050. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  16051. v1Out = d1 > 0;
  16052. v2Out = d2 > 0;
  16053. v3Out = d3 > 0;
  16054. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  16055. switch (total) {
  16056. case 0:
  16057. result.push(vertices[index]);
  16058. result.push(vertices[index + 1]);
  16059. result.push(vertices[index + 2]);
  16060. break;
  16061. case 1:
  16062. if (v1Out) {
  16063. nV1 = vertices[index + 1];
  16064. nV2 = vertices[index + 2];
  16065. nV3 = clipVertices(vertices[index], nV1);
  16066. nV4 = clipVertices(vertices[index], nV2);
  16067. }
  16068. if (v2Out) {
  16069. nV1 = vertices[index];
  16070. nV2 = vertices[index + 2];
  16071. nV3 = clipVertices(vertices[index + 1], nV1);
  16072. nV4 = clipVertices(vertices[index + 1], nV2);
  16073. result.push(nV3);
  16074. result.push(nV2.clone());
  16075. result.push(nV1.clone());
  16076. result.push(nV2.clone());
  16077. result.push(nV3.clone());
  16078. result.push(nV4);
  16079. break;
  16080. }
  16081. if (v3Out) {
  16082. nV1 = vertices[index];
  16083. nV2 = vertices[index + 1];
  16084. nV3 = clipVertices(vertices[index + 2], nV1);
  16085. nV4 = clipVertices(vertices[index + 2], nV2);
  16086. }
  16087. result.push(nV1.clone());
  16088. result.push(nV2.clone());
  16089. result.push(nV3);
  16090. result.push(nV4);
  16091. result.push(nV3.clone());
  16092. result.push(nV2.clone());
  16093. break;
  16094. case 2:
  16095. if (!v1Out) {
  16096. nV1 = vertices[index].clone();
  16097. nV2 = clipVertices(nV1, vertices[index + 1]);
  16098. nV3 = clipVertices(nV1, vertices[index + 2]);
  16099. result.push(nV1);
  16100. result.push(nV2);
  16101. result.push(nV3);
  16102. }
  16103. if (!v2Out) {
  16104. nV1 = vertices[index + 1].clone();
  16105. nV2 = clipVertices(nV1, vertices[index + 2]);
  16106. nV3 = clipVertices(nV1, vertices[index]);
  16107. result.push(nV1);
  16108. result.push(nV2);
  16109. result.push(nV3);
  16110. }
  16111. if (!v3Out) {
  16112. nV1 = vertices[index + 2].clone();
  16113. nV2 = clipVertices(nV1, vertices[index]);
  16114. nV3 = clipVertices(nV1, vertices[index + 1]);
  16115. result.push(nV1);
  16116. result.push(nV2);
  16117. result.push(nV3);
  16118. }
  16119. break;
  16120. case 3:
  16121. break;
  16122. }
  16123. }
  16124. return result;
  16125. };
  16126. for (var index = 0; index < indices.length; index += 3) {
  16127. var faceVertices = new Array();
  16128. faceVertices.push(extractDecalVector3(index));
  16129. faceVertices.push(extractDecalVector3(index + 1));
  16130. faceVertices.push(extractDecalVector3(index + 2));
  16131. // Clip
  16132. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  16133. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  16134. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  16135. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  16136. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  16137. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  16138. if (faceVertices.length === 0) {
  16139. continue;
  16140. }
  16141. // Add UVs and get back to world
  16142. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  16143. var vertex = faceVertices[vIndex];
  16144. vertexData.indices.push(currentVertexDataIndex);
  16145. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  16146. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  16147. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  16148. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  16149. currentVertexDataIndex++;
  16150. }
  16151. }
  16152. // Return mesh
  16153. var decal = new Mesh(name, sourceMesh.getScene());
  16154. vertexData.applyToMesh(decal);
  16155. decal.position = position.clone();
  16156. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  16157. return decal;
  16158. };
  16159. // Skeletons
  16160. /**
  16161. * Update the vertex buffers by applying transformation from the bones
  16162. * @param {skeleton} skeleton to apply
  16163. */
  16164. Mesh.prototype.applySkeleton = function (skeleton) {
  16165. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16166. return this;
  16167. }
  16168. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16169. return this;
  16170. }
  16171. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16172. return this;
  16173. }
  16174. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16175. return this;
  16176. }
  16177. var source;
  16178. if (!this._sourcePositions) {
  16179. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16180. this._sourcePositions = new Float32Array(source);
  16181. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  16182. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  16183. }
  16184. }
  16185. if (!this._sourceNormals) {
  16186. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16187. this._sourceNormals = new Float32Array(source);
  16188. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  16189. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  16190. }
  16191. }
  16192. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16193. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16194. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16195. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16196. var skeletonMatrices = skeleton.getTransformMatrices();
  16197. var tempVector3 = BABYLON.Vector3.Zero();
  16198. var finalMatrix = new BABYLON.Matrix();
  16199. var tempMatrix = new BABYLON.Matrix();
  16200. for (var index = 0; index < positionsData.length; index += 3) {
  16201. var index4 = (index / 3) * 4;
  16202. var matricesWeight0 = matricesWeightsData[index4];
  16203. var matricesWeight1 = matricesWeightsData[index4 + 1];
  16204. var matricesWeight2 = matricesWeightsData[index4 + 2];
  16205. var matricesWeight3 = matricesWeightsData[index4 + 3];
  16206. if (matricesWeight0 > 0) {
  16207. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4] * 16, matricesWeight0, tempMatrix);
  16208. finalMatrix.addToSelf(tempMatrix);
  16209. }
  16210. if (matricesWeight1 > 0) {
  16211. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 1] * 16, matricesWeight1, tempMatrix);
  16212. finalMatrix.addToSelf(tempMatrix);
  16213. }
  16214. if (matricesWeight2 > 0) {
  16215. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 2] * 16, matricesWeight2, tempMatrix);
  16216. finalMatrix.addToSelf(tempMatrix);
  16217. }
  16218. if (matricesWeight3 > 0) {
  16219. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[index4 + 3] * 16, matricesWeight3, tempMatrix);
  16220. finalMatrix.addToSelf(tempMatrix);
  16221. }
  16222. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  16223. tempVector3.toArray(positionsData, index);
  16224. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  16225. tempVector3.toArray(normalsData, index);
  16226. finalMatrix.reset();
  16227. }
  16228. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  16229. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  16230. return this;
  16231. };
  16232. // Tools
  16233. Mesh.MinMax = function (meshes) {
  16234. var minVector = null;
  16235. var maxVector = null;
  16236. for (var i in meshes) {
  16237. var mesh = meshes[i];
  16238. var boundingBox = mesh.getBoundingInfo().boundingBox;
  16239. if (!minVector) {
  16240. minVector = boundingBox.minimumWorld;
  16241. maxVector = boundingBox.maximumWorld;
  16242. continue;
  16243. }
  16244. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  16245. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  16246. }
  16247. return {
  16248. min: minVector,
  16249. max: maxVector
  16250. };
  16251. };
  16252. Mesh.Center = function (meshesOrMinMaxVector) {
  16253. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  16254. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  16255. };
  16256. /**
  16257. * Merge the array of meshes into a single mesh for performance reasons.
  16258. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  16259. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  16260. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  16261. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  16262. */
  16263. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  16264. if (disposeSource === void 0) { disposeSource = true; }
  16265. var index;
  16266. if (!allow32BitsIndices) {
  16267. var totalVertices = 0;
  16268. // Counting vertices
  16269. for (index = 0; index < meshes.length; index++) {
  16270. if (meshes[index]) {
  16271. totalVertices += meshes[index].getTotalVertices();
  16272. if (totalVertices > 65536) {
  16273. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  16274. return null;
  16275. }
  16276. }
  16277. }
  16278. }
  16279. // Merge
  16280. var vertexData;
  16281. var otherVertexData;
  16282. var source;
  16283. for (index = 0; index < meshes.length; index++) {
  16284. if (meshes[index]) {
  16285. meshes[index].computeWorldMatrix(true);
  16286. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  16287. otherVertexData.transform(meshes[index].getWorldMatrix());
  16288. if (vertexData) {
  16289. vertexData.merge(otherVertexData);
  16290. }
  16291. else {
  16292. vertexData = otherVertexData;
  16293. source = meshes[index];
  16294. }
  16295. }
  16296. }
  16297. if (!meshSubclass) {
  16298. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  16299. }
  16300. vertexData.applyToMesh(meshSubclass);
  16301. // Setting properties
  16302. meshSubclass.material = source.material;
  16303. meshSubclass.checkCollisions = source.checkCollisions;
  16304. // Cleaning
  16305. if (disposeSource) {
  16306. for (index = 0; index < meshes.length; index++) {
  16307. if (meshes[index]) {
  16308. meshes[index].dispose();
  16309. }
  16310. }
  16311. }
  16312. return meshSubclass;
  16313. };
  16314. // Consts
  16315. Mesh._FRONTSIDE = 0;
  16316. Mesh._BACKSIDE = 1;
  16317. Mesh._DOUBLESIDE = 2;
  16318. Mesh._DEFAULTSIDE = 0;
  16319. Mesh._NO_CAP = 0;
  16320. Mesh._CAP_START = 1;
  16321. Mesh._CAP_END = 2;
  16322. Mesh._CAP_ALL = 3;
  16323. return Mesh;
  16324. })(BABYLON.AbstractMesh);
  16325. BABYLON.Mesh = Mesh;
  16326. })(BABYLON || (BABYLON = {}));
  16327. var BABYLON;
  16328. (function (BABYLON) {
  16329. var SubMesh = (function () {
  16330. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  16331. if (createBoundingBox === void 0) { createBoundingBox = true; }
  16332. this.materialIndex = materialIndex;
  16333. this.verticesStart = verticesStart;
  16334. this.verticesCount = verticesCount;
  16335. this.indexStart = indexStart;
  16336. this.indexCount = indexCount;
  16337. this._renderId = 0;
  16338. this._mesh = mesh;
  16339. this._renderingMesh = renderingMesh || mesh;
  16340. mesh.subMeshes.push(this);
  16341. this._trianglePlanes = [];
  16342. this._id = mesh.subMeshes.length - 1;
  16343. if (createBoundingBox) {
  16344. this.refreshBoundingInfo();
  16345. mesh.computeWorldMatrix(true);
  16346. }
  16347. }
  16348. SubMesh.prototype.getBoundingInfo = function () {
  16349. return this._boundingInfo;
  16350. };
  16351. SubMesh.prototype.getMesh = function () {
  16352. return this._mesh;
  16353. };
  16354. SubMesh.prototype.getRenderingMesh = function () {
  16355. return this._renderingMesh;
  16356. };
  16357. SubMesh.prototype.getMaterial = function () {
  16358. var rootMaterial = this._renderingMesh.material;
  16359. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  16360. var multiMaterial = rootMaterial;
  16361. return multiMaterial.getSubMaterial(this.materialIndex);
  16362. }
  16363. if (!rootMaterial) {
  16364. return this._mesh.getScene().defaultMaterial;
  16365. }
  16366. return rootMaterial;
  16367. };
  16368. // Methods
  16369. SubMesh.prototype.refreshBoundingInfo = function () {
  16370. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16371. if (!data) {
  16372. this._boundingInfo = this._mesh._boundingInfo;
  16373. return;
  16374. }
  16375. var indices = this._renderingMesh.getIndices();
  16376. var extend;
  16377. if (this.indexStart === 0 && this.indexCount === indices.length) {
  16378. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  16379. }
  16380. else {
  16381. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  16382. }
  16383. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  16384. };
  16385. SubMesh.prototype._checkCollision = function (collider) {
  16386. return this._boundingInfo._checkCollision(collider);
  16387. };
  16388. SubMesh.prototype.updateBoundingInfo = function (world) {
  16389. if (!this._boundingInfo) {
  16390. this.refreshBoundingInfo();
  16391. }
  16392. this._boundingInfo._update(world);
  16393. };
  16394. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  16395. return this._boundingInfo.isInFrustum(frustumPlanes);
  16396. };
  16397. SubMesh.prototype.render = function (enableAlphaMode) {
  16398. this._renderingMesh.render(this, enableAlphaMode);
  16399. };
  16400. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  16401. if (!this._linesIndexBuffer) {
  16402. var linesIndices = [];
  16403. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16404. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  16405. }
  16406. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  16407. this.linesIndexCount = linesIndices.length;
  16408. }
  16409. return this._linesIndexBuffer;
  16410. };
  16411. SubMesh.prototype.canIntersects = function (ray) {
  16412. return ray.intersectsBox(this._boundingInfo.boundingBox);
  16413. };
  16414. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  16415. var intersectInfo = null;
  16416. // Triangles test
  16417. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  16418. var p0 = positions[indices[index]];
  16419. var p1 = positions[indices[index + 1]];
  16420. var p2 = positions[indices[index + 2]];
  16421. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  16422. if (currentIntersectInfo) {
  16423. if (currentIntersectInfo.distance < 0) {
  16424. continue;
  16425. }
  16426. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16427. intersectInfo = currentIntersectInfo;
  16428. intersectInfo.faceId = index / 3;
  16429. if (fastCheck) {
  16430. break;
  16431. }
  16432. }
  16433. }
  16434. }
  16435. return intersectInfo;
  16436. };
  16437. // Clone
  16438. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  16439. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  16440. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  16441. return result;
  16442. };
  16443. // Dispose
  16444. SubMesh.prototype.dispose = function () {
  16445. if (this._linesIndexBuffer) {
  16446. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  16447. this._linesIndexBuffer = null;
  16448. }
  16449. // Remove from mesh
  16450. var index = this._mesh.subMeshes.indexOf(this);
  16451. this._mesh.subMeshes.splice(index, 1);
  16452. };
  16453. // Statics
  16454. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  16455. var minVertexIndex = Number.MAX_VALUE;
  16456. var maxVertexIndex = -Number.MAX_VALUE;
  16457. renderingMesh = renderingMesh || mesh;
  16458. var indices = renderingMesh.getIndices();
  16459. for (var index = startIndex; index < startIndex + indexCount; index++) {
  16460. var vertexIndex = indices[index];
  16461. if (vertexIndex < minVertexIndex)
  16462. minVertexIndex = vertexIndex;
  16463. if (vertexIndex > maxVertexIndex)
  16464. maxVertexIndex = vertexIndex;
  16465. }
  16466. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  16467. };
  16468. return SubMesh;
  16469. })();
  16470. BABYLON.SubMesh = SubMesh;
  16471. })(BABYLON || (BABYLON = {}));
  16472. var BABYLON;
  16473. (function (BABYLON) {
  16474. var BaseTexture = (function () {
  16475. function BaseTexture(scene) {
  16476. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16477. this.hasAlpha = false;
  16478. this.getAlphaFromRGB = false;
  16479. this.level = 1;
  16480. this.isCube = false;
  16481. this.isRenderTarget = false;
  16482. this.animations = new Array();
  16483. this.coordinatesIndex = 0;
  16484. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  16485. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16486. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16487. this.anisotropicFilteringLevel = 4;
  16488. this._scene = scene;
  16489. this._scene.textures.push(this);
  16490. }
  16491. BaseTexture.prototype.getScene = function () {
  16492. return this._scene;
  16493. };
  16494. BaseTexture.prototype.getTextureMatrix = function () {
  16495. return null;
  16496. };
  16497. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  16498. return null;
  16499. };
  16500. BaseTexture.prototype.getInternalTexture = function () {
  16501. return this._texture;
  16502. };
  16503. BaseTexture.prototype.isReady = function () {
  16504. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16505. return true;
  16506. }
  16507. if (this._texture) {
  16508. return this._texture.isReady;
  16509. }
  16510. return false;
  16511. };
  16512. BaseTexture.prototype.getSize = function () {
  16513. if (this._texture._width) {
  16514. return { width: this._texture._width, height: this._texture._height };
  16515. }
  16516. if (this._texture._size) {
  16517. return { width: this._texture._size, height: this._texture._size };
  16518. }
  16519. return { width: 0, height: 0 };
  16520. };
  16521. BaseTexture.prototype.getBaseSize = function () {
  16522. if (!this.isReady())
  16523. return { width: 0, height: 0 };
  16524. if (this._texture._size) {
  16525. return { width: this._texture._size, height: this._texture._size };
  16526. }
  16527. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  16528. };
  16529. BaseTexture.prototype.scale = function (ratio) {
  16530. };
  16531. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  16532. get: function () {
  16533. return false;
  16534. },
  16535. enumerable: true,
  16536. configurable: true
  16537. });
  16538. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  16539. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16540. for (var index = 0; index < texturesCache.length; index++) {
  16541. var texturesCacheEntry = texturesCache[index];
  16542. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16543. texturesCache.splice(index, 1);
  16544. return;
  16545. }
  16546. }
  16547. };
  16548. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  16549. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16550. for (var index = 0; index < texturesCache.length; index++) {
  16551. var texturesCacheEntry = texturesCache[index];
  16552. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  16553. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  16554. texturesCacheEntry.references++;
  16555. return texturesCacheEntry;
  16556. }
  16557. }
  16558. }
  16559. return null;
  16560. };
  16561. BaseTexture.prototype.delayLoad = function () {
  16562. };
  16563. BaseTexture.prototype.releaseInternalTexture = function () {
  16564. if (!this._texture) {
  16565. return;
  16566. }
  16567. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16568. this._texture.references--;
  16569. // Final reference ?
  16570. if (this._texture.references === 0) {
  16571. var index = texturesCache.indexOf(this._texture);
  16572. texturesCache.splice(index, 1);
  16573. this._scene.getEngine()._releaseTexture(this._texture);
  16574. delete this._texture;
  16575. }
  16576. };
  16577. BaseTexture.prototype.clone = function () {
  16578. return null;
  16579. };
  16580. BaseTexture.prototype.dispose = function () {
  16581. // Remove from scene
  16582. var index = this._scene.textures.indexOf(this);
  16583. if (index >= 0) {
  16584. this._scene.textures.splice(index, 1);
  16585. }
  16586. if (this._texture === undefined) {
  16587. return;
  16588. }
  16589. this.releaseInternalTexture();
  16590. // Callback
  16591. if (this.onDispose) {
  16592. this.onDispose();
  16593. }
  16594. };
  16595. return BaseTexture;
  16596. })();
  16597. BABYLON.BaseTexture = BaseTexture;
  16598. })(BABYLON || (BABYLON = {}));
  16599. var BABYLON;
  16600. (function (BABYLON) {
  16601. var Texture = (function (_super) {
  16602. __extends(Texture, _super);
  16603. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16604. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16605. if (onLoad === void 0) { onLoad = null; }
  16606. if (onError === void 0) { onError = null; }
  16607. if (buffer === void 0) { buffer = null; }
  16608. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16609. _super.call(this, scene);
  16610. this.uOffset = 0;
  16611. this.vOffset = 0;
  16612. this.uScale = 1.0;
  16613. this.vScale = 1.0;
  16614. this.uAng = 0;
  16615. this.vAng = 0;
  16616. this.wAng = 0;
  16617. this.name = url;
  16618. this.url = url;
  16619. this._noMipmap = noMipmap;
  16620. this._invertY = invertY;
  16621. this._samplingMode = samplingMode;
  16622. this._buffer = buffer;
  16623. this._deleteBuffer = deleteBuffer;
  16624. if (!url) {
  16625. return;
  16626. }
  16627. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16628. if (!this._texture) {
  16629. if (!scene.useDelayedTextureLoading) {
  16630. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16631. if (deleteBuffer) {
  16632. delete this._buffer;
  16633. }
  16634. }
  16635. else {
  16636. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16637. }
  16638. }
  16639. else {
  16640. BABYLON.Tools.SetImmediate(function () {
  16641. if (onLoad) {
  16642. onLoad();
  16643. }
  16644. });
  16645. }
  16646. }
  16647. Texture.prototype.delayLoad = function () {
  16648. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16649. return;
  16650. }
  16651. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16652. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16653. if (!this._texture) {
  16654. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16655. if (this._deleteBuffer) {
  16656. delete this._buffer;
  16657. }
  16658. }
  16659. };
  16660. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16661. if (!this._texture) {
  16662. return;
  16663. }
  16664. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16665. };
  16666. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16667. x -= this.uOffset + 0.5;
  16668. y -= this.vOffset + 0.5;
  16669. z -= 0.5;
  16670. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16671. t.x *= this.uScale;
  16672. t.y *= this.vScale;
  16673. t.x += 0.5;
  16674. t.y += 0.5;
  16675. t.z += 0.5;
  16676. };
  16677. Texture.prototype.getTextureMatrix = function () {
  16678. if (this.uOffset === this._cachedUOffset &&
  16679. this.vOffset === this._cachedVOffset &&
  16680. this.uScale === this._cachedUScale &&
  16681. this.vScale === this._cachedVScale &&
  16682. this.uAng === this._cachedUAng &&
  16683. this.vAng === this._cachedVAng &&
  16684. this.wAng === this._cachedWAng) {
  16685. return this._cachedTextureMatrix;
  16686. }
  16687. this._cachedUOffset = this.uOffset;
  16688. this._cachedVOffset = this.vOffset;
  16689. this._cachedUScale = this.uScale;
  16690. this._cachedVScale = this.vScale;
  16691. this._cachedUAng = this.uAng;
  16692. this._cachedVAng = this.vAng;
  16693. this._cachedWAng = this.wAng;
  16694. if (!this._cachedTextureMatrix) {
  16695. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16696. this._rowGenerationMatrix = new BABYLON.Matrix();
  16697. this._t0 = BABYLON.Vector3.Zero();
  16698. this._t1 = BABYLON.Vector3.Zero();
  16699. this._t2 = BABYLON.Vector3.Zero();
  16700. }
  16701. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16702. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16703. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16704. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16705. this._t1.subtractInPlace(this._t0);
  16706. this._t2.subtractInPlace(this._t0);
  16707. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16708. this._cachedTextureMatrix.m[0] = this._t1.x;
  16709. this._cachedTextureMatrix.m[1] = this._t1.y;
  16710. this._cachedTextureMatrix.m[2] = this._t1.z;
  16711. this._cachedTextureMatrix.m[4] = this._t2.x;
  16712. this._cachedTextureMatrix.m[5] = this._t2.y;
  16713. this._cachedTextureMatrix.m[6] = this._t2.z;
  16714. this._cachedTextureMatrix.m[8] = this._t0.x;
  16715. this._cachedTextureMatrix.m[9] = this._t0.y;
  16716. this._cachedTextureMatrix.m[10] = this._t0.z;
  16717. return this._cachedTextureMatrix;
  16718. };
  16719. Texture.prototype.getReflectionTextureMatrix = function () {
  16720. if (this.uOffset === this._cachedUOffset &&
  16721. this.vOffset === this._cachedVOffset &&
  16722. this.uScale === this._cachedUScale &&
  16723. this.vScale === this._cachedVScale &&
  16724. this.coordinatesMode === this._cachedCoordinatesMode) {
  16725. return this._cachedTextureMatrix;
  16726. }
  16727. if (!this._cachedTextureMatrix) {
  16728. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16729. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16730. }
  16731. this._cachedCoordinatesMode = this.coordinatesMode;
  16732. switch (this.coordinatesMode) {
  16733. case Texture.SPHERICAL_MODE:
  16734. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16735. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16736. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16737. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16738. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16739. break;
  16740. case Texture.PLANAR_MODE:
  16741. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16742. this._cachedTextureMatrix[0] = this.uScale;
  16743. this._cachedTextureMatrix[5] = this.vScale;
  16744. this._cachedTextureMatrix[12] = this.uOffset;
  16745. this._cachedTextureMatrix[13] = this.vOffset;
  16746. break;
  16747. case Texture.PROJECTION_MODE:
  16748. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16749. this._projectionModeMatrix.m[0] = 0.5;
  16750. this._projectionModeMatrix.m[5] = -0.5;
  16751. this._projectionModeMatrix.m[10] = 0.0;
  16752. this._projectionModeMatrix.m[12] = 0.5;
  16753. this._projectionModeMatrix.m[13] = 0.5;
  16754. this._projectionModeMatrix.m[14] = 1.0;
  16755. this._projectionModeMatrix.m[15] = 1.0;
  16756. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16757. break;
  16758. default:
  16759. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16760. break;
  16761. }
  16762. return this._cachedTextureMatrix;
  16763. };
  16764. Texture.prototype.clone = function () {
  16765. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16766. // Base texture
  16767. newTexture.hasAlpha = this.hasAlpha;
  16768. newTexture.level = this.level;
  16769. newTexture.wrapU = this.wrapU;
  16770. newTexture.wrapV = this.wrapV;
  16771. newTexture.coordinatesIndex = this.coordinatesIndex;
  16772. newTexture.coordinatesMode = this.coordinatesMode;
  16773. // Texture
  16774. newTexture.uOffset = this.uOffset;
  16775. newTexture.vOffset = this.vOffset;
  16776. newTexture.uScale = this.uScale;
  16777. newTexture.vScale = this.vScale;
  16778. newTexture.uAng = this.uAng;
  16779. newTexture.vAng = this.vAng;
  16780. newTexture.wAng = this.wAng;
  16781. return newTexture;
  16782. };
  16783. // Statics
  16784. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16785. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16786. if (onLoad === void 0) { onLoad = null; }
  16787. if (onError === void 0) { onError = null; }
  16788. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16789. };
  16790. // Constants
  16791. Texture.NEAREST_SAMPLINGMODE = 1;
  16792. Texture.BILINEAR_SAMPLINGMODE = 2;
  16793. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16794. Texture.EXPLICIT_MODE = 0;
  16795. Texture.SPHERICAL_MODE = 1;
  16796. Texture.PLANAR_MODE = 2;
  16797. Texture.CUBIC_MODE = 3;
  16798. Texture.PROJECTION_MODE = 4;
  16799. Texture.SKYBOX_MODE = 5;
  16800. Texture.CLAMP_ADDRESSMODE = 0;
  16801. Texture.WRAP_ADDRESSMODE = 1;
  16802. Texture.MIRROR_ADDRESSMODE = 2;
  16803. return Texture;
  16804. })(BABYLON.BaseTexture);
  16805. BABYLON.Texture = Texture;
  16806. })(BABYLON || (BABYLON = {}));
  16807. var BABYLON;
  16808. (function (BABYLON) {
  16809. var CubeTexture = (function (_super) {
  16810. __extends(CubeTexture, _super);
  16811. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16812. _super.call(this, scene);
  16813. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16814. this.name = rootUrl;
  16815. this.url = rootUrl;
  16816. this._noMipmap = noMipmap;
  16817. this.hasAlpha = false;
  16818. this._texture = this._getFromCache(rootUrl, noMipmap);
  16819. if (!extensions) {
  16820. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16821. }
  16822. this._extensions = extensions;
  16823. if (!this._texture) {
  16824. if (!scene.useDelayedTextureLoading) {
  16825. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16826. }
  16827. else {
  16828. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16829. }
  16830. }
  16831. this.isCube = true;
  16832. this._textureMatrix = BABYLON.Matrix.Identity();
  16833. }
  16834. CubeTexture.prototype.clone = function () {
  16835. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16836. // Base texture
  16837. newTexture.level = this.level;
  16838. newTexture.wrapU = this.wrapU;
  16839. newTexture.wrapV = this.wrapV;
  16840. newTexture.coordinatesIndex = this.coordinatesIndex;
  16841. newTexture.coordinatesMode = this.coordinatesMode;
  16842. return newTexture;
  16843. };
  16844. // Methods
  16845. CubeTexture.prototype.delayLoad = function () {
  16846. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16847. return;
  16848. }
  16849. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16850. this._texture = this._getFromCache(this.url, this._noMipmap);
  16851. if (!this._texture) {
  16852. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16853. }
  16854. };
  16855. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16856. return this._textureMatrix;
  16857. };
  16858. return CubeTexture;
  16859. })(BABYLON.BaseTexture);
  16860. BABYLON.CubeTexture = CubeTexture;
  16861. })(BABYLON || (BABYLON = {}));
  16862. var BABYLON;
  16863. (function (BABYLON) {
  16864. var RenderTargetTexture = (function (_super) {
  16865. __extends(RenderTargetTexture, _super);
  16866. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16867. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16868. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16869. _super.call(this, null, scene, !generateMipMaps);
  16870. this.renderList = new Array();
  16871. this.renderParticles = true;
  16872. this.renderSprites = false;
  16873. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16874. this._currentRefreshId = -1;
  16875. this._refreshRate = 1;
  16876. this.name = name;
  16877. this.isRenderTarget = true;
  16878. this._size = size;
  16879. this._generateMipMaps = generateMipMaps;
  16880. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16881. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16882. // Rendering groups
  16883. this._renderingManager = new BABYLON.RenderingManager(scene);
  16884. }
  16885. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16886. this._currentRefreshId = -1;
  16887. };
  16888. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16889. get: function () {
  16890. return this._refreshRate;
  16891. },
  16892. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16893. set: function (value) {
  16894. this._refreshRate = value;
  16895. this.resetRefreshCounter();
  16896. },
  16897. enumerable: true,
  16898. configurable: true
  16899. });
  16900. RenderTargetTexture.prototype._shouldRender = function () {
  16901. if (this._currentRefreshId === -1) {
  16902. this._currentRefreshId = 1;
  16903. return true;
  16904. }
  16905. if (this.refreshRate === this._currentRefreshId) {
  16906. this._currentRefreshId = 1;
  16907. return true;
  16908. }
  16909. this._currentRefreshId++;
  16910. return false;
  16911. };
  16912. RenderTargetTexture.prototype.isReady = function () {
  16913. if (!this.getScene().renderTargetsEnabled) {
  16914. return false;
  16915. }
  16916. return _super.prototype.isReady.call(this);
  16917. };
  16918. RenderTargetTexture.prototype.getRenderSize = function () {
  16919. return this._size;
  16920. };
  16921. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16922. get: function () {
  16923. return true;
  16924. },
  16925. enumerable: true,
  16926. configurable: true
  16927. });
  16928. RenderTargetTexture.prototype.scale = function (ratio) {
  16929. var newSize = this._size * ratio;
  16930. this.resize(newSize, this._generateMipMaps);
  16931. };
  16932. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16933. this.releaseInternalTexture();
  16934. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16935. };
  16936. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16937. var scene = this.getScene();
  16938. var engine = scene.getEngine();
  16939. if (this._waitingRenderList) {
  16940. this.renderList = [];
  16941. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16942. var id = this._waitingRenderList[index];
  16943. this.renderList.push(scene.getMeshByID(id));
  16944. }
  16945. delete this._waitingRenderList;
  16946. }
  16947. if (this.renderList && this.renderList.length === 0) {
  16948. return;
  16949. }
  16950. // Bind
  16951. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16952. engine.bindFramebuffer(this._texture);
  16953. }
  16954. this._renderingManager.reset();
  16955. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16956. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16957. var mesh = currentRenderList[meshIndex];
  16958. if (mesh) {
  16959. if (!mesh.isReady()) {
  16960. // Reset _currentRefreshId
  16961. this.resetRefreshCounter();
  16962. continue;
  16963. }
  16964. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16965. mesh._activate(scene.getRenderId());
  16966. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16967. var subMesh = mesh.subMeshes[subIndex];
  16968. scene._activeIndices += subMesh.indexCount;
  16969. this._renderingManager.dispatch(subMesh);
  16970. }
  16971. }
  16972. }
  16973. }
  16974. if (this.onBeforeRender) {
  16975. this.onBeforeRender();
  16976. }
  16977. // Clear
  16978. if (this.onClear) {
  16979. this.onClear(engine);
  16980. }
  16981. else {
  16982. engine.clear(scene.clearColor, true, true);
  16983. }
  16984. if (!this._doNotChangeAspectRatio) {
  16985. scene.updateTransformMatrix(true);
  16986. }
  16987. // Render
  16988. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16989. if (useCameraPostProcess) {
  16990. scene.postProcessManager._finalizeFrame(false, this._texture);
  16991. }
  16992. if (!this._doNotChangeAspectRatio) {
  16993. scene.updateTransformMatrix(true);
  16994. }
  16995. if (this.onAfterRender) {
  16996. this.onAfterRender();
  16997. }
  16998. // Dump ?
  16999. if (dumpForDebug) {
  17000. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  17001. }
  17002. // Unbind
  17003. engine.unBindFramebuffer(this._texture);
  17004. if (this.onAfterUnbind) {
  17005. this.onAfterUnbind();
  17006. }
  17007. };
  17008. RenderTargetTexture.prototype.clone = function () {
  17009. var textureSize = this.getSize();
  17010. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17011. // Base texture
  17012. newTexture.hasAlpha = this.hasAlpha;
  17013. newTexture.level = this.level;
  17014. // RenderTarget Texture
  17015. newTexture.coordinatesMode = this.coordinatesMode;
  17016. newTexture.renderList = this.renderList.slice(0);
  17017. return newTexture;
  17018. };
  17019. return RenderTargetTexture;
  17020. })(BABYLON.Texture);
  17021. BABYLON.RenderTargetTexture = RenderTargetTexture;
  17022. })(BABYLON || (BABYLON = {}));
  17023. var BABYLON;
  17024. (function (BABYLON) {
  17025. var ProceduralTexture = (function (_super) {
  17026. __extends(ProceduralTexture, _super);
  17027. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  17028. if (generateMipMaps === void 0) { generateMipMaps = true; }
  17029. _super.call(this, null, scene, !generateMipMaps);
  17030. this._currentRefreshId = -1;
  17031. this._refreshRate = 1;
  17032. this._vertexDeclaration = [2];
  17033. this._vertexStrideSize = 2 * 4;
  17034. this._uniforms = new Array();
  17035. this._samplers = new Array();
  17036. this._textures = new Array();
  17037. this._floats = new Array();
  17038. this._floatsArrays = {};
  17039. this._colors3 = new Array();
  17040. this._colors4 = new Array();
  17041. this._vectors2 = new Array();
  17042. this._vectors3 = new Array();
  17043. this._matrices = new Array();
  17044. this._fallbackTextureUsed = false;
  17045. scene._proceduralTextures.push(this);
  17046. this.name = name;
  17047. this.isRenderTarget = true;
  17048. this._size = size;
  17049. this._generateMipMaps = generateMipMaps;
  17050. this.setFragment(fragment);
  17051. this._fallbackTexture = fallbackTexture;
  17052. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  17053. // VBO
  17054. var vertices = [];
  17055. vertices.push(1, 1);
  17056. vertices.push(-1, 1);
  17057. vertices.push(-1, -1);
  17058. vertices.push(1, -1);
  17059. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17060. // Indices
  17061. var indices = [];
  17062. indices.push(0);
  17063. indices.push(1);
  17064. indices.push(2);
  17065. indices.push(0);
  17066. indices.push(2);
  17067. indices.push(3);
  17068. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17069. }
  17070. ProceduralTexture.prototype.reset = function () {
  17071. if (this._effect === undefined) {
  17072. return;
  17073. }
  17074. var engine = this.getScene().getEngine();
  17075. engine._releaseEffect(this._effect);
  17076. };
  17077. ProceduralTexture.prototype.isReady = function () {
  17078. var _this = this;
  17079. var engine = this.getScene().getEngine();
  17080. var shaders;
  17081. if (!this._fragment) {
  17082. return false;
  17083. }
  17084. if (this._fallbackTextureUsed) {
  17085. return true;
  17086. }
  17087. if (this._fragment.fragmentElement !== undefined) {
  17088. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  17089. }
  17090. else {
  17091. shaders = { vertex: "procedural", fragment: this._fragment };
  17092. }
  17093. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  17094. _this.releaseInternalTexture();
  17095. if (_this._fallbackTexture) {
  17096. _this._texture = _this._fallbackTexture._texture;
  17097. _this._texture.references++;
  17098. }
  17099. _this._fallbackTextureUsed = true;
  17100. });
  17101. return this._effect.isReady();
  17102. };
  17103. ProceduralTexture.prototype.resetRefreshCounter = function () {
  17104. this._currentRefreshId = -1;
  17105. };
  17106. ProceduralTexture.prototype.setFragment = function (fragment) {
  17107. this._fragment = fragment;
  17108. };
  17109. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  17110. get: function () {
  17111. return this._refreshRate;
  17112. },
  17113. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  17114. set: function (value) {
  17115. this._refreshRate = value;
  17116. this.resetRefreshCounter();
  17117. },
  17118. enumerable: true,
  17119. configurable: true
  17120. });
  17121. ProceduralTexture.prototype._shouldRender = function () {
  17122. if (!this.isReady() || !this._texture) {
  17123. return false;
  17124. }
  17125. if (this._fallbackTextureUsed) {
  17126. return false;
  17127. }
  17128. if (this._currentRefreshId === -1) {
  17129. this._currentRefreshId = 1;
  17130. return true;
  17131. }
  17132. if (this.refreshRate === this._currentRefreshId) {
  17133. this._currentRefreshId = 1;
  17134. return true;
  17135. }
  17136. this._currentRefreshId++;
  17137. return false;
  17138. };
  17139. ProceduralTexture.prototype.getRenderSize = function () {
  17140. return this._size;
  17141. };
  17142. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  17143. if (this._fallbackTextureUsed) {
  17144. return;
  17145. }
  17146. this.releaseInternalTexture();
  17147. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  17148. };
  17149. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  17150. if (this._uniforms.indexOf(uniformName) === -1) {
  17151. this._uniforms.push(uniformName);
  17152. }
  17153. };
  17154. ProceduralTexture.prototype.setTexture = function (name, texture) {
  17155. if (this._samplers.indexOf(name) === -1) {
  17156. this._samplers.push(name);
  17157. }
  17158. this._textures[name] = texture;
  17159. return this;
  17160. };
  17161. ProceduralTexture.prototype.setFloat = function (name, value) {
  17162. this._checkUniform(name);
  17163. this._floats[name] = value;
  17164. return this;
  17165. };
  17166. ProceduralTexture.prototype.setFloats = function (name, value) {
  17167. this._checkUniform(name);
  17168. this._floatsArrays[name] = value;
  17169. return this;
  17170. };
  17171. ProceduralTexture.prototype.setColor3 = function (name, value) {
  17172. this._checkUniform(name);
  17173. this._colors3[name] = value;
  17174. return this;
  17175. };
  17176. ProceduralTexture.prototype.setColor4 = function (name, value) {
  17177. this._checkUniform(name);
  17178. this._colors4[name] = value;
  17179. return this;
  17180. };
  17181. ProceduralTexture.prototype.setVector2 = function (name, value) {
  17182. this._checkUniform(name);
  17183. this._vectors2[name] = value;
  17184. return this;
  17185. };
  17186. ProceduralTexture.prototype.setVector3 = function (name, value) {
  17187. this._checkUniform(name);
  17188. this._vectors3[name] = value;
  17189. return this;
  17190. };
  17191. ProceduralTexture.prototype.setMatrix = function (name, value) {
  17192. this._checkUniform(name);
  17193. this._matrices[name] = value;
  17194. return this;
  17195. };
  17196. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17197. var scene = this.getScene();
  17198. var engine = scene.getEngine();
  17199. engine.bindFramebuffer(this._texture);
  17200. // Clear
  17201. engine.clear(scene.clearColor, true, true);
  17202. // Render
  17203. engine.enableEffect(this._effect);
  17204. engine.setState(false);
  17205. // Texture
  17206. for (var name in this._textures) {
  17207. this._effect.setTexture(name, this._textures[name]);
  17208. }
  17209. // Float
  17210. for (name in this._floats) {
  17211. this._effect.setFloat(name, this._floats[name]);
  17212. }
  17213. // Floats
  17214. for (name in this._floatsArrays) {
  17215. this._effect.setArray(name, this._floatsArrays[name]);
  17216. }
  17217. // Color3
  17218. for (name in this._colors3) {
  17219. this._effect.setColor3(name, this._colors3[name]);
  17220. }
  17221. // Color4
  17222. for (name in this._colors4) {
  17223. var color = this._colors4[name];
  17224. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  17225. }
  17226. // Vector2
  17227. for (name in this._vectors2) {
  17228. this._effect.setVector2(name, this._vectors2[name]);
  17229. }
  17230. // Vector3
  17231. for (name in this._vectors3) {
  17232. this._effect.setVector3(name, this._vectors3[name]);
  17233. }
  17234. // Matrix
  17235. for (name in this._matrices) {
  17236. this._effect.setMatrix(name, this._matrices[name]);
  17237. }
  17238. // VBOs
  17239. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17240. // Draw order
  17241. engine.draw(true, 0, 6);
  17242. // Unbind
  17243. engine.unBindFramebuffer(this._texture);
  17244. };
  17245. ProceduralTexture.prototype.clone = function () {
  17246. var textureSize = this.getSize();
  17247. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  17248. // Base texture
  17249. newTexture.hasAlpha = this.hasAlpha;
  17250. newTexture.level = this.level;
  17251. // RenderTarget Texture
  17252. newTexture.coordinatesMode = this.coordinatesMode;
  17253. return newTexture;
  17254. };
  17255. ProceduralTexture.prototype.dispose = function () {
  17256. var index = this.getScene()._proceduralTextures.indexOf(this);
  17257. if (index >= 0) {
  17258. this.getScene()._proceduralTextures.splice(index, 1);
  17259. }
  17260. _super.prototype.dispose.call(this);
  17261. };
  17262. return ProceduralTexture;
  17263. })(BABYLON.Texture);
  17264. BABYLON.ProceduralTexture = ProceduralTexture;
  17265. })(BABYLON || (BABYLON = {}));
  17266. var BABYLON;
  17267. (function (BABYLON) {
  17268. var MirrorTexture = (function (_super) {
  17269. __extends(MirrorTexture, _super);
  17270. function MirrorTexture(name, size, scene, generateMipMaps) {
  17271. var _this = this;
  17272. _super.call(this, name, size, scene, generateMipMaps, true);
  17273. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  17274. this._transformMatrix = BABYLON.Matrix.Zero();
  17275. this._mirrorMatrix = BABYLON.Matrix.Zero();
  17276. this.onBeforeRender = function () {
  17277. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  17278. _this._savedViewMatrix = scene.getViewMatrix();
  17279. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  17280. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  17281. scene.clipPlane = _this.mirrorPlane;
  17282. scene.getEngine().cullBackFaces = false;
  17283. };
  17284. this.onAfterRender = function () {
  17285. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  17286. scene.getEngine().cullBackFaces = true;
  17287. delete scene.clipPlane;
  17288. };
  17289. }
  17290. MirrorTexture.prototype.clone = function () {
  17291. var textureSize = this.getSize();
  17292. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17293. // Base texture
  17294. newTexture.hasAlpha = this.hasAlpha;
  17295. newTexture.level = this.level;
  17296. // Mirror Texture
  17297. newTexture.mirrorPlane = this.mirrorPlane.clone();
  17298. newTexture.renderList = this.renderList.slice(0);
  17299. return newTexture;
  17300. };
  17301. return MirrorTexture;
  17302. })(BABYLON.RenderTargetTexture);
  17303. BABYLON.MirrorTexture = MirrorTexture;
  17304. })(BABYLON || (BABYLON = {}));
  17305. var BABYLON;
  17306. (function (BABYLON) {
  17307. var DynamicTexture = (function (_super) {
  17308. __extends(DynamicTexture, _super);
  17309. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  17310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17311. _super.call(this, null, scene, !generateMipMaps);
  17312. this.name = name;
  17313. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17314. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17315. this._generateMipMaps = generateMipMaps;
  17316. if (options.getContext) {
  17317. this._canvas = options;
  17318. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17319. }
  17320. else {
  17321. this._canvas = document.createElement("canvas");
  17322. if (options.width) {
  17323. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  17324. }
  17325. else {
  17326. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  17327. }
  17328. }
  17329. var textureSize = this.getSize();
  17330. this._canvas.width = textureSize.width;
  17331. this._canvas.height = textureSize.height;
  17332. this._context = this._canvas.getContext("2d");
  17333. }
  17334. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  17335. get: function () {
  17336. return true;
  17337. },
  17338. enumerable: true,
  17339. configurable: true
  17340. });
  17341. DynamicTexture.prototype.scale = function (ratio) {
  17342. var textureSize = this.getSize();
  17343. textureSize.width *= ratio;
  17344. textureSize.height *= ratio;
  17345. this._canvas.width = textureSize.width;
  17346. this._canvas.height = textureSize.height;
  17347. this.releaseInternalTexture();
  17348. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  17349. };
  17350. DynamicTexture.prototype.getContext = function () {
  17351. return this._context;
  17352. };
  17353. DynamicTexture.prototype.clear = function () {
  17354. var size = this.getSize();
  17355. this._context.fillRect(0, 0, size.width, size.height);
  17356. };
  17357. DynamicTexture.prototype.update = function (invertY) {
  17358. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  17359. };
  17360. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  17361. if (update === void 0) { update = true; }
  17362. var size = this.getSize();
  17363. if (clearColor) {
  17364. this._context.fillStyle = clearColor;
  17365. this._context.fillRect(0, 0, size.width, size.height);
  17366. }
  17367. this._context.font = font;
  17368. if (x === null) {
  17369. var textSize = this._context.measureText(text);
  17370. x = (size.width - textSize.width) / 2;
  17371. }
  17372. this._context.fillStyle = color;
  17373. this._context.fillText(text, x, y);
  17374. if (update) {
  17375. this.update(invertY);
  17376. }
  17377. };
  17378. DynamicTexture.prototype.clone = function () {
  17379. var textureSize = this.getSize();
  17380. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  17381. // Base texture
  17382. newTexture.hasAlpha = this.hasAlpha;
  17383. newTexture.level = this.level;
  17384. // Dynamic Texture
  17385. newTexture.wrapU = this.wrapU;
  17386. newTexture.wrapV = this.wrapV;
  17387. return newTexture;
  17388. };
  17389. return DynamicTexture;
  17390. })(BABYLON.Texture);
  17391. BABYLON.DynamicTexture = DynamicTexture;
  17392. })(BABYLON || (BABYLON = {}));
  17393. var BABYLON;
  17394. (function (BABYLON) {
  17395. var VideoTexture = (function (_super) {
  17396. __extends(VideoTexture, _super);
  17397. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  17398. var _this = this;
  17399. if (generateMipMaps === void 0) { generateMipMaps = false; }
  17400. if (invertY === void 0) { invertY = false; }
  17401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  17402. _super.call(this, null, scene, !generateMipMaps, invertY);
  17403. this._autoLaunch = true;
  17404. this.name = name;
  17405. this.video = document.createElement("video");
  17406. this.video.autoplay = false;
  17407. this.video.loop = true;
  17408. this.video.addEventListener("canplaythrough", function () {
  17409. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  17410. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17411. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17412. }
  17413. else {
  17414. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17415. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  17416. generateMipMaps = false;
  17417. }
  17418. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  17419. _this._texture.isReady = true;
  17420. });
  17421. urls.forEach(function (url) {
  17422. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  17423. var source = document.createElement("source");
  17424. source.src = url;
  17425. _this.video.appendChild(source);
  17426. });
  17427. this._lastUpdate = BABYLON.Tools.Now;
  17428. }
  17429. VideoTexture.prototype.update = function () {
  17430. if (this._autoLaunch) {
  17431. this._autoLaunch = false;
  17432. this.video.play();
  17433. }
  17434. var now = BABYLON.Tools.Now;
  17435. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  17436. return false;
  17437. }
  17438. this._lastUpdate = now;
  17439. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  17440. return true;
  17441. };
  17442. return VideoTexture;
  17443. })(BABYLON.Texture);
  17444. BABYLON.VideoTexture = VideoTexture;
  17445. })(BABYLON || (BABYLON = {}));
  17446. var BABYLON;
  17447. (function (BABYLON) {
  17448. var CustomProceduralTexture = (function (_super) {
  17449. __extends(CustomProceduralTexture, _super);
  17450. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  17451. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  17452. this._animate = true;
  17453. this._time = 0;
  17454. this._texturePath = texturePath;
  17455. //Try to load json
  17456. this.loadJson(texturePath);
  17457. this.refreshRate = 1;
  17458. }
  17459. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  17460. var _this = this;
  17461. var that = this;
  17462. function noConfigFile() {
  17463. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  17464. try {
  17465. that.setFragment(that._texturePath);
  17466. }
  17467. catch (ex) {
  17468. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  17469. }
  17470. }
  17471. var configFileUrl = jsonUrl + "/config.json";
  17472. var xhr = new XMLHttpRequest();
  17473. xhr.open("GET", configFileUrl, true);
  17474. xhr.addEventListener("load", function () {
  17475. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  17476. try {
  17477. _this._config = JSON.parse(xhr.response);
  17478. _this.updateShaderUniforms();
  17479. _this.updateTextures();
  17480. _this.setFragment(_this._texturePath + "/custom");
  17481. _this._animate = _this._config.animate;
  17482. _this.refreshRate = _this._config.refreshrate;
  17483. }
  17484. catch (ex) {
  17485. noConfigFile();
  17486. }
  17487. }
  17488. else {
  17489. noConfigFile();
  17490. }
  17491. }, false);
  17492. xhr.addEventListener("error", function () {
  17493. noConfigFile();
  17494. }, false);
  17495. try {
  17496. xhr.send();
  17497. }
  17498. catch (ex) {
  17499. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  17500. }
  17501. };
  17502. CustomProceduralTexture.prototype.isReady = function () {
  17503. if (!_super.prototype.isReady.call(this)) {
  17504. return false;
  17505. }
  17506. for (var name in this._textures) {
  17507. var texture = this._textures[name];
  17508. if (!texture.isReady()) {
  17509. return false;
  17510. }
  17511. }
  17512. return true;
  17513. };
  17514. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17515. if (this._animate) {
  17516. this._time += this.getScene().getAnimationRatio() * 0.03;
  17517. this.updateShaderUniforms();
  17518. }
  17519. _super.prototype.render.call(this, useCameraPostProcess);
  17520. };
  17521. CustomProceduralTexture.prototype.updateTextures = function () {
  17522. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  17523. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  17524. }
  17525. };
  17526. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  17527. if (this._config) {
  17528. for (var j = 0; j < this._config.uniforms.length; j++) {
  17529. var uniform = this._config.uniforms[j];
  17530. switch (uniform.type) {
  17531. case "float":
  17532. this.setFloat(uniform.name, uniform.value);
  17533. break;
  17534. case "color3":
  17535. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  17536. break;
  17537. case "color4":
  17538. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  17539. break;
  17540. case "vector2":
  17541. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  17542. break;
  17543. case "vector3":
  17544. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  17545. break;
  17546. }
  17547. }
  17548. }
  17549. this.setFloat("time", this._time);
  17550. };
  17551. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  17552. get: function () {
  17553. return this._animate;
  17554. },
  17555. set: function (value) {
  17556. this._animate = value;
  17557. },
  17558. enumerable: true,
  17559. configurable: true
  17560. });
  17561. return CustomProceduralTexture;
  17562. })(BABYLON.ProceduralTexture);
  17563. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17564. })(BABYLON || (BABYLON = {}));
  17565. var BABYLON;
  17566. (function (BABYLON) {
  17567. var WoodProceduralTexture = (function (_super) {
  17568. __extends(WoodProceduralTexture, _super);
  17569. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17570. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17571. this._ampScale = 100.0;
  17572. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17573. this.updateShaderUniforms();
  17574. this.refreshRate = 0;
  17575. }
  17576. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17577. this.setFloat("ampScale", this._ampScale);
  17578. this.setColor3("woodColor", this._woodColor);
  17579. };
  17580. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17581. get: function () {
  17582. return this._ampScale;
  17583. },
  17584. set: function (value) {
  17585. this._ampScale = value;
  17586. this.updateShaderUniforms();
  17587. },
  17588. enumerable: true,
  17589. configurable: true
  17590. });
  17591. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17592. get: function () {
  17593. return this._woodColor;
  17594. },
  17595. set: function (value) {
  17596. this._woodColor = value;
  17597. this.updateShaderUniforms();
  17598. },
  17599. enumerable: true,
  17600. configurable: true
  17601. });
  17602. return WoodProceduralTexture;
  17603. })(BABYLON.ProceduralTexture);
  17604. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17605. var FireProceduralTexture = (function (_super) {
  17606. __extends(FireProceduralTexture, _super);
  17607. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17608. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17609. this._time = 0.0;
  17610. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17611. this._autoGenerateTime = true;
  17612. this._alphaThreshold = 0.5;
  17613. this._fireColors = FireProceduralTexture.RedFireColors;
  17614. this.updateShaderUniforms();
  17615. this.refreshRate = 1;
  17616. }
  17617. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17618. this.setFloat("time", this._time);
  17619. this.setVector2("speed", this._speed);
  17620. this.setColor3("c1", this._fireColors[0]);
  17621. this.setColor3("c2", this._fireColors[1]);
  17622. this.setColor3("c3", this._fireColors[2]);
  17623. this.setColor3("c4", this._fireColors[3]);
  17624. this.setColor3("c5", this._fireColors[4]);
  17625. this.setColor3("c6", this._fireColors[5]);
  17626. this.setFloat("alphaThreshold", this._alphaThreshold);
  17627. };
  17628. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17629. if (this._autoGenerateTime) {
  17630. this._time += this.getScene().getAnimationRatio() * 0.03;
  17631. this.updateShaderUniforms();
  17632. }
  17633. _super.prototype.render.call(this, useCameraPostProcess);
  17634. };
  17635. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17636. get: function () {
  17637. return [
  17638. new BABYLON.Color3(0.5, 0.0, 1.0),
  17639. new BABYLON.Color3(0.9, 0.0, 1.0),
  17640. new BABYLON.Color3(0.2, 0.0, 1.0),
  17641. new BABYLON.Color3(1.0, 0.9, 1.0),
  17642. new BABYLON.Color3(0.1, 0.1, 1.0),
  17643. new BABYLON.Color3(0.9, 0.9, 1.0)
  17644. ];
  17645. },
  17646. enumerable: true,
  17647. configurable: true
  17648. });
  17649. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17650. get: function () {
  17651. return [
  17652. new BABYLON.Color3(0.5, 1.0, 0.0),
  17653. new BABYLON.Color3(0.5, 1.0, 0.0),
  17654. new BABYLON.Color3(0.3, 0.4, 0.0),
  17655. new BABYLON.Color3(0.5, 1.0, 0.0),
  17656. new BABYLON.Color3(0.2, 0.0, 0.0),
  17657. new BABYLON.Color3(0.5, 1.0, 0.0)
  17658. ];
  17659. },
  17660. enumerable: true,
  17661. configurable: true
  17662. });
  17663. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17664. get: function () {
  17665. return [
  17666. new BABYLON.Color3(0.5, 0.0, 0.1),
  17667. new BABYLON.Color3(0.9, 0.0, 0.0),
  17668. new BABYLON.Color3(0.2, 0.0, 0.0),
  17669. new BABYLON.Color3(1.0, 0.9, 0.0),
  17670. new BABYLON.Color3(0.1, 0.1, 0.1),
  17671. new BABYLON.Color3(0.9, 0.9, 0.9)
  17672. ];
  17673. },
  17674. enumerable: true,
  17675. configurable: true
  17676. });
  17677. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17678. get: function () {
  17679. return [
  17680. new BABYLON.Color3(0.1, 0.0, 0.5),
  17681. new BABYLON.Color3(0.0, 0.0, 0.5),
  17682. new BABYLON.Color3(0.1, 0.0, 0.2),
  17683. new BABYLON.Color3(0.0, 0.0, 1.0),
  17684. new BABYLON.Color3(0.1, 0.2, 0.3),
  17685. new BABYLON.Color3(0.0, 0.2, 0.9)
  17686. ];
  17687. },
  17688. enumerable: true,
  17689. configurable: true
  17690. });
  17691. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17692. get: function () {
  17693. return this._fireColors;
  17694. },
  17695. set: function (value) {
  17696. this._fireColors = value;
  17697. this.updateShaderUniforms();
  17698. },
  17699. enumerable: true,
  17700. configurable: true
  17701. });
  17702. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17703. get: function () {
  17704. return this._time;
  17705. },
  17706. set: function (value) {
  17707. this._time = value;
  17708. this.updateShaderUniforms();
  17709. },
  17710. enumerable: true,
  17711. configurable: true
  17712. });
  17713. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17714. get: function () {
  17715. return this._speed;
  17716. },
  17717. set: function (value) {
  17718. this._speed = value;
  17719. this.updateShaderUniforms();
  17720. },
  17721. enumerable: true,
  17722. configurable: true
  17723. });
  17724. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17725. get: function () {
  17726. return this._alphaThreshold;
  17727. },
  17728. set: function (value) {
  17729. this._alphaThreshold = value;
  17730. this.updateShaderUniforms();
  17731. },
  17732. enumerable: true,
  17733. configurable: true
  17734. });
  17735. return FireProceduralTexture;
  17736. })(BABYLON.ProceduralTexture);
  17737. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17738. var CloudProceduralTexture = (function (_super) {
  17739. __extends(CloudProceduralTexture, _super);
  17740. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17741. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17742. this._skyColor = new BABYLON.Color4(0.15, 0.68, 1.0, 1.0);
  17743. this._cloudColor = new BABYLON.Color4(1, 1, 1, 1.0);
  17744. this.updateShaderUniforms();
  17745. this.refreshRate = 0;
  17746. }
  17747. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17748. this.setColor4("skyColor", this._skyColor);
  17749. this.setColor4("cloudColor", this._cloudColor);
  17750. };
  17751. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17752. get: function () {
  17753. return this._skyColor;
  17754. },
  17755. set: function (value) {
  17756. this._skyColor = value;
  17757. this.updateShaderUniforms();
  17758. },
  17759. enumerable: true,
  17760. configurable: true
  17761. });
  17762. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17763. get: function () {
  17764. return this._cloudColor;
  17765. },
  17766. set: function (value) {
  17767. this._cloudColor = value;
  17768. this.updateShaderUniforms();
  17769. },
  17770. enumerable: true,
  17771. configurable: true
  17772. });
  17773. return CloudProceduralTexture;
  17774. })(BABYLON.ProceduralTexture);
  17775. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17776. var GrassProceduralTexture = (function (_super) {
  17777. __extends(GrassProceduralTexture, _super);
  17778. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17779. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17780. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17781. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17782. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17783. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17784. this._grassColors = [
  17785. new BABYLON.Color3(0.29, 0.38, 0.02),
  17786. new BABYLON.Color3(0.36, 0.49, 0.09),
  17787. new BABYLON.Color3(0.51, 0.6, 0.28)
  17788. ];
  17789. this.updateShaderUniforms();
  17790. this.refreshRate = 0;
  17791. }
  17792. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17793. this.setColor3("herb1Color", this._grassColors[0]);
  17794. this.setColor3("herb2Color", this._grassColors[1]);
  17795. this.setColor3("herb3Color", this._grassColors[2]);
  17796. this.setColor3("groundColor", this._groundColor);
  17797. };
  17798. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17799. get: function () {
  17800. return this._grassColors;
  17801. },
  17802. set: function (value) {
  17803. this._grassColors = value;
  17804. this.updateShaderUniforms();
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17810. get: function () {
  17811. return this._groundColor;
  17812. },
  17813. set: function (value) {
  17814. this.groundColor = value;
  17815. this.updateShaderUniforms();
  17816. },
  17817. enumerable: true,
  17818. configurable: true
  17819. });
  17820. return GrassProceduralTexture;
  17821. })(BABYLON.ProceduralTexture);
  17822. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17823. var RoadProceduralTexture = (function (_super) {
  17824. __extends(RoadProceduralTexture, _super);
  17825. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17826. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17827. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17828. this.updateShaderUniforms();
  17829. this.refreshRate = 0;
  17830. }
  17831. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17832. this.setColor3("roadColor", this._roadColor);
  17833. };
  17834. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17835. get: function () {
  17836. return this._roadColor;
  17837. },
  17838. set: function (value) {
  17839. this._roadColor = value;
  17840. this.updateShaderUniforms();
  17841. },
  17842. enumerable: true,
  17843. configurable: true
  17844. });
  17845. return RoadProceduralTexture;
  17846. })(BABYLON.ProceduralTexture);
  17847. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17848. var BrickProceduralTexture = (function (_super) {
  17849. __extends(BrickProceduralTexture, _super);
  17850. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17851. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17852. this._numberOfBricksHeight = 15;
  17853. this._numberOfBricksWidth = 5;
  17854. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17855. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17856. this.updateShaderUniforms();
  17857. this.refreshRate = 0;
  17858. }
  17859. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17860. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17861. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17862. this.setColor3("brickColor", this._brickColor);
  17863. this.setColor3("jointColor", this._jointColor);
  17864. };
  17865. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17866. get: function () {
  17867. return this._numberOfBricksHeight;
  17868. },
  17869. set: function (value) {
  17870. this._numberOfBricksHeight = value;
  17871. this.updateShaderUniforms();
  17872. },
  17873. enumerable: true,
  17874. configurable: true
  17875. });
  17876. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17877. get: function () {
  17878. return this._numberOfBricksWidth;
  17879. },
  17880. set: function (value) {
  17881. this._numberOfBricksWidth = value;
  17882. this.updateShaderUniforms();
  17883. },
  17884. enumerable: true,
  17885. configurable: true
  17886. });
  17887. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17888. get: function () {
  17889. return this._jointColor;
  17890. },
  17891. set: function (value) {
  17892. this._jointColor = value;
  17893. this.updateShaderUniforms();
  17894. },
  17895. enumerable: true,
  17896. configurable: true
  17897. });
  17898. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17899. get: function () {
  17900. return this._brickColor;
  17901. },
  17902. set: function (value) {
  17903. this._brickColor = value;
  17904. this.updateShaderUniforms();
  17905. },
  17906. enumerable: true,
  17907. configurable: true
  17908. });
  17909. return BrickProceduralTexture;
  17910. })(BABYLON.ProceduralTexture);
  17911. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17912. var MarbleProceduralTexture = (function (_super) {
  17913. __extends(MarbleProceduralTexture, _super);
  17914. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17915. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17916. this._numberOfTilesHeight = 3;
  17917. this._numberOfTilesWidth = 3;
  17918. this._amplitude = 9.0;
  17919. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17920. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17921. this.updateShaderUniforms();
  17922. this.refreshRate = 0;
  17923. }
  17924. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17925. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17926. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17927. this.setFloat("amplitude", this._amplitude);
  17928. this.setColor3("marbleColor", this._marbleColor);
  17929. this.setColor3("jointColor", this._jointColor);
  17930. };
  17931. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17932. get: function () {
  17933. return this._numberOfTilesHeight;
  17934. },
  17935. set: function (value) {
  17936. this._numberOfTilesHeight = value;
  17937. this.updateShaderUniforms();
  17938. },
  17939. enumerable: true,
  17940. configurable: true
  17941. });
  17942. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17943. get: function () {
  17944. return this._numberOfTilesWidth;
  17945. },
  17946. set: function (value) {
  17947. this._numberOfTilesWidth = value;
  17948. this.updateShaderUniforms();
  17949. },
  17950. enumerable: true,
  17951. configurable: true
  17952. });
  17953. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17954. get: function () {
  17955. return this._jointColor;
  17956. },
  17957. set: function (value) {
  17958. this._jointColor = value;
  17959. this.updateShaderUniforms();
  17960. },
  17961. enumerable: true,
  17962. configurable: true
  17963. });
  17964. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17965. get: function () {
  17966. return this._marbleColor;
  17967. },
  17968. set: function (value) {
  17969. this._marbleColor = value;
  17970. this.updateShaderUniforms();
  17971. },
  17972. enumerable: true,
  17973. configurable: true
  17974. });
  17975. return MarbleProceduralTexture;
  17976. })(BABYLON.ProceduralTexture);
  17977. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17978. })(BABYLON || (BABYLON = {}));
  17979. var BABYLON;
  17980. (function (BABYLON) {
  17981. var EffectFallbacks = (function () {
  17982. function EffectFallbacks() {
  17983. this._defines = {};
  17984. this._currentRank = 32;
  17985. this._maxRank = -1;
  17986. }
  17987. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17988. if (!this._defines[rank]) {
  17989. if (rank < this._currentRank) {
  17990. this._currentRank = rank;
  17991. }
  17992. if (rank > this._maxRank) {
  17993. this._maxRank = rank;
  17994. }
  17995. this._defines[rank] = new Array();
  17996. }
  17997. this._defines[rank].push(define);
  17998. };
  17999. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  18000. get: function () {
  18001. return this._currentRank <= this._maxRank;
  18002. },
  18003. enumerable: true,
  18004. configurable: true
  18005. });
  18006. EffectFallbacks.prototype.reduce = function (currentDefines) {
  18007. var currentFallbacks = this._defines[this._currentRank];
  18008. for (var index = 0; index < currentFallbacks.length; index++) {
  18009. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  18010. }
  18011. this._currentRank++;
  18012. return currentDefines;
  18013. };
  18014. return EffectFallbacks;
  18015. })();
  18016. BABYLON.EffectFallbacks = EffectFallbacks;
  18017. var Effect = (function () {
  18018. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  18019. var _this = this;
  18020. this._isReady = false;
  18021. this._compilationError = "";
  18022. this._valueCache = [];
  18023. this._engine = engine;
  18024. this.name = baseName;
  18025. this.defines = defines;
  18026. this._uniformsNames = uniformsNames.concat(samplers);
  18027. this._samplers = samplers;
  18028. this._attributesNames = attributesNames;
  18029. this.onError = onError;
  18030. this.onCompiled = onCompiled;
  18031. var vertexSource;
  18032. var fragmentSource;
  18033. if (baseName.vertexElement) {
  18034. vertexSource = document.getElementById(baseName.vertexElement);
  18035. if (!vertexSource) {
  18036. vertexSource = baseName.vertexElement;
  18037. }
  18038. }
  18039. else {
  18040. vertexSource = baseName.vertex || baseName;
  18041. }
  18042. if (baseName.fragmentElement) {
  18043. fragmentSource = document.getElementById(baseName.fragmentElement);
  18044. if (!fragmentSource) {
  18045. fragmentSource = baseName.fragmentElement;
  18046. }
  18047. }
  18048. else {
  18049. fragmentSource = baseName.fragment || baseName;
  18050. }
  18051. this._loadVertexShader(vertexSource, function (vertexCode) {
  18052. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  18053. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  18054. });
  18055. });
  18056. }
  18057. // Properties
  18058. Effect.prototype.isReady = function () {
  18059. return this._isReady;
  18060. };
  18061. Effect.prototype.getProgram = function () {
  18062. return this._program;
  18063. };
  18064. Effect.prototype.getAttributesNames = function () {
  18065. return this._attributesNames;
  18066. };
  18067. Effect.prototype.getAttributeLocation = function (index) {
  18068. return this._attributes[index];
  18069. };
  18070. Effect.prototype.getAttributeLocationByName = function (name) {
  18071. var index = this._attributesNames.indexOf(name);
  18072. return this._attributes[index];
  18073. };
  18074. Effect.prototype.getAttributesCount = function () {
  18075. return this._attributes.length;
  18076. };
  18077. Effect.prototype.getUniformIndex = function (uniformName) {
  18078. return this._uniformsNames.indexOf(uniformName);
  18079. };
  18080. Effect.prototype.getUniform = function (uniformName) {
  18081. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  18082. };
  18083. Effect.prototype.getSamplers = function () {
  18084. return this._samplers;
  18085. };
  18086. Effect.prototype.getCompilationError = function () {
  18087. return this._compilationError;
  18088. };
  18089. // Methods
  18090. Effect.prototype._loadVertexShader = function (vertex, callback) {
  18091. // DOM element ?
  18092. if (vertex instanceof HTMLElement) {
  18093. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  18094. callback(vertexCode);
  18095. return;
  18096. }
  18097. // Is in local store ?
  18098. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  18099. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  18100. return;
  18101. }
  18102. var vertexShaderUrl;
  18103. if (vertex[0] === "." || vertex[0] === "/") {
  18104. vertexShaderUrl = vertex;
  18105. }
  18106. else {
  18107. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  18108. }
  18109. // Vertex shader
  18110. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  18111. };
  18112. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  18113. // DOM element ?
  18114. if (fragment instanceof HTMLElement) {
  18115. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  18116. callback(fragmentCode);
  18117. return;
  18118. }
  18119. // Is in local store ?
  18120. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  18121. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  18122. return;
  18123. }
  18124. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  18125. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  18126. return;
  18127. }
  18128. var fragmentShaderUrl;
  18129. if (fragment[0] === "." || fragment[0] === "/") {
  18130. fragmentShaderUrl = fragment;
  18131. }
  18132. else {
  18133. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  18134. }
  18135. // Fragment shader
  18136. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  18137. };
  18138. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  18139. try {
  18140. var engine = this._engine;
  18141. if (!engine.getCaps().highPrecisionShaderSupported) {
  18142. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18143. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18144. }
  18145. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  18146. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  18147. this._attributes = engine.getAttributes(this._program, attributesNames);
  18148. for (var index = 0; index < this._samplers.length; index++) {
  18149. var sampler = this.getUniform(this._samplers[index]);
  18150. if (sampler == null) {
  18151. this._samplers.splice(index, 1);
  18152. index--;
  18153. }
  18154. }
  18155. engine.bindSamplers(this);
  18156. this._isReady = true;
  18157. if (this.onCompiled) {
  18158. this.onCompiled(this);
  18159. }
  18160. }
  18161. catch (e) {
  18162. // Is it a problem with precision?
  18163. if (e.message.indexOf("highp") !== -1) {
  18164. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  18165. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  18166. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18167. return;
  18168. }
  18169. // Let's go through fallbacks then
  18170. if (fallbacks && fallbacks.isMoreFallbacks) {
  18171. defines = fallbacks.reduce(defines);
  18172. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  18173. }
  18174. else {
  18175. BABYLON.Tools.Error("Unable to compile effect: ");
  18176. if (this.name.vertexElement) {
  18177. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  18178. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  18179. }
  18180. else if (this.name.vertex) {
  18181. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  18182. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  18183. }
  18184. else {
  18185. BABYLON.Tools.Error("Vertex shader:" + this.name);
  18186. BABYLON.Tools.Error("Fragment shader:" + this.name);
  18187. }
  18188. BABYLON.Tools.Error("Defines: " + defines);
  18189. BABYLON.Tools.Error("Error: " + e.message);
  18190. this._compilationError = e.message;
  18191. if (this.onError) {
  18192. this.onError(this, this._compilationError);
  18193. }
  18194. }
  18195. }
  18196. };
  18197. Effect.prototype._bindTexture = function (channel, texture) {
  18198. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  18199. };
  18200. Effect.prototype.setTexture = function (channel, texture) {
  18201. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  18202. };
  18203. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  18204. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  18205. };
  18206. //public _cacheMatrix(uniformName, matrix) {
  18207. // if (!this._valueCache[uniformName]) {
  18208. // this._valueCache[uniformName] = new BABYLON.Matrix();
  18209. // }
  18210. // for (var index = 0; index < 16; index++) {
  18211. // this._valueCache[uniformName].m[index] = matrix.m[index];
  18212. // }
  18213. //};
  18214. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  18215. if (!this._valueCache[uniformName]) {
  18216. this._valueCache[uniformName] = [x, y];
  18217. return;
  18218. }
  18219. this._valueCache[uniformName][0] = x;
  18220. this._valueCache[uniformName][1] = y;
  18221. };
  18222. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  18223. if (!this._valueCache[uniformName]) {
  18224. this._valueCache[uniformName] = [x, y, z];
  18225. return;
  18226. }
  18227. this._valueCache[uniformName][0] = x;
  18228. this._valueCache[uniformName][1] = y;
  18229. this._valueCache[uniformName][2] = z;
  18230. };
  18231. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  18232. if (!this._valueCache[uniformName]) {
  18233. this._valueCache[uniformName] = [x, y, z, w];
  18234. return;
  18235. }
  18236. this._valueCache[uniformName][0] = x;
  18237. this._valueCache[uniformName][1] = y;
  18238. this._valueCache[uniformName][2] = z;
  18239. this._valueCache[uniformName][3] = w;
  18240. };
  18241. Effect.prototype.setArray = function (uniformName, array) {
  18242. this._engine.setArray(this.getUniform(uniformName), array);
  18243. return this;
  18244. };
  18245. Effect.prototype.setArray2 = function (uniformName, array) {
  18246. this._engine.setArray2(this.getUniform(uniformName), array);
  18247. return this;
  18248. };
  18249. Effect.prototype.setArray3 = function (uniformName, array) {
  18250. this._engine.setArray3(this.getUniform(uniformName), array);
  18251. return this;
  18252. };
  18253. Effect.prototype.setArray4 = function (uniformName, array) {
  18254. this._engine.setArray4(this.getUniform(uniformName), array);
  18255. return this;
  18256. };
  18257. Effect.prototype.setMatrices = function (uniformName, matrices) {
  18258. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  18259. return this;
  18260. };
  18261. Effect.prototype.setMatrix = function (uniformName, matrix) {
  18262. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  18263. // return;
  18264. //this._cacheMatrix(uniformName, matrix);
  18265. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  18266. return this;
  18267. };
  18268. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  18269. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  18270. return this;
  18271. };
  18272. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  18273. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  18274. return this;
  18275. };
  18276. Effect.prototype.setFloat = function (uniformName, value) {
  18277. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  18278. return this;
  18279. this._valueCache[uniformName] = value;
  18280. this._engine.setFloat(this.getUniform(uniformName), value);
  18281. return this;
  18282. };
  18283. Effect.prototype.setBool = function (uniformName, bool) {
  18284. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  18285. return this;
  18286. this._valueCache[uniformName] = bool;
  18287. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  18288. return this;
  18289. };
  18290. Effect.prototype.setVector2 = function (uniformName, vector2) {
  18291. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  18292. return this;
  18293. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  18294. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  18295. return this;
  18296. };
  18297. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  18298. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  18299. return this;
  18300. this._cacheFloat2(uniformName, x, y);
  18301. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  18302. return this;
  18303. };
  18304. Effect.prototype.setVector3 = function (uniformName, vector3) {
  18305. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  18306. return this;
  18307. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  18308. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  18309. return this;
  18310. };
  18311. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  18312. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  18313. return this;
  18314. this._cacheFloat3(uniformName, x, y, z);
  18315. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  18316. return this;
  18317. };
  18318. Effect.prototype.setVector4 = function (uniformName, vector4) {
  18319. 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)
  18320. return this;
  18321. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  18322. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  18323. return this;
  18324. };
  18325. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  18326. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  18327. return this;
  18328. this._cacheFloat4(uniformName, x, y, z, w);
  18329. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  18330. return this;
  18331. };
  18332. Effect.prototype.setColor3 = function (uniformName, color3) {
  18333. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  18334. return this;
  18335. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  18336. this._engine.setColor3(this.getUniform(uniformName), color3);
  18337. return this;
  18338. };
  18339. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  18340. 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)
  18341. return this;
  18342. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  18343. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  18344. return this;
  18345. };
  18346. // Statics
  18347. Effect.ShadersStore = {};
  18348. return Effect;
  18349. })();
  18350. BABYLON.Effect = Effect;
  18351. })(BABYLON || (BABYLON = {}));
  18352. var BABYLON;
  18353. (function (BABYLON) {
  18354. var Material = (function () {
  18355. function Material(name, scene, doNotAdd) {
  18356. this.name = name;
  18357. this.checkReadyOnEveryCall = true;
  18358. this.checkReadyOnlyOnce = false;
  18359. this.state = "";
  18360. this.alpha = 1.0;
  18361. this.backFaceCulling = true;
  18362. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  18363. this.disableDepthWrite = false;
  18364. this._wasPreviouslyReady = false;
  18365. this._fillMode = Material.TriangleFillMode;
  18366. this.pointSize = 1.0;
  18367. this.zOffset = 0;
  18368. this.id = name;
  18369. this._scene = scene;
  18370. if (!doNotAdd) {
  18371. scene.materials.push(this);
  18372. }
  18373. }
  18374. Object.defineProperty(Material, "TriangleFillMode", {
  18375. get: function () {
  18376. return Material._TriangleFillMode;
  18377. },
  18378. enumerable: true,
  18379. configurable: true
  18380. });
  18381. Object.defineProperty(Material, "WireFrameFillMode", {
  18382. get: function () {
  18383. return Material._WireFrameFillMode;
  18384. },
  18385. enumerable: true,
  18386. configurable: true
  18387. });
  18388. Object.defineProperty(Material, "PointFillMode", {
  18389. get: function () {
  18390. return Material._PointFillMode;
  18391. },
  18392. enumerable: true,
  18393. configurable: true
  18394. });
  18395. Object.defineProperty(Material.prototype, "wireframe", {
  18396. get: function () {
  18397. return this._fillMode === Material.WireFrameFillMode;
  18398. },
  18399. set: function (value) {
  18400. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  18401. },
  18402. enumerable: true,
  18403. configurable: true
  18404. });
  18405. Object.defineProperty(Material.prototype, "pointsCloud", {
  18406. get: function () {
  18407. return this._fillMode === Material.PointFillMode;
  18408. },
  18409. set: function (value) {
  18410. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  18411. },
  18412. enumerable: true,
  18413. configurable: true
  18414. });
  18415. Object.defineProperty(Material.prototype, "fillMode", {
  18416. get: function () {
  18417. return this._fillMode;
  18418. },
  18419. set: function (value) {
  18420. this._fillMode = value;
  18421. },
  18422. enumerable: true,
  18423. configurable: true
  18424. });
  18425. Material.prototype.isReady = function (mesh, useInstances) {
  18426. return true;
  18427. };
  18428. Material.prototype.getEffect = function () {
  18429. return this._effect;
  18430. };
  18431. Material.prototype.getScene = function () {
  18432. return this._scene;
  18433. };
  18434. Material.prototype.needAlphaBlending = function () {
  18435. return (this.alpha < 1.0);
  18436. };
  18437. Material.prototype.needAlphaTesting = function () {
  18438. return false;
  18439. };
  18440. Material.prototype.getAlphaTestTexture = function () {
  18441. return null;
  18442. };
  18443. Material.prototype.trackCreation = function (onCompiled, onError) {
  18444. };
  18445. Material.prototype._preBind = function () {
  18446. var engine = this._scene.getEngine();
  18447. engine.enableEffect(this._effect);
  18448. engine.setState(this.backFaceCulling, this.zOffset);
  18449. };
  18450. Material.prototype.bind = function (world, mesh) {
  18451. this._scene._cachedMaterial = this;
  18452. if (this.onBind) {
  18453. this.onBind(this, mesh);
  18454. }
  18455. if (this.disableDepthWrite) {
  18456. var engine = this._scene.getEngine();
  18457. this._cachedDepthWriteState = engine.getDepthWrite();
  18458. engine.setDepthWrite(false);
  18459. }
  18460. };
  18461. Material.prototype.bindOnlyWorldMatrix = function (world) {
  18462. };
  18463. Material.prototype.unbind = function () {
  18464. if (this.disableDepthWrite) {
  18465. var engine = this._scene.getEngine();
  18466. engine.setDepthWrite(this._cachedDepthWriteState);
  18467. }
  18468. };
  18469. Material.prototype.clone = function (name) {
  18470. return null;
  18471. };
  18472. Material.prototype.dispose = function (forceDisposeEffect) {
  18473. // Remove from scene
  18474. var index = this._scene.materials.indexOf(this);
  18475. this._scene.materials.splice(index, 1);
  18476. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  18477. if (forceDisposeEffect && this._effect) {
  18478. this._scene.getEngine()._releaseEffect(this._effect);
  18479. this._effect = null;
  18480. }
  18481. // Callback
  18482. if (this.onDispose) {
  18483. this.onDispose();
  18484. }
  18485. };
  18486. Material._TriangleFillMode = 0;
  18487. Material._WireFrameFillMode = 1;
  18488. Material._PointFillMode = 2;
  18489. return Material;
  18490. })();
  18491. BABYLON.Material = Material;
  18492. })(BABYLON || (BABYLON = {}));
  18493. var BABYLON;
  18494. (function (BABYLON) {
  18495. var maxSimultaneousLights = 4;
  18496. var FresnelParameters = (function () {
  18497. function FresnelParameters() {
  18498. this.isEnabled = true;
  18499. this.leftColor = BABYLON.Color3.White();
  18500. this.rightColor = BABYLON.Color3.Black();
  18501. this.bias = 0;
  18502. this.power = 1;
  18503. }
  18504. return FresnelParameters;
  18505. })();
  18506. BABYLON.FresnelParameters = FresnelParameters;
  18507. var StandardMaterialDefines = (function () {
  18508. function StandardMaterialDefines() {
  18509. this.DIFFUSE = false;
  18510. this.AMBIENT = false;
  18511. this.OPACITY = false;
  18512. this.OPACITYRGB = false;
  18513. this.REFLECTION = false;
  18514. this.EMISSIVE = false;
  18515. this.SPECULAR = false;
  18516. this.BUMP = false;
  18517. this.SPECULAROVERALPHA = false;
  18518. this.CLIPPLANE = false;
  18519. this.ALPHATEST = false;
  18520. this.ALPHAFROMDIFFUSE = false;
  18521. this.POINTSIZE = false;
  18522. this.FOG = false;
  18523. this.LIGHT0 = false;
  18524. this.LIGHT1 = false;
  18525. this.LIGHT2 = false;
  18526. this.LIGHT3 = false;
  18527. this.SPOTLIGHT0 = false;
  18528. this.SPOTLIGHT1 = false;
  18529. this.SPOTLIGHT2 = false;
  18530. this.SPOTLIGHT3 = false;
  18531. this.HEMILIGHT0 = false;
  18532. this.HEMILIGHT1 = false;
  18533. this.HEMILIGHT2 = false;
  18534. this.HEMILIGHT3 = false;
  18535. this.POINTDIRLIGHT0 = false;
  18536. this.POINTDIRLIGHT1 = false;
  18537. this.POINTDIRLIGHT2 = false;
  18538. this.POINTDIRLIGHT3 = false;
  18539. this.SPECULARTERM = false;
  18540. this.SHADOW0 = false;
  18541. this.SHADOW1 = false;
  18542. this.SHADOW2 = false;
  18543. this.SHADOW3 = false;
  18544. this.SHADOWS = false;
  18545. this.SHADOWVSM0 = false;
  18546. this.SHADOWVSM1 = false;
  18547. this.SHADOWVSM2 = false;
  18548. this.SHADOWVSM3 = false;
  18549. this.SHADOWPCF0 = false;
  18550. this.SHADOWPCF1 = false;
  18551. this.SHADOWPCF2 = false;
  18552. this.SHADOWPCF3 = false;
  18553. this.DIFFUSEFRESNEL = false;
  18554. this.OPACITYFRESNEL = false;
  18555. this.REFLECTIONFRESNEL = false;
  18556. this.EMISSIVEFRESNEL = false;
  18557. this.FRESNEL = false;
  18558. this.NORMAL = false;
  18559. this.UV1 = false;
  18560. this.UV2 = false;
  18561. this.VERTEXCOLOR = false;
  18562. this.VERTEXALPHA = false;
  18563. this.BONES = false;
  18564. this.BONES4 = false;
  18565. this.BonesPerMesh = 0;
  18566. this.INSTANCES = false;
  18567. this.GLOSSINESS = false;
  18568. this._keys = Object.keys(this);
  18569. }
  18570. StandardMaterialDefines.prototype.isEqual = function (other) {
  18571. for (var index = 0; index < this._keys.length; index++) {
  18572. var prop = this._keys[index];
  18573. if (this[prop] !== other[prop]) {
  18574. return false;
  18575. }
  18576. }
  18577. return true;
  18578. };
  18579. StandardMaterialDefines.prototype.cloneTo = function (other) {
  18580. for (var index = 0; index < this._keys.length; index++) {
  18581. var prop = this._keys[index];
  18582. other[prop] = this[prop];
  18583. }
  18584. };
  18585. StandardMaterialDefines.prototype.reset = function () {
  18586. for (var index = 0; index < this._keys.length; index++) {
  18587. var prop = this._keys[index];
  18588. if (prop === "BonesPerMesh") {
  18589. this[prop] = 0;
  18590. continue;
  18591. }
  18592. this[prop] = false;
  18593. }
  18594. };
  18595. StandardMaterialDefines.prototype.toString = function () {
  18596. var result = "";
  18597. for (var index = 0; index < this._keys.length; index++) {
  18598. var prop = this._keys[index];
  18599. if (prop === "BonesPerMesh" && this[prop] > 0) {
  18600. result += "#define BonesPerMesh " + this[prop] + "\n";
  18601. continue;
  18602. }
  18603. if (this[prop]) {
  18604. result += "#define " + prop + "\n";
  18605. }
  18606. }
  18607. return result;
  18608. };
  18609. return StandardMaterialDefines;
  18610. })();
  18611. var StandardMaterial = (function (_super) {
  18612. __extends(StandardMaterial, _super);
  18613. function StandardMaterial(name, scene) {
  18614. var _this = this;
  18615. _super.call(this, name, scene);
  18616. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18617. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  18618. this.specularColor = new BABYLON.Color3(1, 1, 1);
  18619. this.specularPower = 64;
  18620. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  18621. this.useAlphaFromDiffuseTexture = false;
  18622. this.useSpecularOverAlpha = true;
  18623. this.fogEnabled = true;
  18624. this.useGlossinessFromSpecularMapAlpha = false;
  18625. this._renderTargets = new BABYLON.SmartArray(16);
  18626. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  18627. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  18628. this._scaledDiffuse = new BABYLON.Color3();
  18629. this._scaledSpecular = new BABYLON.Color3();
  18630. this._defines = new StandardMaterialDefines();
  18631. this._cachedDefines = new StandardMaterialDefines();
  18632. this._cachedDefines.BonesPerMesh = -1;
  18633. this.getRenderTargetTextures = function () {
  18634. _this._renderTargets.reset();
  18635. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  18636. _this._renderTargets.push(_this.reflectionTexture);
  18637. }
  18638. return _this._renderTargets;
  18639. };
  18640. }
  18641. StandardMaterial.prototype.needAlphaBlending = function () {
  18642. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  18643. };
  18644. StandardMaterial.prototype.needAlphaTesting = function () {
  18645. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  18646. };
  18647. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  18648. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  18649. };
  18650. StandardMaterial.prototype.getAlphaTestTexture = function () {
  18651. return this.diffuseTexture;
  18652. };
  18653. // Methods
  18654. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  18655. if (this.checkReadyOnlyOnce) {
  18656. if (this._wasPreviouslyReady) {
  18657. return true;
  18658. }
  18659. }
  18660. var scene = this.getScene();
  18661. if (!this.checkReadyOnEveryCall) {
  18662. if (this._renderId === scene.getRenderId()) {
  18663. return true;
  18664. }
  18665. }
  18666. var engine = scene.getEngine();
  18667. var needNormals = false;
  18668. var needUVs = false;
  18669. this._defines.reset();
  18670. // Textures
  18671. if (scene.texturesEnabled) {
  18672. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18673. if (!this.diffuseTexture.isReady()) {
  18674. return false;
  18675. }
  18676. else {
  18677. needUVs = true;
  18678. this._defines.DIFFUSE = true;
  18679. }
  18680. }
  18681. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18682. if (!this.ambientTexture.isReady()) {
  18683. return false;
  18684. }
  18685. else {
  18686. needUVs = true;
  18687. this._defines.AMBIENT = true;
  18688. }
  18689. }
  18690. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18691. if (!this.opacityTexture.isReady()) {
  18692. return false;
  18693. }
  18694. else {
  18695. needUVs = true;
  18696. this._defines.OPACITY = true;
  18697. if (this.opacityTexture.getAlphaFromRGB) {
  18698. this._defines.OPACITYRGB = true;
  18699. }
  18700. }
  18701. }
  18702. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18703. if (!this.reflectionTexture.isReady()) {
  18704. return false;
  18705. }
  18706. else {
  18707. needNormals = true;
  18708. needUVs = true;
  18709. this._defines.REFLECTION = true;
  18710. }
  18711. }
  18712. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18713. if (!this.emissiveTexture.isReady()) {
  18714. return false;
  18715. }
  18716. else {
  18717. needUVs = true;
  18718. this._defines.EMISSIVE = true;
  18719. }
  18720. }
  18721. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18722. if (!this.specularTexture.isReady()) {
  18723. return false;
  18724. }
  18725. else {
  18726. needUVs = true;
  18727. this._defines.SPECULAR = true;
  18728. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  18729. }
  18730. }
  18731. }
  18732. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18733. if (!this.bumpTexture.isReady()) {
  18734. return false;
  18735. }
  18736. else {
  18737. needUVs = true;
  18738. this._defines.BUMP = true;
  18739. }
  18740. }
  18741. // Effect
  18742. if (scene.clipPlane) {
  18743. this._defines.CLIPPLANE = true;
  18744. }
  18745. if (engine.getAlphaTesting()) {
  18746. this._defines.ALPHATEST = true;
  18747. }
  18748. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18749. this._defines.ALPHAFROMDIFFUSE = true;
  18750. }
  18751. // Point size
  18752. if (this.pointsCloud || scene.forcePointsCloud) {
  18753. this._defines.POINTSIZE = true;
  18754. }
  18755. // Fog
  18756. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18757. this._defines.FOG = true;
  18758. }
  18759. var lightIndex = 0;
  18760. if (scene.lightsEnabled) {
  18761. for (var index = 0; index < scene.lights.length; index++) {
  18762. var light = scene.lights[index];
  18763. if (!light.isEnabled()) {
  18764. continue;
  18765. }
  18766. // Excluded check
  18767. if (light._excludedMeshesIds.length > 0) {
  18768. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18769. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18770. if (excludedMesh) {
  18771. light.excludedMeshes.push(excludedMesh);
  18772. }
  18773. }
  18774. light._excludedMeshesIds = [];
  18775. }
  18776. // Included check
  18777. if (light._includedOnlyMeshesIds.length > 0) {
  18778. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18779. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18780. if (includedOnlyMesh) {
  18781. light.includedOnlyMeshes.push(includedOnlyMesh);
  18782. }
  18783. }
  18784. light._includedOnlyMeshesIds = [];
  18785. }
  18786. if (!light.canAffectMesh(mesh)) {
  18787. continue;
  18788. }
  18789. needNormals = true;
  18790. this._defines["LIGHT" + lightIndex] = true;
  18791. var type;
  18792. if (light instanceof BABYLON.SpotLight) {
  18793. type = "SPOTLIGHT" + lightIndex;
  18794. }
  18795. else if (light instanceof BABYLON.HemisphericLight) {
  18796. type = "HEMILIGHT" + lightIndex;
  18797. }
  18798. else {
  18799. type = "POINTDIRLIGHT" + lightIndex;
  18800. }
  18801. this._defines[type] = true;
  18802. // Specular
  18803. if (!light.specular.equalsFloats(0, 0, 0)) {
  18804. this._defines.SPECULARTERM = true;
  18805. }
  18806. // Shadows
  18807. if (scene.shadowsEnabled) {
  18808. var shadowGenerator = light.getShadowGenerator();
  18809. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18810. this._defines["SHADOW" + lightIndex] = true;
  18811. this._defines.SHADOWS = true;
  18812. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18813. this._defines["SHADOWVSM" + lightIndex] = true;
  18814. }
  18815. if (shadowGenerator.usePoissonSampling) {
  18816. this._defines["SHADOWPCF" + lightIndex] = true;
  18817. }
  18818. }
  18819. }
  18820. lightIndex++;
  18821. if (lightIndex === maxSimultaneousLights)
  18822. break;
  18823. }
  18824. }
  18825. if (StandardMaterial.FresnelEnabled) {
  18826. // Fresnel
  18827. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18828. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18829. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18830. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18831. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18832. this._defines.DIFFUSEFRESNEL = true;
  18833. }
  18834. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18835. this._defines.OPACITYFRESNEL = true;
  18836. }
  18837. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18838. this._defines.REFLECTIONFRESNEL = true;
  18839. }
  18840. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18841. this._defines.EMISSIVEFRESNEL = true;
  18842. }
  18843. needNormals = true;
  18844. this._defines.FRESNEL = true;
  18845. }
  18846. }
  18847. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  18848. this._defines.SPECULAROVERALPHA = true;
  18849. }
  18850. // Attribs
  18851. if (mesh) {
  18852. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18853. this._defines.NORMAL = true;
  18854. }
  18855. if (needUVs) {
  18856. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18857. this._defines.UV1 = true;
  18858. }
  18859. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18860. this._defines.UV2 = true;
  18861. }
  18862. }
  18863. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18864. this._defines.VERTEXCOLOR = true;
  18865. if (mesh.hasVertexAlpha) {
  18866. this._defines.VERTEXALPHA = true;
  18867. }
  18868. }
  18869. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  18870. this._defines.BONES = true;
  18871. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  18872. this._defines.BONES4 = true;
  18873. }
  18874. // Instances
  18875. if (useInstances) {
  18876. this._defines.INSTANCES = true;
  18877. }
  18878. }
  18879. // Get correct effect
  18880. if (!this._defines.isEqual(this._cachedDefines)) {
  18881. this._defines.cloneTo(this._cachedDefines);
  18882. scene.resetCachedMaterial();
  18883. // Fallbacks
  18884. var fallbacks = new BABYLON.EffectFallbacks();
  18885. if (this._defines.REFLECTION) {
  18886. fallbacks.addFallback(0, "REFLECTION");
  18887. }
  18888. if (this._defines.SPECULAR) {
  18889. fallbacks.addFallback(0, "SPECULAR");
  18890. }
  18891. if (this._defines.BUMP) {
  18892. fallbacks.addFallback(0, "BUMP");
  18893. }
  18894. if (this._defines.SPECULAROVERALPHA) {
  18895. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18896. }
  18897. if (this._defines.FOG) {
  18898. fallbacks.addFallback(1, "FOG");
  18899. }
  18900. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  18901. if (!this._defines["LIGHT" + lightIndex]) {
  18902. continue;
  18903. }
  18904. if (lightIndex > 0) {
  18905. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18906. }
  18907. if (this._defines["SHADOW" + lightIndex]) {
  18908. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18909. }
  18910. if (this._defines["SHADOWPCF" + lightIndex]) {
  18911. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18912. }
  18913. if (this._defines["SHADOWVSM" + lightIndex]) {
  18914. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18915. }
  18916. }
  18917. if (this._defines.SPECULARTERM) {
  18918. fallbacks.addFallback(0, "SPECULARTERM");
  18919. }
  18920. if (this._defines.DIFFUSEFRESNEL) {
  18921. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  18922. }
  18923. if (this._defines.OPACITYFRESNEL) {
  18924. fallbacks.addFallback(2, "OPACITYFRESNEL");
  18925. }
  18926. if (this._defines.REFLECTIONFRESNEL) {
  18927. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  18928. }
  18929. if (this._defines.EMISSIVEFRESNEL) {
  18930. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  18931. }
  18932. if (this._defines.FRESNEL) {
  18933. fallbacks.addFallback(4, "FRESNEL");
  18934. }
  18935. if (this._defines.BONES4) {
  18936. fallbacks.addFallback(0, "BONES4");
  18937. }
  18938. //Attributes
  18939. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18940. if (this._defines.NORMAL) {
  18941. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18942. }
  18943. if (this._defines.UV1) {
  18944. attribs.push(BABYLON.VertexBuffer.UVKind);
  18945. }
  18946. if (this._defines.UV2) {
  18947. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18948. }
  18949. if (this._defines.VERTEXCOLOR) {
  18950. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18951. }
  18952. if (this._defines.BONES) {
  18953. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18954. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18955. }
  18956. if (this._defines.INSTANCES) {
  18957. attribs.push("world0");
  18958. attribs.push("world1");
  18959. attribs.push("world2");
  18960. attribs.push("world3");
  18961. }
  18962. // Legacy browser patch
  18963. var shaderName = "default";
  18964. if (!scene.getEngine().getCaps().standardDerivatives) {
  18965. shaderName = "legacydefault";
  18966. }
  18967. var join = this._defines.toString();
  18968. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18969. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18970. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18971. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18972. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18973. "vFogInfos", "vFogColor", "pointSize",
  18974. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18975. "mBones",
  18976. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18977. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18978. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18979. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18980. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18981. ], join, fallbacks, this.onCompiled, this.onError);
  18982. }
  18983. if (!this._effect.isReady()) {
  18984. return false;
  18985. }
  18986. this._renderId = scene.getRenderId();
  18987. this._wasPreviouslyReady = true;
  18988. return true;
  18989. };
  18990. StandardMaterial.prototype.unbind = function () {
  18991. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18992. this._effect.setTexture("reflection2DSampler", null);
  18993. }
  18994. _super.prototype.unbind.call(this);
  18995. };
  18996. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18997. this._effect.setMatrix("world", world);
  18998. };
  18999. StandardMaterial.prototype.bind = function (world, mesh) {
  19000. var scene = this.getScene();
  19001. // Matrices
  19002. this.bindOnlyWorldMatrix(world);
  19003. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  19004. // Bones
  19005. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  19006. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  19007. }
  19008. if (scene.getCachedMaterial() !== this) {
  19009. if (StandardMaterial.FresnelEnabled) {
  19010. // Fresnel
  19011. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  19012. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  19013. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  19014. }
  19015. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  19016. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  19017. }
  19018. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  19019. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  19020. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  19021. }
  19022. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  19023. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  19024. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  19025. }
  19026. }
  19027. // Textures
  19028. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  19029. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  19030. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  19031. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  19032. }
  19033. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  19034. this._effect.setTexture("ambientSampler", this.ambientTexture);
  19035. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  19036. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  19037. }
  19038. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  19039. this._effect.setTexture("opacitySampler", this.opacityTexture);
  19040. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  19041. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  19042. }
  19043. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  19044. if (this.reflectionTexture.isCube) {
  19045. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  19046. }
  19047. else {
  19048. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  19049. }
  19050. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  19051. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  19052. }
  19053. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  19054. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  19055. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  19056. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  19057. }
  19058. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  19059. this._effect.setTexture("specularSampler", this.specularTexture);
  19060. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  19061. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  19062. }
  19063. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  19064. this._effect.setTexture("bumpSampler", this.bumpTexture);
  19065. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  19066. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  19067. }
  19068. // Clip plane
  19069. if (scene.clipPlane) {
  19070. var clipPlane = scene.clipPlane;
  19071. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  19072. }
  19073. // Point size
  19074. if (this.pointsCloud) {
  19075. this._effect.setFloat("pointSize", this.pointSize);
  19076. }
  19077. // Colors
  19078. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  19079. // Scaling down color according to emissive
  19080. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19081. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19082. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19083. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  19084. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  19085. if (this._defines.SPECULARTERM) {
  19086. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  19087. }
  19088. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  19089. }
  19090. // Scaling down color according to emissive
  19091. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  19092. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  19093. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  19094. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  19095. if (scene.lightsEnabled) {
  19096. var lightIndex = 0;
  19097. for (var index = 0; index < scene.lights.length; index++) {
  19098. var light = scene.lights[index];
  19099. if (!light.isEnabled()) {
  19100. continue;
  19101. }
  19102. if (!light.canAffectMesh(mesh)) {
  19103. continue;
  19104. }
  19105. if (light instanceof BABYLON.PointLight) {
  19106. // Point Light
  19107. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19108. }
  19109. else if (light instanceof BABYLON.DirectionalLight) {
  19110. // Directional Light
  19111. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  19112. }
  19113. else if (light instanceof BABYLON.SpotLight) {
  19114. // Spot Light
  19115. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  19116. }
  19117. else if (light instanceof BABYLON.HemisphericLight) {
  19118. // Hemispheric Light
  19119. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  19120. }
  19121. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  19122. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  19123. if (this._defines.SPECULARTERM) {
  19124. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  19125. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  19126. }
  19127. // Shadows
  19128. if (scene.shadowsEnabled) {
  19129. var shadowGenerator = light.getShadowGenerator();
  19130. if (mesh.receiveShadows && shadowGenerator) {
  19131. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  19132. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  19133. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  19134. }
  19135. }
  19136. lightIndex++;
  19137. if (lightIndex === maxSimultaneousLights)
  19138. break;
  19139. }
  19140. }
  19141. // View
  19142. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  19143. this._effect.setMatrix("view", scene.getViewMatrix());
  19144. }
  19145. // Fog
  19146. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  19147. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  19148. this._effect.setColor3("vFogColor", scene.fogColor);
  19149. }
  19150. _super.prototype.bind.call(this, world, mesh);
  19151. };
  19152. StandardMaterial.prototype.getAnimatables = function () {
  19153. var results = [];
  19154. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  19155. results.push(this.diffuseTexture);
  19156. }
  19157. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  19158. results.push(this.ambientTexture);
  19159. }
  19160. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  19161. results.push(this.opacityTexture);
  19162. }
  19163. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  19164. results.push(this.reflectionTexture);
  19165. }
  19166. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  19167. results.push(this.emissiveTexture);
  19168. }
  19169. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  19170. results.push(this.specularTexture);
  19171. }
  19172. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  19173. results.push(this.bumpTexture);
  19174. }
  19175. return results;
  19176. };
  19177. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  19178. if (this.diffuseTexture) {
  19179. this.diffuseTexture.dispose();
  19180. }
  19181. if (this.ambientTexture) {
  19182. this.ambientTexture.dispose();
  19183. }
  19184. if (this.opacityTexture) {
  19185. this.opacityTexture.dispose();
  19186. }
  19187. if (this.reflectionTexture) {
  19188. this.reflectionTexture.dispose();
  19189. }
  19190. if (this.emissiveTexture) {
  19191. this.emissiveTexture.dispose();
  19192. }
  19193. if (this.specularTexture) {
  19194. this.specularTexture.dispose();
  19195. }
  19196. if (this.bumpTexture) {
  19197. this.bumpTexture.dispose();
  19198. }
  19199. _super.prototype.dispose.call(this, forceDisposeEffect);
  19200. };
  19201. StandardMaterial.prototype.clone = function (name) {
  19202. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  19203. // Base material
  19204. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  19205. newStandardMaterial.alpha = this.alpha;
  19206. newStandardMaterial.fillMode = this.fillMode;
  19207. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  19208. // Standard material
  19209. if (this.diffuseTexture && this.diffuseTexture.clone) {
  19210. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  19211. }
  19212. if (this.ambientTexture && this.ambientTexture.clone) {
  19213. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  19214. }
  19215. if (this.opacityTexture && this.opacityTexture.clone) {
  19216. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  19217. }
  19218. if (this.reflectionTexture && this.reflectionTexture.clone) {
  19219. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  19220. }
  19221. if (this.emissiveTexture && this.emissiveTexture.clone) {
  19222. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  19223. }
  19224. if (this.specularTexture && this.specularTexture.clone) {
  19225. newStandardMaterial.specularTexture = this.specularTexture.clone();
  19226. }
  19227. if (this.bumpTexture && this.bumpTexture.clone) {
  19228. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  19229. }
  19230. newStandardMaterial.ambientColor = this.ambientColor.clone();
  19231. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  19232. newStandardMaterial.specularColor = this.specularColor.clone();
  19233. newStandardMaterial.specularPower = this.specularPower;
  19234. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  19235. return newStandardMaterial;
  19236. };
  19237. // Statics
  19238. // Flags used to enable or disable a type of texture for all Standard Materials
  19239. StandardMaterial.DiffuseTextureEnabled = true;
  19240. StandardMaterial.AmbientTextureEnabled = true;
  19241. StandardMaterial.OpacityTextureEnabled = true;
  19242. StandardMaterial.ReflectionTextureEnabled = true;
  19243. StandardMaterial.EmissiveTextureEnabled = true;
  19244. StandardMaterial.SpecularTextureEnabled = true;
  19245. StandardMaterial.BumpTextureEnabled = true;
  19246. StandardMaterial.FresnelEnabled = true;
  19247. return StandardMaterial;
  19248. })(BABYLON.Material);
  19249. BABYLON.StandardMaterial = StandardMaterial;
  19250. })(BABYLON || (BABYLON = {}));
  19251. var BABYLON;
  19252. (function (BABYLON) {
  19253. var MultiMaterial = (function (_super) {
  19254. __extends(MultiMaterial, _super);
  19255. function MultiMaterial(name, scene) {
  19256. _super.call(this, name, scene, true);
  19257. this.subMaterials = new Array();
  19258. scene.multiMaterials.push(this);
  19259. }
  19260. // Properties
  19261. MultiMaterial.prototype.getSubMaterial = function (index) {
  19262. if (index < 0 || index >= this.subMaterials.length) {
  19263. return this.getScene().defaultMaterial;
  19264. }
  19265. return this.subMaterials[index];
  19266. };
  19267. // Methods
  19268. MultiMaterial.prototype.isReady = function (mesh) {
  19269. for (var index = 0; index < this.subMaterials.length; index++) {
  19270. var subMaterial = this.subMaterials[index];
  19271. if (subMaterial) {
  19272. if (!this.subMaterials[index].isReady(mesh)) {
  19273. return false;
  19274. }
  19275. }
  19276. }
  19277. return true;
  19278. };
  19279. MultiMaterial.prototype.clone = function (name) {
  19280. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  19281. for (var index = 0; index < this.subMaterials.length; index++) {
  19282. var subMaterial = this.subMaterials[index];
  19283. newMultiMaterial.subMaterials.push(subMaterial);
  19284. }
  19285. return newMultiMaterial;
  19286. };
  19287. return MultiMaterial;
  19288. })(BABYLON.Material);
  19289. BABYLON.MultiMaterial = MultiMaterial;
  19290. })(BABYLON || (BABYLON = {}));
  19291. var BABYLON;
  19292. (function (BABYLON) {
  19293. var SceneLoader = (function () {
  19294. function SceneLoader() {
  19295. }
  19296. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19297. get: function () {
  19298. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19299. },
  19300. set: function (value) {
  19301. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19302. },
  19303. enumerable: true,
  19304. configurable: true
  19305. });
  19306. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19307. get: function () {
  19308. return SceneLoader._ShowLoadingScreen;
  19309. },
  19310. set: function (value) {
  19311. SceneLoader._ShowLoadingScreen = value;
  19312. },
  19313. enumerable: true,
  19314. configurable: true
  19315. });
  19316. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19317. var dotPosition = sceneFilename.lastIndexOf(".");
  19318. var queryStringPosition = sceneFilename.indexOf("?");
  19319. if (queryStringPosition === -1) {
  19320. queryStringPosition = sceneFilename.length;
  19321. }
  19322. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19323. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19324. var plugin = this._registeredPlugins[index];
  19325. if (plugin.extensions.indexOf(extension) !== -1) {
  19326. return plugin;
  19327. }
  19328. }
  19329. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19330. };
  19331. // Public functions
  19332. SceneLoader.RegisterPlugin = function (plugin) {
  19333. plugin.extensions = plugin.extensions.toLowerCase();
  19334. SceneLoader._registeredPlugins.push(plugin);
  19335. };
  19336. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19337. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19338. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19339. return;
  19340. }
  19341. var loadingToken = {};
  19342. scene._addPendingData(loadingToken);
  19343. var manifestChecked = function (success) {
  19344. scene.database = database;
  19345. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19346. var importMeshFromData = function (data) {
  19347. var meshes = [];
  19348. var particleSystems = [];
  19349. var skeletons = [];
  19350. try {
  19351. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19352. if (onerror) {
  19353. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  19354. }
  19355. scene._removePendingData(loadingToken);
  19356. return;
  19357. }
  19358. }
  19359. catch (e) {
  19360. if (onerror) {
  19361. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  19362. }
  19363. scene._removePendingData(loadingToken);
  19364. return;
  19365. }
  19366. if (onsuccess) {
  19367. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19368. onsuccess(meshes, particleSystems, skeletons);
  19369. scene._removePendingData(loadingToken);
  19370. }
  19371. };
  19372. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19373. // Direct load
  19374. importMeshFromData(sceneFilename.substr(5));
  19375. return;
  19376. }
  19377. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19378. importMeshFromData(data);
  19379. }, progressCallBack, database);
  19380. };
  19381. if (scene.getEngine().enableOfflineSupport) {
  19382. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19383. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19384. }
  19385. else {
  19386. manifestChecked(true);
  19387. }
  19388. };
  19389. /**
  19390. * Load a scene
  19391. * @param rootUrl a string that defines the root url for scene and resources
  19392. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19393. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19394. */
  19395. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19396. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19397. };
  19398. /**
  19399. * Append a scene
  19400. * @param rootUrl a string that defines the root url for scene and resources
  19401. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19402. * @param scene is the instance of BABYLON.Scene to append to
  19403. */
  19404. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19405. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19406. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19407. return;
  19408. }
  19409. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19410. var database;
  19411. var loadingToken = {};
  19412. scene._addPendingData(loadingToken);
  19413. if (SceneLoader.ShowLoadingScreen) {
  19414. scene.getEngine().displayLoadingUI();
  19415. }
  19416. var loadSceneFromData = function (data) {
  19417. scene.database = database;
  19418. if (!plugin.load(scene, data, rootUrl)) {
  19419. if (onerror) {
  19420. onerror(scene);
  19421. }
  19422. scene._removePendingData(loadingToken);
  19423. scene.getEngine().hideLoadingUI();
  19424. return;
  19425. }
  19426. if (onsuccess) {
  19427. onsuccess(scene);
  19428. }
  19429. scene._removePendingData(loadingToken);
  19430. if (SceneLoader.ShowLoadingScreen) {
  19431. scene.executeWhenReady(function () {
  19432. scene.getEngine().hideLoadingUI();
  19433. });
  19434. }
  19435. };
  19436. var manifestChecked = function (success) {
  19437. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19438. };
  19439. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19440. // Direct load
  19441. loadSceneFromData(sceneFilename.substr(5));
  19442. return;
  19443. }
  19444. if (rootUrl.indexOf("file:") === -1) {
  19445. if (scene.getEngine().enableOfflineSupport) {
  19446. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19447. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19448. }
  19449. else {
  19450. manifestChecked(true);
  19451. }
  19452. }
  19453. else {
  19454. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19455. }
  19456. };
  19457. // Flags
  19458. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19459. SceneLoader._ShowLoadingScreen = true;
  19460. // Members
  19461. SceneLoader._registeredPlugins = new Array();
  19462. return SceneLoader;
  19463. })();
  19464. BABYLON.SceneLoader = SceneLoader;
  19465. ;
  19466. })(BABYLON || (BABYLON = {}));
  19467. var BABYLON;
  19468. (function (BABYLON) {
  19469. var Internals;
  19470. (function (Internals) {
  19471. var checkColors4 = function (colors, count) {
  19472. // Check if color3 was used
  19473. if (colors.length === count * 3) {
  19474. var colors4 = [];
  19475. for (var index = 0; index < colors.length; index += 3) {
  19476. var newIndex = (index / 3) * 4;
  19477. colors4[newIndex] = colors[index];
  19478. colors4[newIndex + 1] = colors[index + 1];
  19479. colors4[newIndex + 2] = colors[index + 2];
  19480. colors4[newIndex + 3] = 1.0;
  19481. }
  19482. return colors4;
  19483. }
  19484. return colors;
  19485. };
  19486. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19487. var texture = null;
  19488. if ((parsedTexture.name || parsedTexture.extensions) && !parsedTexture.isRenderTarget) {
  19489. texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  19490. texture.name = parsedTexture.name;
  19491. texture.hasAlpha = parsedTexture.hasAlpha;
  19492. texture.level = parsedTexture.level;
  19493. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19494. }
  19495. return texture;
  19496. };
  19497. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19498. if (parsedTexture.isCube) {
  19499. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19500. }
  19501. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19502. return null;
  19503. }
  19504. var texture;
  19505. if (parsedTexture.mirrorPlane) {
  19506. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19507. texture._waitingRenderList = parsedTexture.renderList;
  19508. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19509. }
  19510. else if (parsedTexture.isRenderTarget) {
  19511. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19512. texture._waitingRenderList = parsedTexture.renderList;
  19513. }
  19514. else {
  19515. if (parsedTexture.base64String) {
  19516. texture = BABYLON.Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  19517. }
  19518. else {
  19519. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19520. }
  19521. }
  19522. texture.name = parsedTexture.name;
  19523. texture.hasAlpha = parsedTexture.hasAlpha;
  19524. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19525. texture.level = parsedTexture.level;
  19526. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19527. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19528. texture.uOffset = parsedTexture.uOffset;
  19529. texture.vOffset = parsedTexture.vOffset;
  19530. texture.uScale = parsedTexture.uScale;
  19531. texture.vScale = parsedTexture.vScale;
  19532. texture.uAng = parsedTexture.uAng;
  19533. texture.vAng = parsedTexture.vAng;
  19534. texture.wAng = parsedTexture.wAng;
  19535. texture.wrapU = parsedTexture.wrapU;
  19536. texture.wrapV = parsedTexture.wrapV;
  19537. // Animations
  19538. if (parsedTexture.animations) {
  19539. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19540. var parsedAnimation = parsedTexture.animations[animationIndex];
  19541. texture.animations.push(parseAnimation(parsedAnimation));
  19542. }
  19543. }
  19544. return texture;
  19545. };
  19546. var parseSkeleton = function (parsedSkeleton, scene) {
  19547. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19548. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19549. var parsedBone = parsedSkeleton.bones[index];
  19550. var parentBone = null;
  19551. if (parsedBone.parentBoneIndex > -1) {
  19552. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19553. }
  19554. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19555. if (parsedBone.animation) {
  19556. bone.animations.push(parseAnimation(parsedBone.animation));
  19557. }
  19558. }
  19559. return skeleton;
  19560. };
  19561. var parseFresnelParameters = function (parsedFresnelParameters) {
  19562. var fresnelParameters = new BABYLON.FresnelParameters();
  19563. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19564. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19565. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19566. fresnelParameters.bias = parsedFresnelParameters.bias;
  19567. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19568. return fresnelParameters;
  19569. };
  19570. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19571. var material;
  19572. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19573. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19574. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19575. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19576. material.specularPower = parsedMaterial.specularPower;
  19577. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19578. material.alpha = parsedMaterial.alpha;
  19579. material.id = parsedMaterial.id;
  19580. if (parsedMaterial.disableDepthWrite) {
  19581. material.disableDepthWrite = parsedMaterial.disableDepthWrite;
  19582. }
  19583. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19584. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19585. material.wireframe = parsedMaterial.wireframe;
  19586. if (parsedMaterial.diffuseTexture) {
  19587. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19588. }
  19589. if (parsedMaterial.diffuseFresnelParameters) {
  19590. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19591. }
  19592. if (parsedMaterial.ambientTexture) {
  19593. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19594. }
  19595. if (parsedMaterial.opacityTexture) {
  19596. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19597. }
  19598. if (parsedMaterial.opacityFresnelParameters) {
  19599. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19600. }
  19601. if (parsedMaterial.reflectionTexture) {
  19602. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19603. }
  19604. if (parsedMaterial.reflectionFresnelParameters) {
  19605. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19606. }
  19607. if (parsedMaterial.emissiveTexture) {
  19608. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19609. }
  19610. if (parsedMaterial.emissiveFresnelParameters) {
  19611. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19612. }
  19613. if (parsedMaterial.specularTexture) {
  19614. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19615. }
  19616. if (parsedMaterial.bumpTexture) {
  19617. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19618. }
  19619. if (parsedMaterial.checkReadyOnlyOnce) {
  19620. material.checkReadyOnlyOnce = parsedMaterial.checkReadyOnlyOnce;
  19621. }
  19622. return material;
  19623. };
  19624. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19625. for (var index = 0; index < parsedData.materials.length; index++) {
  19626. var parsedMaterial = parsedData.materials[index];
  19627. if (parsedMaterial.id === id) {
  19628. return parseMaterial(parsedMaterial, scene, rootUrl);
  19629. }
  19630. }
  19631. return null;
  19632. };
  19633. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19634. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19635. multiMaterial.id = parsedMultiMaterial.id;
  19636. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19637. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19638. var subMatId = parsedMultiMaterial.materials[matIndex];
  19639. if (subMatId) {
  19640. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19641. }
  19642. else {
  19643. multiMaterial.subMaterials.push(null);
  19644. }
  19645. }
  19646. return multiMaterial;
  19647. };
  19648. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19649. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19650. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19651. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19652. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19653. var parsedFlare = parsedLensFlareSystem.flares[index];
  19654. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19655. }
  19656. return lensFlareSystem;
  19657. };
  19658. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19659. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19660. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19661. if (parsedParticleSystem.textureName) {
  19662. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19663. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19664. }
  19665. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19666. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19667. particleSystem.minSize = parsedParticleSystem.minSize;
  19668. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19669. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19670. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19671. particleSystem.emitter = emitter;
  19672. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19673. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19674. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19675. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19676. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19677. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19678. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19679. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19680. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19681. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19682. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19683. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19684. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19685. particleSystem.start();
  19686. return particleSystem;
  19687. };
  19688. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19689. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19690. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19691. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19692. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19693. shadowGenerator.getShadowMap().renderList.push(mesh);
  19694. }
  19695. if (parsedShadowGenerator.usePoissonSampling) {
  19696. shadowGenerator.usePoissonSampling = true;
  19697. }
  19698. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19699. shadowGenerator.useVarianceShadowMap = true;
  19700. }
  19701. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19702. shadowGenerator.useBlurVarianceShadowMap = true;
  19703. if (parsedShadowGenerator.blurScale) {
  19704. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19705. }
  19706. if (parsedShadowGenerator.blurBoxOffset) {
  19707. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19708. }
  19709. }
  19710. if (parsedShadowGenerator.bias !== undefined) {
  19711. shadowGenerator.bias = parsedShadowGenerator.bias;
  19712. }
  19713. return shadowGenerator;
  19714. };
  19715. var parseAnimation = function (parsedAnimation) {
  19716. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19717. var dataType = parsedAnimation.dataType;
  19718. var keys = [];
  19719. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19720. var key = parsedAnimation.keys[index];
  19721. var data;
  19722. switch (dataType) {
  19723. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19724. data = key.values[0];
  19725. break;
  19726. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19727. data = BABYLON.Quaternion.FromArray(key.values);
  19728. break;
  19729. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19730. data = BABYLON.Matrix.FromArray(key.values);
  19731. break;
  19732. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19733. default:
  19734. data = BABYLON.Vector3.FromArray(key.values);
  19735. break;
  19736. }
  19737. keys.push({
  19738. frame: key.frame,
  19739. value: data
  19740. });
  19741. }
  19742. animation.setKeys(keys);
  19743. return animation;
  19744. };
  19745. var parseLight = function (parsedLight, scene) {
  19746. var light;
  19747. switch (parsedLight.type) {
  19748. case 0:
  19749. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19750. break;
  19751. case 1:
  19752. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19753. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19754. break;
  19755. case 2:
  19756. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19757. break;
  19758. case 3:
  19759. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19760. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19761. break;
  19762. }
  19763. light.id = parsedLight.id;
  19764. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19765. if (parsedLight.intensity !== undefined) {
  19766. light.intensity = parsedLight.intensity;
  19767. }
  19768. if (parsedLight.range) {
  19769. light.range = parsedLight.range;
  19770. }
  19771. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19772. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19773. if (parsedLight.excludedMeshesIds) {
  19774. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19775. }
  19776. // Parent
  19777. if (parsedLight.parentId) {
  19778. light._waitingParentId = parsedLight.parentId;
  19779. }
  19780. if (parsedLight.includedOnlyMeshesIds) {
  19781. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19782. }
  19783. // Animations
  19784. if (parsedLight.animations) {
  19785. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19786. var parsedAnimation = parsedLight.animations[animationIndex];
  19787. light.animations.push(parseAnimation(parsedAnimation));
  19788. }
  19789. }
  19790. if (parsedLight.autoAnimate) {
  19791. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19792. }
  19793. };
  19794. var parseCamera = function (parsedCamera, scene) {
  19795. var camera;
  19796. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19797. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19798. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19799. var alpha = parsedCamera.alpha;
  19800. var beta = parsedCamera.beta;
  19801. var radius = parsedCamera.radius;
  19802. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19803. var interaxial_distance = parsedCamera.interaxial_distance;
  19804. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19805. }
  19806. else {
  19807. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19808. }
  19809. }
  19810. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19811. interaxial_distance = parsedCamera.interaxial_distance;
  19812. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19813. }
  19814. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19815. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19816. }
  19817. else if (parsedCamera.type === "FollowCamera") {
  19818. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19819. camera.heightOffset = parsedCamera.heightOffset;
  19820. camera.radius = parsedCamera.radius;
  19821. camera.rotationOffset = parsedCamera.rotationOffset;
  19822. if (lockedTargetMesh)
  19823. camera.target = lockedTargetMesh;
  19824. }
  19825. else if (parsedCamera.type === "GamepadCamera") {
  19826. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19827. }
  19828. else if (parsedCamera.type === "TouchCamera") {
  19829. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19830. }
  19831. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19832. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19833. }
  19834. else if (parsedCamera.type === "WebVRFreeCamera") {
  19835. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19836. }
  19837. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19838. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19839. }
  19840. else {
  19841. // Free Camera is the default value
  19842. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19843. }
  19844. // apply 3d rig, when found
  19845. if (parsedCamera.cameraRigMode) {
  19846. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  19847. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  19848. }
  19849. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19850. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19851. camera.lockedTarget = lockedTargetMesh;
  19852. }
  19853. camera.id = parsedCamera.id;
  19854. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19855. // Parent
  19856. if (parsedCamera.parentId) {
  19857. camera._waitingParentId = parsedCamera.parentId;
  19858. }
  19859. // Target
  19860. if (parsedCamera.target) {
  19861. if (camera.setTarget) {
  19862. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19863. }
  19864. else {
  19865. //For ArcRotate
  19866. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19867. }
  19868. }
  19869. else {
  19870. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19871. }
  19872. camera.fov = parsedCamera.fov;
  19873. camera.minZ = parsedCamera.minZ;
  19874. camera.maxZ = parsedCamera.maxZ;
  19875. camera.speed = parsedCamera.speed;
  19876. camera.inertia = parsedCamera.inertia;
  19877. camera.checkCollisions = parsedCamera.checkCollisions;
  19878. camera.applyGravity = parsedCamera.applyGravity;
  19879. if (parsedCamera.ellipsoid) {
  19880. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19881. }
  19882. // Animations
  19883. if (parsedCamera.animations) {
  19884. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19885. var parsedAnimation = parsedCamera.animations[animationIndex];
  19886. camera.animations.push(parseAnimation(parsedAnimation));
  19887. }
  19888. }
  19889. if (parsedCamera.autoAnimate) {
  19890. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19891. }
  19892. // Layer Mask
  19893. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19894. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19895. }
  19896. else {
  19897. camera.layerMask = 0x0FFFFFFF;
  19898. }
  19899. return camera;
  19900. };
  19901. var parseGeometry = function (parsedGeometry, scene) {
  19902. var id = parsedGeometry.id;
  19903. return scene.getGeometryByID(id);
  19904. };
  19905. var parseBox = function (parsedBox, scene) {
  19906. if (parseGeometry(parsedBox, scene)) {
  19907. return null; // null since geometry could be something else than a box...
  19908. }
  19909. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19910. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19911. scene.pushGeometry(box, true);
  19912. return box;
  19913. };
  19914. var parseSphere = function (parsedSphere, scene) {
  19915. if (parseGeometry(parsedSphere, scene)) {
  19916. return null; // null since geometry could be something else than a sphere...
  19917. }
  19918. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19919. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19920. scene.pushGeometry(sphere, true);
  19921. return sphere;
  19922. };
  19923. var parseCylinder = function (parsedCylinder, scene) {
  19924. if (parseGeometry(parsedCylinder, scene)) {
  19925. return null; // null since geometry could be something else than a cylinder...
  19926. }
  19927. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19928. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19929. scene.pushGeometry(cylinder, true);
  19930. return cylinder;
  19931. };
  19932. var parseTorus = function (parsedTorus, scene) {
  19933. if (parseGeometry(parsedTorus, scene)) {
  19934. return null; // null since geometry could be something else than a torus...
  19935. }
  19936. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19937. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19938. scene.pushGeometry(torus, true);
  19939. return torus;
  19940. };
  19941. var parseGround = function (parsedGround, scene) {
  19942. if (parseGeometry(parsedGround, scene)) {
  19943. return null; // null since geometry could be something else than a ground...
  19944. }
  19945. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19946. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19947. scene.pushGeometry(ground, true);
  19948. return ground;
  19949. };
  19950. var parsePlane = function (parsedPlane, scene) {
  19951. if (parseGeometry(parsedPlane, scene)) {
  19952. return null; // null since geometry could be something else than a plane...
  19953. }
  19954. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19955. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19956. scene.pushGeometry(plane, true);
  19957. return plane;
  19958. };
  19959. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19960. if (parseGeometry(parsedTorusKnot, scene)) {
  19961. return null; // null since geometry could be something else than a torusKnot...
  19962. }
  19963. 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);
  19964. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19965. scene.pushGeometry(torusKnot, true);
  19966. return torusKnot;
  19967. };
  19968. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19969. if (parseGeometry(parsedVertexData, scene)) {
  19970. return null; // null since geometry could be a primitive
  19971. }
  19972. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19973. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19974. if (parsedVertexData.delayLoadingFile) {
  19975. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19976. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19977. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19978. geometry._delayInfo = [];
  19979. if (parsedVertexData.hasUVs) {
  19980. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19981. }
  19982. if (parsedVertexData.hasUVs2) {
  19983. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19984. }
  19985. if (parsedVertexData.hasUVs3) {
  19986. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  19987. }
  19988. if (parsedVertexData.hasUVs4) {
  19989. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  19990. }
  19991. if (parsedVertexData.hasUVs5) {
  19992. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  19993. }
  19994. if (parsedVertexData.hasUVs6) {
  19995. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  19996. }
  19997. if (parsedVertexData.hasColors) {
  19998. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19999. }
  20000. if (parsedVertexData.hasMatricesIndices) {
  20001. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20002. }
  20003. if (parsedVertexData.hasMatricesWeights) {
  20004. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20005. }
  20006. geometry._delayLoadingFunction = importVertexData;
  20007. }
  20008. else {
  20009. importVertexData(parsedVertexData, geometry);
  20010. }
  20011. scene.pushGeometry(geometry, true);
  20012. return geometry;
  20013. };
  20014. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20015. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20016. mesh.id = parsedMesh.id;
  20017. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20018. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20019. if (parsedMesh.rotationQuaternion) {
  20020. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20021. }
  20022. else if (parsedMesh.rotation) {
  20023. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20024. }
  20025. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20026. if (parsedMesh.localMatrix) {
  20027. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20028. }
  20029. else if (parsedMesh.pivotMatrix) {
  20030. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20031. }
  20032. mesh.setEnabled(parsedMesh.isEnabled);
  20033. mesh.isVisible = parsedMesh.isVisible;
  20034. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20035. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20036. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20037. if (parsedMesh.applyFog !== undefined) {
  20038. mesh.applyFog = parsedMesh.applyFog;
  20039. }
  20040. if (parsedMesh.pickable !== undefined) {
  20041. mesh.isPickable = parsedMesh.pickable;
  20042. }
  20043. if (parsedMesh.alphaIndex !== undefined) {
  20044. mesh.alphaIndex = parsedMesh.alphaIndex;
  20045. }
  20046. mesh.receiveShadows = parsedMesh.receiveShadows;
  20047. mesh.billboardMode = parsedMesh.billboardMode;
  20048. if (parsedMesh.visibility !== undefined) {
  20049. mesh.visibility = parsedMesh.visibility;
  20050. }
  20051. mesh.checkCollisions = parsedMesh.checkCollisions;
  20052. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20053. // freezeWorldMatrix
  20054. if (parsedMesh.freezeWorldMatrix) {
  20055. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20056. }
  20057. // Parent
  20058. if (parsedMesh.parentId) {
  20059. mesh._waitingParentId = parsedMesh.parentId;
  20060. }
  20061. // Actions
  20062. if (parsedMesh.actions !== undefined) {
  20063. mesh._waitingActions = parsedMesh.actions;
  20064. }
  20065. // Geometry
  20066. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20067. if (parsedMesh.delayLoadingFile) {
  20068. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20069. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20070. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20071. if (parsedMesh._binaryInfo) {
  20072. mesh._binaryInfo = parsedMesh._binaryInfo;
  20073. }
  20074. mesh._delayInfo = [];
  20075. if (parsedMesh.hasUVs) {
  20076. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20077. }
  20078. if (parsedMesh.hasUVs2) {
  20079. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20080. }
  20081. if (parsedMesh.hasUVs3) {
  20082. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20083. }
  20084. if (parsedMesh.hasUVs4) {
  20085. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20086. }
  20087. if (parsedMesh.hasUVs5) {
  20088. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20089. }
  20090. if (parsedMesh.hasUVs6) {
  20091. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20092. }
  20093. if (parsedMesh.hasColors) {
  20094. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20095. }
  20096. if (parsedMesh.hasMatricesIndices) {
  20097. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20098. }
  20099. if (parsedMesh.hasMatricesWeights) {
  20100. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20101. }
  20102. mesh._delayLoadingFunction = importGeometry;
  20103. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20104. mesh._checkDelayState();
  20105. }
  20106. }
  20107. else {
  20108. importGeometry(parsedMesh, mesh);
  20109. }
  20110. // Material
  20111. if (parsedMesh.materialId) {
  20112. mesh.setMaterialByID(parsedMesh.materialId);
  20113. }
  20114. else {
  20115. mesh.material = null;
  20116. }
  20117. // Skeleton
  20118. if (parsedMesh.skeletonId > -1) {
  20119. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20120. }
  20121. // Physics
  20122. if (parsedMesh.physicsImpostor) {
  20123. if (!scene.isPhysicsEnabled()) {
  20124. scene.enablePhysics();
  20125. }
  20126. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20127. }
  20128. // Animations
  20129. if (parsedMesh.animations) {
  20130. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20131. var parsedAnimation = parsedMesh.animations[animationIndex];
  20132. mesh.animations.push(parseAnimation(parsedAnimation));
  20133. }
  20134. }
  20135. if (parsedMesh.autoAnimate) {
  20136. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20137. }
  20138. // Layer Mask
  20139. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20140. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20141. }
  20142. else {
  20143. mesh.layerMask = 0x0FFFFFFF;
  20144. }
  20145. // Instances
  20146. if (parsedMesh.instances) {
  20147. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20148. var parsedInstance = parsedMesh.instances[index];
  20149. var instance = mesh.createInstance(parsedInstance.name);
  20150. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20151. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20152. if (parsedInstance.rotationQuaternion) {
  20153. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20154. }
  20155. else if (parsedInstance.rotation) {
  20156. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20157. }
  20158. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20159. instance.checkCollisions = mesh.checkCollisions;
  20160. if (parsedMesh.animations) {
  20161. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20162. parsedAnimation = parsedMesh.animations[animationIndex];
  20163. instance.animations.push(parseAnimation(parsedAnimation));
  20164. }
  20165. }
  20166. }
  20167. }
  20168. return mesh;
  20169. };
  20170. var parseActions = function (parsedActions, object, scene) {
  20171. var actionManager = new BABYLON.ActionManager(scene);
  20172. if (object === null)
  20173. scene.actionManager = actionManager;
  20174. else
  20175. object.actionManager = actionManager;
  20176. // instanciate a new object
  20177. var instanciate = function (name, params) {
  20178. var newInstance = Object.create(BABYLON[name].prototype);
  20179. newInstance.constructor.apply(newInstance, params);
  20180. return newInstance;
  20181. };
  20182. var parseParameter = function (name, value, target, propertyPath) {
  20183. if (propertyPath === null) {
  20184. // String, boolean or float
  20185. var floatValue = parseFloat(value);
  20186. if (value === "true" || value === "false")
  20187. return value === "true";
  20188. else
  20189. return isNaN(floatValue) ? value : floatValue;
  20190. }
  20191. var effectiveTarget = propertyPath.split(".");
  20192. var values = value.split(",");
  20193. // Get effective Target
  20194. for (var i = 0; i < effectiveTarget.length; i++) {
  20195. target = target[effectiveTarget[i]];
  20196. }
  20197. // Return appropriate value with its type
  20198. if (typeof (target) === "boolean")
  20199. return values[0] === "true";
  20200. if (typeof (target) === "string")
  20201. return values[0];
  20202. // Parameters with multiple values such as Vector3 etc.
  20203. var split = new Array();
  20204. for (var i = 0; i < values.length; i++)
  20205. split.push(parseFloat(values[i]));
  20206. if (target instanceof BABYLON.Vector3)
  20207. return BABYLON.Vector3.FromArray(split);
  20208. if (target instanceof BABYLON.Vector4)
  20209. return BABYLON.Vector4.FromArray(split);
  20210. if (target instanceof BABYLON.Color3)
  20211. return BABYLON.Color3.FromArray(split);
  20212. if (target instanceof BABYLON.Color4)
  20213. return BABYLON.Color4.FromArray(split);
  20214. return parseFloat(values[0]);
  20215. };
  20216. // traverse graph per trigger
  20217. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20218. if (combineArray === void 0) { combineArray = null; }
  20219. if (parsedAction.detached)
  20220. return;
  20221. var parameters = new Array();
  20222. var target = null;
  20223. var propertyPath = null;
  20224. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20225. // Parameters
  20226. if (parsedAction.type === 2)
  20227. parameters.push(actionManager);
  20228. else
  20229. parameters.push(trigger);
  20230. if (combine) {
  20231. var actions = new Array();
  20232. for (var j = 0; j < parsedAction.combine.length; j++) {
  20233. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20234. }
  20235. parameters.push(actions);
  20236. }
  20237. else {
  20238. for (var i = 0; i < parsedAction.properties.length; i++) {
  20239. var value = parsedAction.properties[i].value;
  20240. var name = parsedAction.properties[i].name;
  20241. var targetType = parsedAction.properties[i].targetType;
  20242. if (name === "target")
  20243. if (targetType !== null && targetType === "SceneProperties")
  20244. value = target = scene;
  20245. else
  20246. value = target = scene.getNodeByName(value);
  20247. else if (name === "parent")
  20248. value = scene.getNodeByName(value);
  20249. else if (name === "sound")
  20250. value = scene.getSoundByName(value);
  20251. else if (name !== "propertyPath") {
  20252. if (parsedAction.type === 2 && name === "operator")
  20253. value = BABYLON.ValueCondition[value];
  20254. else
  20255. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20256. }
  20257. else {
  20258. propertyPath = value;
  20259. }
  20260. parameters.push(value);
  20261. }
  20262. }
  20263. if (combineArray === null) {
  20264. parameters.push(condition);
  20265. }
  20266. else {
  20267. parameters.push(null);
  20268. }
  20269. // If interpolate value action
  20270. if (parsedAction.name === "InterpolateValueAction") {
  20271. var param = parameters[parameters.length - 2];
  20272. parameters[parameters.length - 1] = param;
  20273. parameters[parameters.length - 2] = condition;
  20274. }
  20275. // Action or condition(s) and not CombineAction
  20276. var newAction = instanciate(parsedAction.name, parameters);
  20277. if (combineArray === null) {
  20278. if (newAction instanceof BABYLON.Condition) {
  20279. condition = newAction;
  20280. newAction = action;
  20281. }
  20282. else {
  20283. condition = null;
  20284. if (action)
  20285. action.then(newAction);
  20286. else
  20287. actionManager.registerAction(newAction);
  20288. }
  20289. }
  20290. else {
  20291. combineArray.push(newAction);
  20292. }
  20293. for (var i = 0; i < parsedAction.children.length; i++)
  20294. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20295. };
  20296. // triggers
  20297. for (var i = 0; i < parsedActions.children.length; i++) {
  20298. var triggerParams;
  20299. var trigger = parsedActions.children[i];
  20300. if (trigger.properties.length > 0) {
  20301. var param = trigger.properties[0].value;
  20302. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  20303. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20304. }
  20305. else
  20306. triggerParams = BABYLON.ActionManager[trigger.name];
  20307. for (var j = 0; j < trigger.children.length; j++) {
  20308. if (!trigger.detached)
  20309. traverse(trigger.children[j], triggerParams, null, null);
  20310. }
  20311. }
  20312. };
  20313. var parseSound = function (parsedSound, scene, rootUrl) {
  20314. var soundName = parsedSound.name;
  20315. var soundUrl = rootUrl + soundName;
  20316. var options = {
  20317. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  20318. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  20319. rolloffFactor: parsedSound.rolloffFactor,
  20320. refDistance: parsedSound.refDistance,
  20321. distanceModel: parsedSound.distanceModel,
  20322. playbackRate: parsedSound.playbackRate
  20323. };
  20324. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  20325. scene._addPendingData(newSound);
  20326. if (parsedSound.position) {
  20327. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20328. newSound.setPosition(soundPosition);
  20329. }
  20330. if (parsedSound.isDirectional) {
  20331. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20332. if (parsedSound.localDirectionToMesh) {
  20333. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20334. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20335. }
  20336. }
  20337. if (parsedSound.connectedMeshId) {
  20338. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20339. if (connectedMesh) {
  20340. newSound.attachToMesh(connectedMesh);
  20341. }
  20342. }
  20343. };
  20344. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20345. names = (names instanceof Array) ? names : [names];
  20346. for (var i in names) {
  20347. if (mesh.name === names[i]) {
  20348. hierarchyIds.push(mesh.id);
  20349. return true;
  20350. }
  20351. }
  20352. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20353. hierarchyIds.push(mesh.id);
  20354. return true;
  20355. }
  20356. return false;
  20357. };
  20358. var importVertexData = function (parsedVertexData, geometry) {
  20359. var vertexData = new BABYLON.VertexData();
  20360. // positions
  20361. var positions = parsedVertexData.positions;
  20362. if (positions) {
  20363. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20364. }
  20365. // normals
  20366. var normals = parsedVertexData.normals;
  20367. if (normals) {
  20368. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20369. }
  20370. // uvs
  20371. var uvs = parsedVertexData.uvs;
  20372. if (uvs) {
  20373. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20374. }
  20375. // uv2s
  20376. var uv2s = parsedVertexData.uv2s;
  20377. if (uv2s) {
  20378. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20379. }
  20380. // uv3s
  20381. var uv3s = parsedVertexData.uv3s;
  20382. if (uv3s) {
  20383. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  20384. }
  20385. // uv4s
  20386. var uv4s = parsedVertexData.uv4s;
  20387. if (uv4s) {
  20388. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  20389. }
  20390. // uv5s
  20391. var uv5s = parsedVertexData.uv5s;
  20392. if (uv5s) {
  20393. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  20394. }
  20395. // uv6s
  20396. var uv6s = parsedVertexData.uv6s;
  20397. if (uv6s) {
  20398. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  20399. }
  20400. // colors
  20401. var colors = parsedVertexData.colors;
  20402. if (colors) {
  20403. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20404. }
  20405. // matricesIndices
  20406. var matricesIndices = parsedVertexData.matricesIndices;
  20407. if (matricesIndices) {
  20408. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20409. }
  20410. // matricesWeights
  20411. var matricesWeights = parsedVertexData.matricesWeights;
  20412. if (matricesWeights) {
  20413. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20414. }
  20415. // indices
  20416. var indices = parsedVertexData.indices;
  20417. if (indices) {
  20418. vertexData.indices = indices;
  20419. }
  20420. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20421. };
  20422. var importGeometry = function (parsedGeometry, mesh) {
  20423. var scene = mesh.getScene();
  20424. // Geometry
  20425. var geometryId = parsedGeometry.geometryId;
  20426. if (geometryId) {
  20427. var geometry = scene.getGeometryByID(geometryId);
  20428. if (geometry) {
  20429. geometry.applyToMesh(mesh);
  20430. }
  20431. }
  20432. else if (parsedGeometry instanceof ArrayBuffer) {
  20433. var binaryInfo = mesh._binaryInfo;
  20434. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20435. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20436. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20437. }
  20438. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20439. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20440. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20441. }
  20442. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20443. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20444. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20445. }
  20446. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20447. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20448. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20449. }
  20450. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  20451. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  20452. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  20453. }
  20454. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  20455. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  20456. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  20457. }
  20458. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  20459. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  20460. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  20461. }
  20462. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  20463. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  20464. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  20465. }
  20466. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20467. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20468. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  20469. }
  20470. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20471. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20472. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20473. }
  20474. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20475. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20476. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20477. }
  20478. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20479. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20480. mesh.setIndices(indicesData);
  20481. }
  20482. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20483. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20484. mesh.subMeshes = [];
  20485. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20486. var materialIndex = subMeshesData[(i * 5) + 0];
  20487. var verticesStart = subMeshesData[(i * 5) + 1];
  20488. var verticesCount = subMeshesData[(i * 5) + 2];
  20489. var indexStart = subMeshesData[(i * 5) + 3];
  20490. var indexCount = subMeshesData[(i * 5) + 4];
  20491. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20492. }
  20493. }
  20494. }
  20495. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20496. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20497. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20498. if (parsedGeometry.uvs) {
  20499. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20500. }
  20501. if (parsedGeometry.uvs2) {
  20502. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20503. }
  20504. if (parsedGeometry.uvs3) {
  20505. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  20506. }
  20507. if (parsedGeometry.uvs4) {
  20508. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  20509. }
  20510. if (parsedGeometry.uvs5) {
  20511. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  20512. }
  20513. if (parsedGeometry.uvs6) {
  20514. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  20515. }
  20516. if (parsedGeometry.colors) {
  20517. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20518. }
  20519. if (parsedGeometry.matricesIndices) {
  20520. if (!parsedGeometry.matricesIndices._isExpanded) {
  20521. var floatIndices = [];
  20522. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20523. var matricesIndex = parsedGeometry.matricesIndices[i];
  20524. floatIndices.push(matricesIndex & 0x000000FF);
  20525. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20526. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20527. floatIndices.push(matricesIndex >> 24);
  20528. }
  20529. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20530. }
  20531. else {
  20532. delete parsedGeometry.matricesIndices._isExpanded;
  20533. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20534. }
  20535. }
  20536. if (parsedGeometry.matricesWeights) {
  20537. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20538. }
  20539. mesh.setIndices(parsedGeometry.indices);
  20540. }
  20541. // SubMeshes
  20542. if (parsedGeometry.subMeshes) {
  20543. mesh.subMeshes = [];
  20544. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20545. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20546. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20547. }
  20548. }
  20549. // Flat shading
  20550. if (mesh._shouldGenerateFlatShading) {
  20551. mesh.convertToFlatShadedMesh();
  20552. delete mesh._shouldGenerateFlatShading;
  20553. }
  20554. // Update
  20555. mesh.computeWorldMatrix(true);
  20556. // Octree
  20557. if (scene._selectionOctree) {
  20558. scene._selectionOctree.addMesh(mesh);
  20559. }
  20560. };
  20561. BABYLON.SceneLoader.RegisterPlugin({
  20562. extensions: ".babylon",
  20563. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20564. var parsedData = JSON.parse(data);
  20565. var loadedSkeletonsIds = [];
  20566. var loadedMaterialsIds = [];
  20567. var hierarchyIds = [];
  20568. for (var index = 0; index < parsedData.meshes.length; index++) {
  20569. var parsedMesh = parsedData.meshes[index];
  20570. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20571. if (meshesNames instanceof Array) {
  20572. // Remove found mesh name from list.
  20573. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20574. }
  20575. //Geometry?
  20576. if (parsedMesh.geometryId) {
  20577. //does the file contain geometries?
  20578. if (parsedData.geometries) {
  20579. //find the correct geometry and add it to the scene
  20580. var found = false;
  20581. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  20582. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  20583. return;
  20584. }
  20585. else {
  20586. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  20587. if (parsedGeometryData.id == parsedMesh.geometryId) {
  20588. switch (geometryType) {
  20589. case "boxes":
  20590. parseBox(parsedGeometryData, scene);
  20591. break;
  20592. case "spheres":
  20593. parseSphere(parsedGeometryData, scene);
  20594. break;
  20595. case "cylinders":
  20596. parseCylinder(parsedGeometryData, scene);
  20597. break;
  20598. case "toruses":
  20599. parseTorus(parsedGeometryData, scene);
  20600. break;
  20601. case "grounds":
  20602. parseGround(parsedGeometryData, scene);
  20603. break;
  20604. case "planes":
  20605. parsePlane(parsedGeometryData, scene);
  20606. break;
  20607. case "torusKnots":
  20608. parseTorusKnot(parsedGeometryData, scene);
  20609. break;
  20610. case "vertexData":
  20611. parseVertexData(parsedGeometryData, scene, rootUrl);
  20612. break;
  20613. }
  20614. found = true;
  20615. }
  20616. });
  20617. }
  20618. });
  20619. if (!found) {
  20620. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  20621. }
  20622. }
  20623. }
  20624. // Material ?
  20625. if (parsedMesh.materialId) {
  20626. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20627. if (!materialFound && parsedData.multiMaterials) {
  20628. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20629. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20630. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20631. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20632. var subMatId = parsedMultiMaterial.materials[matIndex];
  20633. loadedMaterialsIds.push(subMatId);
  20634. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20635. }
  20636. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20637. parseMultiMaterial(parsedMultiMaterial, scene);
  20638. materialFound = true;
  20639. break;
  20640. }
  20641. }
  20642. }
  20643. if (!materialFound) {
  20644. loadedMaterialsIds.push(parsedMesh.materialId);
  20645. if (!parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl)) {
  20646. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  20647. }
  20648. }
  20649. }
  20650. // Skeleton ?
  20651. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20652. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20653. if (!skeletonAlreadyLoaded) {
  20654. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20655. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20656. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20657. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20658. loadedSkeletonsIds.push(parsedSkeleton.id);
  20659. }
  20660. }
  20661. }
  20662. }
  20663. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20664. meshes.push(mesh);
  20665. }
  20666. }
  20667. // Connecting parents
  20668. for (index = 0; index < scene.meshes.length; index++) {
  20669. var currentMesh = scene.meshes[index];
  20670. if (currentMesh._waitingParentId) {
  20671. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20672. currentMesh._waitingParentId = undefined;
  20673. }
  20674. }
  20675. // freeze world matrix application
  20676. for (index = 0; index < scene.meshes.length; index++) {
  20677. var currentMesh = scene.meshes[index];
  20678. if (currentMesh._waitingFreezeWorldMatrix) {
  20679. currentMesh.freezeWorldMatrix();
  20680. currentMesh._waitingFreezeWorldMatrix = undefined;
  20681. }
  20682. }
  20683. // Particles
  20684. if (parsedData.particleSystems) {
  20685. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20686. var parsedParticleSystem = parsedData.particleSystems[index];
  20687. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20688. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20689. }
  20690. }
  20691. }
  20692. return true;
  20693. },
  20694. load: function (scene, data, rootUrl) {
  20695. var parsedData = JSON.parse(data);
  20696. // Scene
  20697. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20698. scene.autoClear = parsedData.autoClear;
  20699. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20700. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20701. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20702. // Fog
  20703. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20704. scene.fogMode = parsedData.fogMode;
  20705. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20706. scene.fogStart = parsedData.fogStart;
  20707. scene.fogEnd = parsedData.fogEnd;
  20708. scene.fogDensity = parsedData.fogDensity;
  20709. }
  20710. // Lights
  20711. for (var index = 0; index < parsedData.lights.length; index++) {
  20712. var parsedLight = parsedData.lights[index];
  20713. parseLight(parsedLight, scene);
  20714. }
  20715. // Materials
  20716. if (parsedData.materials) {
  20717. for (index = 0; index < parsedData.materials.length; index++) {
  20718. var parsedMaterial = parsedData.materials[index];
  20719. parseMaterial(parsedMaterial, scene, rootUrl);
  20720. }
  20721. }
  20722. if (parsedData.multiMaterials) {
  20723. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20724. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20725. parseMultiMaterial(parsedMultiMaterial, scene);
  20726. }
  20727. }
  20728. // Skeletons
  20729. if (parsedData.skeletons) {
  20730. for (index = 0; index < parsedData.skeletons.length; index++) {
  20731. var parsedSkeleton = parsedData.skeletons[index];
  20732. parseSkeleton(parsedSkeleton, scene);
  20733. }
  20734. }
  20735. // Geometries
  20736. var geometries = parsedData.geometries;
  20737. if (geometries) {
  20738. // Boxes
  20739. var boxes = geometries.boxes;
  20740. if (boxes) {
  20741. for (index = 0; index < boxes.length; index++) {
  20742. var parsedBox = boxes[index];
  20743. parseBox(parsedBox, scene);
  20744. }
  20745. }
  20746. // Spheres
  20747. var spheres = geometries.spheres;
  20748. if (spheres) {
  20749. for (index = 0; index < spheres.length; index++) {
  20750. var parsedSphere = spheres[index];
  20751. parseSphere(parsedSphere, scene);
  20752. }
  20753. }
  20754. // Cylinders
  20755. var cylinders = geometries.cylinders;
  20756. if (cylinders) {
  20757. for (index = 0; index < cylinders.length; index++) {
  20758. var parsedCylinder = cylinders[index];
  20759. parseCylinder(parsedCylinder, scene);
  20760. }
  20761. }
  20762. // Toruses
  20763. var toruses = geometries.toruses;
  20764. if (toruses) {
  20765. for (index = 0; index < toruses.length; index++) {
  20766. var parsedTorus = toruses[index];
  20767. parseTorus(parsedTorus, scene);
  20768. }
  20769. }
  20770. // Grounds
  20771. var grounds = geometries.grounds;
  20772. if (grounds) {
  20773. for (index = 0; index < grounds.length; index++) {
  20774. var parsedGround = grounds[index];
  20775. parseGround(parsedGround, scene);
  20776. }
  20777. }
  20778. // Planes
  20779. var planes = geometries.planes;
  20780. if (planes) {
  20781. for (index = 0; index < planes.length; index++) {
  20782. var parsedPlane = planes[index];
  20783. parsePlane(parsedPlane, scene);
  20784. }
  20785. }
  20786. // TorusKnots
  20787. var torusKnots = geometries.torusKnots;
  20788. if (torusKnots) {
  20789. for (index = 0; index < torusKnots.length; index++) {
  20790. var parsedTorusKnot = torusKnots[index];
  20791. parseTorusKnot(parsedTorusKnot, scene);
  20792. }
  20793. }
  20794. // VertexData
  20795. var vertexData = geometries.vertexData;
  20796. if (vertexData) {
  20797. for (index = 0; index < vertexData.length; index++) {
  20798. var parsedVertexData = vertexData[index];
  20799. parseVertexData(parsedVertexData, scene, rootUrl);
  20800. }
  20801. }
  20802. }
  20803. // Meshes
  20804. for (index = 0; index < parsedData.meshes.length; index++) {
  20805. var parsedMesh = parsedData.meshes[index];
  20806. parseMesh(parsedMesh, scene, rootUrl);
  20807. }
  20808. // Cameras
  20809. for (index = 0; index < parsedData.cameras.length; index++) {
  20810. var parsedCamera = parsedData.cameras[index];
  20811. parseCamera(parsedCamera, scene);
  20812. }
  20813. if (parsedData.activeCameraID) {
  20814. scene.setActiveCameraByID(parsedData.activeCameraID);
  20815. }
  20816. // Browsing all the graph to connect the dots
  20817. for (index = 0; index < scene.cameras.length; index++) {
  20818. var camera = scene.cameras[index];
  20819. if (camera._waitingParentId) {
  20820. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20821. camera._waitingParentId = undefined;
  20822. }
  20823. }
  20824. for (index = 0; index < scene.lights.length; index++) {
  20825. var light = scene.lights[index];
  20826. if (light._waitingParentId) {
  20827. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20828. light._waitingParentId = undefined;
  20829. }
  20830. }
  20831. // Sounds
  20832. if (parsedData.sounds) {
  20833. for (index = 0; index < parsedData.sounds.length; index++) {
  20834. var parsedSound = parsedData.sounds[index];
  20835. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20836. parseSound(parsedSound, scene, rootUrl);
  20837. }
  20838. else {
  20839. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20840. }
  20841. }
  20842. }
  20843. // Connect parents & children and parse actions
  20844. for (index = 0; index < scene.meshes.length; index++) {
  20845. var mesh = scene.meshes[index];
  20846. if (mesh._waitingParentId) {
  20847. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20848. mesh._waitingParentId = undefined;
  20849. }
  20850. if (mesh._waitingActions) {
  20851. parseActions(mesh._waitingActions, mesh, scene);
  20852. mesh._waitingActions = undefined;
  20853. }
  20854. }
  20855. // freeze world matrix application
  20856. for (index = 0; index < scene.meshes.length; index++) {
  20857. var currentMesh = scene.meshes[index];
  20858. if (currentMesh._waitingFreezeWorldMatrix) {
  20859. currentMesh.freezeWorldMatrix();
  20860. currentMesh._waitingFreezeWorldMatrix = undefined;
  20861. }
  20862. }
  20863. // Particles Systems
  20864. if (parsedData.particleSystems) {
  20865. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20866. var parsedParticleSystem = parsedData.particleSystems[index];
  20867. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20868. }
  20869. }
  20870. // Lens flares
  20871. if (parsedData.lensFlareSystems) {
  20872. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20873. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20874. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20875. }
  20876. }
  20877. // Shadows
  20878. if (parsedData.shadowGenerators) {
  20879. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20880. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20881. parseShadowGenerator(parsedShadowGenerator, scene);
  20882. }
  20883. }
  20884. // Actions (scene)
  20885. if (parsedData.actions) {
  20886. parseActions(parsedData.actions, null, scene);
  20887. }
  20888. // Finish
  20889. return true;
  20890. }
  20891. });
  20892. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20893. })(BABYLON || (BABYLON = {}));
  20894. var BABYLON;
  20895. (function (BABYLON) {
  20896. var SpriteManager = (function () {
  20897. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20899. this.name = name;
  20900. this.cellSize = cellSize;
  20901. this.sprites = new Array();
  20902. this.renderingGroupId = 0;
  20903. this.fogEnabled = true;
  20904. this._vertexDeclaration = [4, 4, 4, 4];
  20905. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20906. this._capacity = capacity;
  20907. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20908. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20909. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20910. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20911. this._scene = scene;
  20912. this._scene.spriteManagers.push(this);
  20913. // VBO
  20914. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20915. var indices = [];
  20916. var index = 0;
  20917. for (var count = 0; count < capacity; count++) {
  20918. indices.push(index);
  20919. indices.push(index + 1);
  20920. indices.push(index + 2);
  20921. indices.push(index);
  20922. indices.push(index + 2);
  20923. indices.push(index + 3);
  20924. index += 4;
  20925. }
  20926. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20927. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20928. // Effects
  20929. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20930. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20931. }
  20932. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20933. var arrayOffset = index * 16;
  20934. if (offsetX === 0)
  20935. offsetX = this._epsilon;
  20936. else if (offsetX === 1)
  20937. offsetX = 1 - this._epsilon;
  20938. if (offsetY === 0)
  20939. offsetY = this._epsilon;
  20940. else if (offsetY === 1)
  20941. offsetY = 1 - this._epsilon;
  20942. this._vertices[arrayOffset] = sprite.position.x;
  20943. this._vertices[arrayOffset + 1] = sprite.position.y;
  20944. this._vertices[arrayOffset + 2] = sprite.position.z;
  20945. this._vertices[arrayOffset + 3] = sprite.angle;
  20946. this._vertices[arrayOffset + 4] = sprite.width;
  20947. this._vertices[arrayOffset + 5] = sprite.height;
  20948. this._vertices[arrayOffset + 6] = offsetX;
  20949. this._vertices[arrayOffset + 7] = offsetY;
  20950. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20951. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20952. var offset = (sprite.cellIndex / rowSize) >> 0;
  20953. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20954. this._vertices[arrayOffset + 11] = offset;
  20955. // Color
  20956. this._vertices[arrayOffset + 12] = sprite.color.r;
  20957. this._vertices[arrayOffset + 13] = sprite.color.g;
  20958. this._vertices[arrayOffset + 14] = sprite.color.b;
  20959. this._vertices[arrayOffset + 15] = sprite.color.a;
  20960. };
  20961. SpriteManager.prototype.render = function () {
  20962. // Check
  20963. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20964. return;
  20965. var engine = this._scene.getEngine();
  20966. var baseSize = this._spriteTexture.getBaseSize();
  20967. // Sprites
  20968. var deltaTime = engine.getDeltaTime();
  20969. var max = Math.min(this._capacity, this.sprites.length);
  20970. var rowSize = baseSize.width / this.cellSize;
  20971. var offset = 0;
  20972. for (var index = 0; index < max; index++) {
  20973. var sprite = this.sprites[index];
  20974. if (!sprite) {
  20975. continue;
  20976. }
  20977. sprite._animate(deltaTime);
  20978. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20979. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20980. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20981. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20982. }
  20983. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20984. // Render
  20985. var effect = this._effectBase;
  20986. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20987. effect = this._effectFog;
  20988. }
  20989. engine.enableEffect(effect);
  20990. var viewMatrix = this._scene.getViewMatrix();
  20991. effect.setTexture("diffuseSampler", this._spriteTexture);
  20992. effect.setMatrix("view", viewMatrix);
  20993. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20994. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20995. // Fog
  20996. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20997. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20998. effect.setColor3("vFogColor", this._scene.fogColor);
  20999. }
  21000. // VBOs
  21001. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21002. // Draw order
  21003. engine.setDepthFunctionToLessOrEqual();
  21004. effect.setBool("alphaTest", true);
  21005. engine.setColorWrite(false);
  21006. engine.draw(true, 0, max * 6);
  21007. engine.setColorWrite(true);
  21008. effect.setBool("alphaTest", false);
  21009. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21010. engine.draw(true, 0, max * 6);
  21011. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21012. };
  21013. SpriteManager.prototype.dispose = function () {
  21014. if (this._vertexBuffer) {
  21015. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21016. this._vertexBuffer = null;
  21017. }
  21018. if (this._indexBuffer) {
  21019. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21020. this._indexBuffer = null;
  21021. }
  21022. if (this._spriteTexture) {
  21023. this._spriteTexture.dispose();
  21024. this._spriteTexture = null;
  21025. }
  21026. // Remove from scene
  21027. var index = this._scene.spriteManagers.indexOf(this);
  21028. this._scene.spriteManagers.splice(index, 1);
  21029. // Callback
  21030. if (this.onDispose) {
  21031. this.onDispose();
  21032. }
  21033. };
  21034. return SpriteManager;
  21035. })();
  21036. BABYLON.SpriteManager = SpriteManager;
  21037. })(BABYLON || (BABYLON = {}));
  21038. var BABYLON;
  21039. (function (BABYLON) {
  21040. var Sprite = (function () {
  21041. function Sprite(name, manager) {
  21042. this.name = name;
  21043. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21044. this.width = 1.0;
  21045. this.height = 1.0;
  21046. this.angle = 0;
  21047. this.cellIndex = 0;
  21048. this.invertU = 0;
  21049. this.invertV = 0;
  21050. this.animations = new Array();
  21051. this._animationStarted = false;
  21052. this._loopAnimation = false;
  21053. this._fromIndex = 0;
  21054. this._toIndex = 0;
  21055. this._delay = 0;
  21056. this._direction = 1;
  21057. this._frameCount = 0;
  21058. this._time = 0;
  21059. this._manager = manager;
  21060. this._manager.sprites.push(this);
  21061. this.position = BABYLON.Vector3.Zero();
  21062. }
  21063. Object.defineProperty(Sprite.prototype, "size", {
  21064. get: function () {
  21065. return this.width;
  21066. },
  21067. set: function (value) {
  21068. this.width = value;
  21069. this.height = value;
  21070. },
  21071. enumerable: true,
  21072. configurable: true
  21073. });
  21074. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  21075. this._fromIndex = from;
  21076. this._toIndex = to;
  21077. this._loopAnimation = loop;
  21078. this._delay = delay;
  21079. this._animationStarted = true;
  21080. this._direction = from < to ? 1 : -1;
  21081. this.cellIndex = from;
  21082. this._time = 0;
  21083. };
  21084. Sprite.prototype.stopAnimation = function () {
  21085. this._animationStarted = false;
  21086. };
  21087. Sprite.prototype._animate = function (deltaTime) {
  21088. if (!this._animationStarted)
  21089. return;
  21090. this._time += deltaTime;
  21091. if (this._time > this._delay) {
  21092. this._time = this._time % this._delay;
  21093. this.cellIndex += this._direction;
  21094. if (this.cellIndex == this._toIndex) {
  21095. if (this._loopAnimation) {
  21096. this.cellIndex = this._fromIndex;
  21097. }
  21098. else {
  21099. this._animationStarted = false;
  21100. if (this.disposeWhenFinishedAnimating) {
  21101. this.dispose();
  21102. }
  21103. }
  21104. }
  21105. }
  21106. };
  21107. Sprite.prototype.dispose = function () {
  21108. for (var i = 0; i < this._manager.sprites.length; i++) {
  21109. if (this._manager.sprites[i] == this) {
  21110. this._manager.sprites.splice(i, 1);
  21111. }
  21112. }
  21113. };
  21114. return Sprite;
  21115. })();
  21116. BABYLON.Sprite = Sprite;
  21117. })(BABYLON || (BABYLON = {}));
  21118. var BABYLON;
  21119. (function (BABYLON) {
  21120. var Layer = (function () {
  21121. function Layer(name, imgUrl, scene, isBackground, color) {
  21122. this.name = name;
  21123. this._vertexDeclaration = [2];
  21124. this._vertexStrideSize = 2 * 4;
  21125. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  21126. this.isBackground = isBackground === undefined ? true : isBackground;
  21127. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  21128. this._scene = scene;
  21129. this._scene.layers.push(this);
  21130. // VBO
  21131. var vertices = [];
  21132. vertices.push(1, 1);
  21133. vertices.push(-1, 1);
  21134. vertices.push(-1, -1);
  21135. vertices.push(1, -1);
  21136. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  21137. // Indices
  21138. var indices = [];
  21139. indices.push(0);
  21140. indices.push(1);
  21141. indices.push(2);
  21142. indices.push(0);
  21143. indices.push(2);
  21144. indices.push(3);
  21145. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21146. // Effects
  21147. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  21148. }
  21149. Layer.prototype.render = function () {
  21150. // Check
  21151. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  21152. return;
  21153. var engine = this._scene.getEngine();
  21154. // Render
  21155. engine.enableEffect(this._effect);
  21156. engine.setState(false);
  21157. // Texture
  21158. this._effect.setTexture("textureSampler", this.texture);
  21159. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  21160. // Color
  21161. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  21162. // VBOs
  21163. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21164. // Draw order
  21165. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21166. engine.draw(true, 0, 6);
  21167. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21168. };
  21169. Layer.prototype.dispose = function () {
  21170. if (this._vertexBuffer) {
  21171. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21172. this._vertexBuffer = null;
  21173. }
  21174. if (this._indexBuffer) {
  21175. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21176. this._indexBuffer = null;
  21177. }
  21178. if (this.texture) {
  21179. this.texture.dispose();
  21180. this.texture = null;
  21181. }
  21182. // Remove from scene
  21183. var index = this._scene.layers.indexOf(this);
  21184. this._scene.layers.splice(index, 1);
  21185. // Callback
  21186. if (this.onDispose) {
  21187. this.onDispose();
  21188. }
  21189. };
  21190. return Layer;
  21191. })();
  21192. BABYLON.Layer = Layer;
  21193. })(BABYLON || (BABYLON = {}));
  21194. var BABYLON;
  21195. (function (BABYLON) {
  21196. var Particle = (function () {
  21197. function Particle() {
  21198. this.position = BABYLON.Vector3.Zero();
  21199. this.direction = BABYLON.Vector3.Zero();
  21200. this.color = new BABYLON.Color4(0, 0, 0, 0);
  21201. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  21202. this.lifeTime = 1.0;
  21203. this.age = 0;
  21204. this.size = 0;
  21205. this.angle = 0;
  21206. this.angularSpeed = 0;
  21207. }
  21208. Particle.prototype.copyTo = function (other) {
  21209. other.position.copyFrom(this.position);
  21210. other.direction.copyFrom(this.direction);
  21211. other.color.copyFrom(this.color);
  21212. other.colorStep.copyFrom(this.colorStep);
  21213. other.lifeTime = this.lifeTime;
  21214. other.age = this.age;
  21215. other.size = this.size;
  21216. other.angle = this.angle;
  21217. other.angularSpeed = this.angularSpeed;
  21218. };
  21219. return Particle;
  21220. })();
  21221. BABYLON.Particle = Particle;
  21222. })(BABYLON || (BABYLON = {}));
  21223. var BABYLON;
  21224. (function (BABYLON) {
  21225. var randomNumber = function (min, max) {
  21226. if (min === max) {
  21227. return (min);
  21228. }
  21229. var random = Math.random();
  21230. return ((random * (max - min)) + min);
  21231. };
  21232. var ParticleSystem = (function () {
  21233. function ParticleSystem(name, capacity, scene, customEffect) {
  21234. var _this = this;
  21235. this.name = name;
  21236. this.renderingGroupId = 0;
  21237. this.emitter = null;
  21238. this.emitRate = 10;
  21239. this.manualEmitCount = -1;
  21240. this.updateSpeed = 0.01;
  21241. this.targetStopDuration = 0;
  21242. this.disposeOnStop = false;
  21243. this.minEmitPower = 1;
  21244. this.maxEmitPower = 1;
  21245. this.minLifeTime = 1;
  21246. this.maxLifeTime = 1;
  21247. this.minSize = 1;
  21248. this.maxSize = 1;
  21249. this.minAngularSpeed = 0;
  21250. this.maxAngularSpeed = 0;
  21251. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  21252. this.forceDepthWrite = false;
  21253. this.gravity = BABYLON.Vector3.Zero();
  21254. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  21255. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  21256. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  21257. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  21258. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21259. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21260. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  21261. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  21262. this.particles = new Array();
  21263. this._vertexDeclaration = [3, 4, 4];
  21264. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  21265. this._stockParticles = new Array();
  21266. this._newPartsExcess = 0;
  21267. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  21268. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  21269. this._scaledDirection = BABYLON.Vector3.Zero();
  21270. this._scaledGravity = BABYLON.Vector3.Zero();
  21271. this._currentRenderId = -1;
  21272. this._started = false;
  21273. this._stopped = false;
  21274. this._actualFrame = 0;
  21275. this.id = name;
  21276. this._capacity = capacity;
  21277. this._scene = scene;
  21278. this._customEffect = customEffect;
  21279. scene.particleSystems.push(this);
  21280. // VBO
  21281. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  21282. var indices = [];
  21283. var index = 0;
  21284. for (var count = 0; count < capacity; count++) {
  21285. indices.push(index);
  21286. indices.push(index + 1);
  21287. indices.push(index + 2);
  21288. indices.push(index);
  21289. indices.push(index + 2);
  21290. indices.push(index + 3);
  21291. index += 4;
  21292. }
  21293. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  21294. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  21295. // Default behaviors
  21296. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  21297. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  21298. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  21299. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  21300. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  21301. };
  21302. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  21303. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  21304. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  21305. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  21306. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  21307. };
  21308. this.updateFunction = function (particles) {
  21309. for (var index = 0; index < particles.length; index++) {
  21310. var particle = particles[index];
  21311. particle.age += _this._scaledUpdateSpeed;
  21312. if (particle.age >= particle.lifeTime) {
  21313. _this.recycleParticle(particle);
  21314. index--;
  21315. continue;
  21316. }
  21317. else {
  21318. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  21319. particle.color.addInPlace(_this._scaledColorStep);
  21320. if (particle.color.a < 0)
  21321. particle.color.a = 0;
  21322. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  21323. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  21324. particle.position.addInPlace(_this._scaledDirection);
  21325. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  21326. particle.direction.addInPlace(_this._scaledGravity);
  21327. }
  21328. }
  21329. };
  21330. }
  21331. ParticleSystem.prototype.recycleParticle = function (particle) {
  21332. var lastParticle = this.particles.pop();
  21333. if (lastParticle !== particle) {
  21334. lastParticle.copyTo(particle);
  21335. this._stockParticles.push(lastParticle);
  21336. }
  21337. };
  21338. ParticleSystem.prototype.getCapacity = function () {
  21339. return this._capacity;
  21340. };
  21341. ParticleSystem.prototype.isAlive = function () {
  21342. return this._alive;
  21343. };
  21344. ParticleSystem.prototype.isStarted = function () {
  21345. return this._started;
  21346. };
  21347. ParticleSystem.prototype.start = function () {
  21348. this._started = true;
  21349. this._stopped = false;
  21350. this._actualFrame = 0;
  21351. };
  21352. ParticleSystem.prototype.stop = function () {
  21353. this._stopped = true;
  21354. };
  21355. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  21356. var offset = index * 11;
  21357. this._vertices[offset] = particle.position.x;
  21358. this._vertices[offset + 1] = particle.position.y;
  21359. this._vertices[offset + 2] = particle.position.z;
  21360. this._vertices[offset + 3] = particle.color.r;
  21361. this._vertices[offset + 4] = particle.color.g;
  21362. this._vertices[offset + 5] = particle.color.b;
  21363. this._vertices[offset + 6] = particle.color.a;
  21364. this._vertices[offset + 7] = particle.angle;
  21365. this._vertices[offset + 8] = particle.size;
  21366. this._vertices[offset + 9] = offsetX;
  21367. this._vertices[offset + 10] = offsetY;
  21368. };
  21369. ParticleSystem.prototype._update = function (newParticles) {
  21370. // Update current
  21371. this._alive = this.particles.length > 0;
  21372. this.updateFunction(this.particles);
  21373. // Add new ones
  21374. var worldMatrix;
  21375. if (this.emitter.position) {
  21376. worldMatrix = this.emitter.getWorldMatrix();
  21377. }
  21378. else {
  21379. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  21380. }
  21381. for (var index = 0; index < newParticles; index++) {
  21382. if (this.particles.length === this._capacity) {
  21383. break;
  21384. }
  21385. if (this._stockParticles.length !== 0) {
  21386. var particle = this._stockParticles.pop();
  21387. particle.age = 0;
  21388. }
  21389. else {
  21390. particle = new BABYLON.Particle();
  21391. }
  21392. this.particles.push(particle);
  21393. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  21394. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  21395. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  21396. particle.size = randomNumber(this.minSize, this.maxSize);
  21397. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  21398. this.startPositionFunction(worldMatrix, particle.position);
  21399. var step = randomNumber(0, 1.0);
  21400. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  21401. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  21402. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  21403. }
  21404. };
  21405. ParticleSystem.prototype._getEffect = function () {
  21406. if (this._customEffect) {
  21407. return this._customEffect;
  21408. }
  21409. ;
  21410. var defines = [];
  21411. if (this._scene.clipPlane) {
  21412. defines.push("#define CLIPPLANE");
  21413. }
  21414. // Effect
  21415. var join = defines.join("\n");
  21416. if (this._cachedDefines !== join) {
  21417. this._cachedDefines = join;
  21418. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  21419. }
  21420. return this._effect;
  21421. };
  21422. ParticleSystem.prototype.animate = function () {
  21423. if (!this._started)
  21424. return;
  21425. var effect = this._getEffect();
  21426. // Check
  21427. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  21428. return;
  21429. if (this._currentRenderId === this._scene.getRenderId()) {
  21430. return;
  21431. }
  21432. this._currentRenderId = this._scene.getRenderId();
  21433. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  21434. // determine the number of particles we need to create
  21435. var emitCout;
  21436. if (this.manualEmitCount > -1) {
  21437. emitCout = this.manualEmitCount;
  21438. this.manualEmitCount = 0;
  21439. }
  21440. else {
  21441. emitCout = this.emitRate;
  21442. }
  21443. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  21444. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  21445. if (this._newPartsExcess > 1.0) {
  21446. newParticles += this._newPartsExcess >> 0;
  21447. this._newPartsExcess -= this._newPartsExcess >> 0;
  21448. }
  21449. this._alive = false;
  21450. if (!this._stopped) {
  21451. this._actualFrame += this._scaledUpdateSpeed;
  21452. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  21453. this.stop();
  21454. }
  21455. else {
  21456. newParticles = 0;
  21457. }
  21458. this._update(newParticles);
  21459. // Stopped?
  21460. if (this._stopped) {
  21461. if (!this._alive) {
  21462. this._started = false;
  21463. if (this.disposeOnStop) {
  21464. this._scene._toBeDisposed.push(this);
  21465. }
  21466. }
  21467. }
  21468. // Update VBO
  21469. var offset = 0;
  21470. for (var index = 0; index < this.particles.length; index++) {
  21471. var particle = this.particles[index];
  21472. this._appendParticleVertex(offset++, particle, 0, 0);
  21473. this._appendParticleVertex(offset++, particle, 1, 0);
  21474. this._appendParticleVertex(offset++, particle, 1, 1);
  21475. this._appendParticleVertex(offset++, particle, 0, 1);
  21476. }
  21477. var engine = this._scene.getEngine();
  21478. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  21479. };
  21480. ParticleSystem.prototype.render = function () {
  21481. var effect = this._getEffect();
  21482. // Check
  21483. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  21484. return 0;
  21485. var engine = this._scene.getEngine();
  21486. // Render
  21487. engine.enableEffect(effect);
  21488. engine.setState(false);
  21489. var viewMatrix = this._scene.getViewMatrix();
  21490. effect.setTexture("diffuseSampler", this.particleTexture);
  21491. effect.setMatrix("view", viewMatrix);
  21492. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  21493. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  21494. if (this._scene.clipPlane) {
  21495. var clipPlane = this._scene.clipPlane;
  21496. var invView = viewMatrix.clone();
  21497. invView.invert();
  21498. effect.setMatrix("invView", invView);
  21499. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  21500. }
  21501. // VBOs
  21502. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21503. // Draw order
  21504. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  21505. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  21506. }
  21507. else {
  21508. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21509. }
  21510. if (this.forceDepthWrite) {
  21511. engine.setDepthWrite(true);
  21512. }
  21513. engine.draw(true, 0, this.particles.length * 6);
  21514. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21515. return this.particles.length;
  21516. };
  21517. ParticleSystem.prototype.dispose = function () {
  21518. if (this._vertexBuffer) {
  21519. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21520. this._vertexBuffer = null;
  21521. }
  21522. if (this._indexBuffer) {
  21523. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21524. this._indexBuffer = null;
  21525. }
  21526. if (this.particleTexture) {
  21527. this.particleTexture.dispose();
  21528. this.particleTexture = null;
  21529. }
  21530. // Remove from scene
  21531. var index = this._scene.particleSystems.indexOf(this);
  21532. this._scene.particleSystems.splice(index, 1);
  21533. // Callback
  21534. if (this.onDispose) {
  21535. this.onDispose();
  21536. }
  21537. };
  21538. // Clone
  21539. ParticleSystem.prototype.clone = function (name, newEmitter) {
  21540. var result = new ParticleSystem(name, this._capacity, this._scene);
  21541. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  21542. if (newEmitter === undefined) {
  21543. newEmitter = this.emitter;
  21544. }
  21545. result.emitter = newEmitter;
  21546. if (this.particleTexture) {
  21547. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  21548. }
  21549. result.start();
  21550. return result;
  21551. };
  21552. // Statics
  21553. ParticleSystem.BLENDMODE_ONEONE = 0;
  21554. ParticleSystem.BLENDMODE_STANDARD = 1;
  21555. return ParticleSystem;
  21556. })();
  21557. BABYLON.ParticleSystem = ParticleSystem;
  21558. })(BABYLON || (BABYLON = {}));
  21559. var BABYLON;
  21560. (function (BABYLON) {
  21561. var Animation = (function () {
  21562. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  21563. this.name = name;
  21564. this.targetProperty = targetProperty;
  21565. this.framePerSecond = framePerSecond;
  21566. this.dataType = dataType;
  21567. this.loopMode = loopMode;
  21568. this._offsetsCache = {};
  21569. this._highLimitsCache = {};
  21570. this._stopped = false;
  21571. this.allowMatricesInterpolation = false;
  21572. this.targetPropertyPath = targetProperty.split(".");
  21573. this.dataType = dataType;
  21574. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  21575. }
  21576. Animation.CreateAndStartAnimation = function (name, mesh, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  21577. var dataType = undefined;
  21578. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  21579. dataType = Animation.ANIMATIONTYPE_FLOAT;
  21580. }
  21581. else if (from instanceof BABYLON.Quaternion) {
  21582. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  21583. }
  21584. else if (from instanceof BABYLON.Vector3) {
  21585. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  21586. }
  21587. else if (from instanceof BABYLON.Vector2) {
  21588. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  21589. }
  21590. else if (from instanceof BABYLON.Color3) {
  21591. dataType = Animation.ANIMATIONTYPE_COLOR3;
  21592. }
  21593. if (dataType == undefined) {
  21594. return null;
  21595. }
  21596. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  21597. var keys = [];
  21598. keys.push({ frame: 0, value: from });
  21599. keys.push({ frame: totalFrame, value: to });
  21600. animation.setKeys(keys);
  21601. if (easingFunction !== undefined) {
  21602. animation.setEasingFunction(easingFunction);
  21603. }
  21604. mesh.animations.push(animation);
  21605. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  21606. };
  21607. // Methods
  21608. Animation.prototype.reset = function () {
  21609. this._offsetsCache = {};
  21610. this._highLimitsCache = {};
  21611. this.currentFrame = 0;
  21612. };
  21613. Animation.prototype.isStopped = function () {
  21614. return this._stopped;
  21615. };
  21616. Animation.prototype.getKeys = function () {
  21617. return this._keys;
  21618. };
  21619. Animation.prototype.getEasingFunction = function () {
  21620. return this._easingFunction;
  21621. };
  21622. Animation.prototype.setEasingFunction = function (easingFunction) {
  21623. this._easingFunction = easingFunction;
  21624. };
  21625. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  21626. return startValue + (endValue - startValue) * gradient;
  21627. };
  21628. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  21629. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  21630. };
  21631. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  21632. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  21633. };
  21634. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  21635. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  21636. };
  21637. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  21638. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  21639. };
  21640. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  21641. var startScale = new BABYLON.Vector3(0, 0, 0);
  21642. var startRotation = new BABYLON.Quaternion();
  21643. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  21644. startValue.decompose(startScale, startRotation, startTranslation);
  21645. var endScale = new BABYLON.Vector3(0, 0, 0);
  21646. var endRotation = new BABYLON.Quaternion();
  21647. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  21648. endValue.decompose(endScale, endRotation, endTranslation);
  21649. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  21650. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  21651. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  21652. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  21653. return result;
  21654. };
  21655. Animation.prototype.clone = function () {
  21656. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  21657. clone.setKeys(this._keys);
  21658. return clone;
  21659. };
  21660. Animation.prototype.setKeys = function (values) {
  21661. this._keys = values.slice(0);
  21662. this._offsetsCache = {};
  21663. this._highLimitsCache = {};
  21664. };
  21665. Animation.prototype._getKeyValue = function (value) {
  21666. if (typeof value === "function") {
  21667. return value();
  21668. }
  21669. return value;
  21670. };
  21671. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  21672. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  21673. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  21674. }
  21675. this.currentFrame = currentFrame;
  21676. // Try to get a hash to find the right key
  21677. 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));
  21678. if (this._keys[startKey].frame >= currentFrame) {
  21679. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  21680. startKey--;
  21681. }
  21682. }
  21683. for (var key = startKey; key < this._keys.length; key++) {
  21684. if (this._keys[key + 1].frame >= currentFrame) {
  21685. var startValue = this._getKeyValue(this._keys[key].value);
  21686. var endValue = this._getKeyValue(this._keys[key + 1].value);
  21687. // gradient : percent of currentFrame between the frame inf and the frame sup
  21688. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  21689. // check for easingFunction and correction of gradient
  21690. if (this._easingFunction != null) {
  21691. gradient = this._easingFunction.ease(gradient);
  21692. }
  21693. switch (this.dataType) {
  21694. // Float
  21695. case Animation.ANIMATIONTYPE_FLOAT:
  21696. switch (loopMode) {
  21697. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21698. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21699. return this.floatInterpolateFunction(startValue, endValue, gradient);
  21700. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21701. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  21702. }
  21703. break;
  21704. // Quaternion
  21705. case Animation.ANIMATIONTYPE_QUATERNION:
  21706. var quaternion = null;
  21707. switch (loopMode) {
  21708. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21709. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21710. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  21711. break;
  21712. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21713. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21714. break;
  21715. }
  21716. return quaternion;
  21717. // Vector3
  21718. case Animation.ANIMATIONTYPE_VECTOR3:
  21719. switch (loopMode) {
  21720. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21721. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21722. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  21723. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21724. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21725. }
  21726. // Vector2
  21727. case Animation.ANIMATIONTYPE_VECTOR2:
  21728. switch (loopMode) {
  21729. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21730. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21731. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  21732. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21733. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21734. }
  21735. // Color3
  21736. case Animation.ANIMATIONTYPE_COLOR3:
  21737. switch (loopMode) {
  21738. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21739. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21740. return this.color3InterpolateFunction(startValue, endValue, gradient);
  21741. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21742. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  21743. }
  21744. // Matrix
  21745. case Animation.ANIMATIONTYPE_MATRIX:
  21746. switch (loopMode) {
  21747. case Animation.ANIMATIONLOOPMODE_CYCLE:
  21748. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  21749. if (this.allowMatricesInterpolation) {
  21750. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  21751. }
  21752. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  21753. return startValue;
  21754. }
  21755. default:
  21756. break;
  21757. }
  21758. break;
  21759. }
  21760. }
  21761. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  21762. };
  21763. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  21764. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  21765. this._stopped = true;
  21766. return false;
  21767. }
  21768. var returnValue = true;
  21769. // Adding a start key at frame 0 if missing
  21770. if (this._keys[0].frame !== 0) {
  21771. var newKey = { frame: 0, value: this._keys[0].value };
  21772. this._keys.splice(0, 0, newKey);
  21773. }
  21774. // Check limits
  21775. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  21776. from = this._keys[0].frame;
  21777. }
  21778. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  21779. to = this._keys[this._keys.length - 1].frame;
  21780. }
  21781. // Compute ratio
  21782. var range = to - from;
  21783. var offsetValue;
  21784. // ratio represents the frame delta between from and to
  21785. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  21786. var highLimitValue = 0;
  21787. if (ratio > range && !loop) {
  21788. returnValue = false;
  21789. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  21790. }
  21791. else {
  21792. // Get max value if required
  21793. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  21794. var keyOffset = to.toString() + from.toString();
  21795. if (!this._offsetsCache[keyOffset]) {
  21796. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21797. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  21798. switch (this.dataType) {
  21799. // Float
  21800. case Animation.ANIMATIONTYPE_FLOAT:
  21801. this._offsetsCache[keyOffset] = toValue - fromValue;
  21802. break;
  21803. // Quaternion
  21804. case Animation.ANIMATIONTYPE_QUATERNION:
  21805. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21806. break;
  21807. // Vector3
  21808. case Animation.ANIMATIONTYPE_VECTOR3:
  21809. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21810. // Vector2
  21811. case Animation.ANIMATIONTYPE_VECTOR2:
  21812. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21813. // Color3
  21814. case Animation.ANIMATIONTYPE_COLOR3:
  21815. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  21816. default:
  21817. break;
  21818. }
  21819. this._highLimitsCache[keyOffset] = toValue;
  21820. }
  21821. highLimitValue = this._highLimitsCache[keyOffset];
  21822. offsetValue = this._offsetsCache[keyOffset];
  21823. }
  21824. }
  21825. if (offsetValue === undefined) {
  21826. switch (this.dataType) {
  21827. // Float
  21828. case Animation.ANIMATIONTYPE_FLOAT:
  21829. offsetValue = 0;
  21830. break;
  21831. // Quaternion
  21832. case Animation.ANIMATIONTYPE_QUATERNION:
  21833. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  21834. break;
  21835. // Vector3
  21836. case Animation.ANIMATIONTYPE_VECTOR3:
  21837. offsetValue = BABYLON.Vector3.Zero();
  21838. break;
  21839. // Vector2
  21840. case Animation.ANIMATIONTYPE_VECTOR2:
  21841. offsetValue = BABYLON.Vector2.Zero();
  21842. break;
  21843. // Color3
  21844. case Animation.ANIMATIONTYPE_COLOR3:
  21845. offsetValue = BABYLON.Color3.Black();
  21846. }
  21847. }
  21848. // Compute value
  21849. var repeatCount = (ratio / range) >> 0;
  21850. var currentFrame = returnValue ? from + ratio % range : to;
  21851. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  21852. // Set value
  21853. if (this.targetPropertyPath.length > 1) {
  21854. var property = this._target[this.targetPropertyPath[0]];
  21855. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  21856. property = property[this.targetPropertyPath[index]];
  21857. }
  21858. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  21859. }
  21860. else {
  21861. this._target[this.targetPropertyPath[0]] = currentValue;
  21862. }
  21863. if (this._target.markAsDirty) {
  21864. this._target.markAsDirty(this.targetProperty);
  21865. }
  21866. if (!returnValue) {
  21867. this._stopped = true;
  21868. }
  21869. return returnValue;
  21870. };
  21871. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21872. get: function () {
  21873. return Animation._ANIMATIONTYPE_FLOAT;
  21874. },
  21875. enumerable: true,
  21876. configurable: true
  21877. });
  21878. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21879. get: function () {
  21880. return Animation._ANIMATIONTYPE_VECTOR3;
  21881. },
  21882. enumerable: true,
  21883. configurable: true
  21884. });
  21885. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21886. get: function () {
  21887. return Animation._ANIMATIONTYPE_VECTOR2;
  21888. },
  21889. enumerable: true,
  21890. configurable: true
  21891. });
  21892. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21893. get: function () {
  21894. return Animation._ANIMATIONTYPE_QUATERNION;
  21895. },
  21896. enumerable: true,
  21897. configurable: true
  21898. });
  21899. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21900. get: function () {
  21901. return Animation._ANIMATIONTYPE_MATRIX;
  21902. },
  21903. enumerable: true,
  21904. configurable: true
  21905. });
  21906. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21907. get: function () {
  21908. return Animation._ANIMATIONTYPE_COLOR3;
  21909. },
  21910. enumerable: true,
  21911. configurable: true
  21912. });
  21913. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21914. get: function () {
  21915. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21916. },
  21917. enumerable: true,
  21918. configurable: true
  21919. });
  21920. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21921. get: function () {
  21922. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21923. },
  21924. enumerable: true,
  21925. configurable: true
  21926. });
  21927. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21928. get: function () {
  21929. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21930. },
  21931. enumerable: true,
  21932. configurable: true
  21933. });
  21934. // Statics
  21935. Animation._ANIMATIONTYPE_FLOAT = 0;
  21936. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21937. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21938. Animation._ANIMATIONTYPE_MATRIX = 3;
  21939. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21940. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21941. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21942. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21943. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21944. return Animation;
  21945. })();
  21946. BABYLON.Animation = Animation;
  21947. })(BABYLON || (BABYLON = {}));
  21948. var BABYLON;
  21949. (function (BABYLON) {
  21950. var Animatable = (function () {
  21951. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21952. if (fromFrame === void 0) { fromFrame = 0; }
  21953. if (toFrame === void 0) { toFrame = 100; }
  21954. if (loopAnimation === void 0) { loopAnimation = false; }
  21955. if (speedRatio === void 0) { speedRatio = 1.0; }
  21956. this.target = target;
  21957. this.fromFrame = fromFrame;
  21958. this.toFrame = toFrame;
  21959. this.loopAnimation = loopAnimation;
  21960. this.speedRatio = speedRatio;
  21961. this.onAnimationEnd = onAnimationEnd;
  21962. this._animations = new Array();
  21963. this._paused = false;
  21964. this.animationStarted = false;
  21965. if (animations) {
  21966. this.appendAnimations(target, animations);
  21967. }
  21968. this._scene = scene;
  21969. scene._activeAnimatables.push(this);
  21970. }
  21971. // Methods
  21972. Animatable.prototype.appendAnimations = function (target, animations) {
  21973. for (var index = 0; index < animations.length; index++) {
  21974. var animation = animations[index];
  21975. animation._target = target;
  21976. this._animations.push(animation);
  21977. }
  21978. };
  21979. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21980. var animations = this._animations;
  21981. for (var index = 0; index < animations.length; index++) {
  21982. if (animations[index].targetProperty === property) {
  21983. return animations[index];
  21984. }
  21985. }
  21986. return null;
  21987. };
  21988. Animatable.prototype.reset = function () {
  21989. var animations = this._animations;
  21990. for (var index = 0; index < animations.length; index++) {
  21991. animations[index].reset();
  21992. }
  21993. this._localDelayOffset = null;
  21994. this._pausedDelay = null;
  21995. };
  21996. Animatable.prototype.pause = function () {
  21997. if (this._paused) {
  21998. return;
  21999. }
  22000. this._paused = true;
  22001. };
  22002. Animatable.prototype.restart = function () {
  22003. this._paused = false;
  22004. };
  22005. Animatable.prototype.stop = function () {
  22006. var index = this._scene._activeAnimatables.indexOf(this);
  22007. if (index > -1) {
  22008. this._scene._activeAnimatables.splice(index, 1);
  22009. }
  22010. if (this.onAnimationEnd) {
  22011. this.onAnimationEnd();
  22012. }
  22013. };
  22014. Animatable.prototype._animate = function (delay) {
  22015. if (this._paused) {
  22016. if (!this._pausedDelay) {
  22017. this._pausedDelay = delay;
  22018. }
  22019. return true;
  22020. }
  22021. if (!this._localDelayOffset) {
  22022. this._localDelayOffset = delay;
  22023. }
  22024. else if (this._pausedDelay) {
  22025. this._localDelayOffset += delay - this._pausedDelay;
  22026. this._pausedDelay = null;
  22027. }
  22028. // Animating
  22029. var running = false;
  22030. var animations = this._animations;
  22031. for (var index = 0; index < animations.length; index++) {
  22032. var animation = animations[index];
  22033. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  22034. running = running || isRunning;
  22035. }
  22036. if (!running) {
  22037. // Remove from active animatables
  22038. index = this._scene._activeAnimatables.indexOf(this);
  22039. this._scene._activeAnimatables.splice(index, 1);
  22040. }
  22041. if (!running && this.onAnimationEnd) {
  22042. this.onAnimationEnd();
  22043. }
  22044. return running;
  22045. };
  22046. return Animatable;
  22047. })();
  22048. BABYLON.Animatable = Animatable;
  22049. })(BABYLON || (BABYLON = {}));
  22050. var BABYLON;
  22051. (function (BABYLON) {
  22052. var EasingFunction = (function () {
  22053. function EasingFunction() {
  22054. // Properties
  22055. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  22056. }
  22057. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  22058. get: function () {
  22059. return EasingFunction._EASINGMODE_EASEIN;
  22060. },
  22061. enumerable: true,
  22062. configurable: true
  22063. });
  22064. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  22065. get: function () {
  22066. return EasingFunction._EASINGMODE_EASEOUT;
  22067. },
  22068. enumerable: true,
  22069. configurable: true
  22070. });
  22071. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  22072. get: function () {
  22073. return EasingFunction._EASINGMODE_EASEINOUT;
  22074. },
  22075. enumerable: true,
  22076. configurable: true
  22077. });
  22078. EasingFunction.prototype.setEasingMode = function (easingMode) {
  22079. var n = Math.min(Math.max(easingMode, 0), 2);
  22080. this._easingMode = n;
  22081. };
  22082. EasingFunction.prototype.getEasingMode = function () {
  22083. return this._easingMode;
  22084. };
  22085. EasingFunction.prototype.easeInCore = function (gradient) {
  22086. throw new Error('You must implement this method');
  22087. };
  22088. EasingFunction.prototype.ease = function (gradient) {
  22089. switch (this._easingMode) {
  22090. case EasingFunction.EASINGMODE_EASEIN:
  22091. return this.easeInCore(gradient);
  22092. case EasingFunction.EASINGMODE_EASEOUT:
  22093. return (1 - this.easeInCore(1 - gradient));
  22094. }
  22095. if (gradient >= 0.5) {
  22096. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  22097. }
  22098. return (this.easeInCore(gradient * 2) * 0.5);
  22099. };
  22100. //Statics
  22101. EasingFunction._EASINGMODE_EASEIN = 0;
  22102. EasingFunction._EASINGMODE_EASEOUT = 1;
  22103. EasingFunction._EASINGMODE_EASEINOUT = 2;
  22104. return EasingFunction;
  22105. })();
  22106. BABYLON.EasingFunction = EasingFunction;
  22107. var CircleEase = (function (_super) {
  22108. __extends(CircleEase, _super);
  22109. function CircleEase() {
  22110. _super.apply(this, arguments);
  22111. }
  22112. CircleEase.prototype.easeInCore = function (gradient) {
  22113. gradient = Math.max(0, Math.min(1, gradient));
  22114. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  22115. };
  22116. return CircleEase;
  22117. })(EasingFunction);
  22118. BABYLON.CircleEase = CircleEase;
  22119. var BackEase = (function (_super) {
  22120. __extends(BackEase, _super);
  22121. function BackEase(amplitude) {
  22122. if (amplitude === void 0) { amplitude = 1; }
  22123. _super.call(this);
  22124. this.amplitude = amplitude;
  22125. }
  22126. BackEase.prototype.easeInCore = function (gradient) {
  22127. var num = Math.max(0, this.amplitude);
  22128. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  22129. };
  22130. return BackEase;
  22131. })(EasingFunction);
  22132. BABYLON.BackEase = BackEase;
  22133. var BounceEase = (function (_super) {
  22134. __extends(BounceEase, _super);
  22135. function BounceEase(bounces, bounciness) {
  22136. if (bounces === void 0) { bounces = 3; }
  22137. if (bounciness === void 0) { bounciness = 2; }
  22138. _super.call(this);
  22139. this.bounces = bounces;
  22140. this.bounciness = bounciness;
  22141. }
  22142. BounceEase.prototype.easeInCore = function (gradient) {
  22143. var y = Math.max(0.0, this.bounces);
  22144. var bounciness = this.bounciness;
  22145. if (bounciness <= 1.0) {
  22146. bounciness = 1.001;
  22147. }
  22148. var num9 = Math.pow(bounciness, y);
  22149. var num5 = 1.0 - bounciness;
  22150. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  22151. var num15 = gradient * num4;
  22152. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  22153. var num3 = Math.floor(num65);
  22154. var num13 = num3 + 1.0;
  22155. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  22156. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  22157. var num7 = (num8 + num12) * 0.5;
  22158. var num6 = gradient - num7;
  22159. var num2 = num7 - num8;
  22160. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  22161. };
  22162. return BounceEase;
  22163. })(EasingFunction);
  22164. BABYLON.BounceEase = BounceEase;
  22165. var CubicEase = (function (_super) {
  22166. __extends(CubicEase, _super);
  22167. function CubicEase() {
  22168. _super.apply(this, arguments);
  22169. }
  22170. CubicEase.prototype.easeInCore = function (gradient) {
  22171. return (gradient * gradient * gradient);
  22172. };
  22173. return CubicEase;
  22174. })(EasingFunction);
  22175. BABYLON.CubicEase = CubicEase;
  22176. var ElasticEase = (function (_super) {
  22177. __extends(ElasticEase, _super);
  22178. function ElasticEase(oscillations, springiness) {
  22179. if (oscillations === void 0) { oscillations = 3; }
  22180. if (springiness === void 0) { springiness = 3; }
  22181. _super.call(this);
  22182. this.oscillations = oscillations;
  22183. this.springiness = springiness;
  22184. }
  22185. ElasticEase.prototype.easeInCore = function (gradient) {
  22186. var num2;
  22187. var num3 = Math.max(0.0, this.oscillations);
  22188. var num = Math.max(0.0, this.springiness);
  22189. if (num == 0) {
  22190. num2 = gradient;
  22191. }
  22192. else {
  22193. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  22194. }
  22195. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  22196. };
  22197. return ElasticEase;
  22198. })(EasingFunction);
  22199. BABYLON.ElasticEase = ElasticEase;
  22200. var ExponentialEase = (function (_super) {
  22201. __extends(ExponentialEase, _super);
  22202. function ExponentialEase(exponent) {
  22203. if (exponent === void 0) { exponent = 2; }
  22204. _super.call(this);
  22205. this.exponent = exponent;
  22206. }
  22207. ExponentialEase.prototype.easeInCore = function (gradient) {
  22208. if (this.exponent <= 0) {
  22209. return gradient;
  22210. }
  22211. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  22212. };
  22213. return ExponentialEase;
  22214. })(EasingFunction);
  22215. BABYLON.ExponentialEase = ExponentialEase;
  22216. var PowerEase = (function (_super) {
  22217. __extends(PowerEase, _super);
  22218. function PowerEase(power) {
  22219. if (power === void 0) { power = 2; }
  22220. _super.call(this);
  22221. this.power = power;
  22222. }
  22223. PowerEase.prototype.easeInCore = function (gradient) {
  22224. var y = Math.max(0.0, this.power);
  22225. return Math.pow(gradient, y);
  22226. };
  22227. return PowerEase;
  22228. })(EasingFunction);
  22229. BABYLON.PowerEase = PowerEase;
  22230. var QuadraticEase = (function (_super) {
  22231. __extends(QuadraticEase, _super);
  22232. function QuadraticEase() {
  22233. _super.apply(this, arguments);
  22234. }
  22235. QuadraticEase.prototype.easeInCore = function (gradient) {
  22236. return (gradient * gradient);
  22237. };
  22238. return QuadraticEase;
  22239. })(EasingFunction);
  22240. BABYLON.QuadraticEase = QuadraticEase;
  22241. var QuarticEase = (function (_super) {
  22242. __extends(QuarticEase, _super);
  22243. function QuarticEase() {
  22244. _super.apply(this, arguments);
  22245. }
  22246. QuarticEase.prototype.easeInCore = function (gradient) {
  22247. return (gradient * gradient * gradient * gradient);
  22248. };
  22249. return QuarticEase;
  22250. })(EasingFunction);
  22251. BABYLON.QuarticEase = QuarticEase;
  22252. var QuinticEase = (function (_super) {
  22253. __extends(QuinticEase, _super);
  22254. function QuinticEase() {
  22255. _super.apply(this, arguments);
  22256. }
  22257. QuinticEase.prototype.easeInCore = function (gradient) {
  22258. return (gradient * gradient * gradient * gradient * gradient);
  22259. };
  22260. return QuinticEase;
  22261. })(EasingFunction);
  22262. BABYLON.QuinticEase = QuinticEase;
  22263. var SineEase = (function (_super) {
  22264. __extends(SineEase, _super);
  22265. function SineEase() {
  22266. _super.apply(this, arguments);
  22267. }
  22268. SineEase.prototype.easeInCore = function (gradient) {
  22269. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  22270. };
  22271. return SineEase;
  22272. })(EasingFunction);
  22273. BABYLON.SineEase = SineEase;
  22274. var BezierCurveEase = (function (_super) {
  22275. __extends(BezierCurveEase, _super);
  22276. function BezierCurveEase(x1, y1, x2, y2) {
  22277. if (x1 === void 0) { x1 = 0; }
  22278. if (y1 === void 0) { y1 = 0; }
  22279. if (x2 === void 0) { x2 = 1; }
  22280. if (y2 === void 0) { y2 = 1; }
  22281. _super.call(this);
  22282. this.x1 = x1;
  22283. this.y1 = y1;
  22284. this.x2 = x2;
  22285. this.y2 = y2;
  22286. }
  22287. BezierCurveEase.prototype.easeInCore = function (gradient) {
  22288. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  22289. };
  22290. return BezierCurveEase;
  22291. })(EasingFunction);
  22292. BABYLON.BezierCurveEase = BezierCurveEase;
  22293. })(BABYLON || (BABYLON = {}));
  22294. var BABYLON;
  22295. (function (BABYLON) {
  22296. var Octree = (function () {
  22297. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  22298. if (maxDepth === void 0) { maxDepth = 2; }
  22299. this.maxDepth = maxDepth;
  22300. this.dynamicContent = new Array();
  22301. this._maxBlockCapacity = maxBlockCapacity || 64;
  22302. this._selectionContent = new BABYLON.SmartArray(1024);
  22303. this._creationFunc = creationFunc;
  22304. }
  22305. // Methods
  22306. Octree.prototype.update = function (worldMin, worldMax, entries) {
  22307. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  22308. };
  22309. Octree.prototype.addMesh = function (entry) {
  22310. for (var index = 0; index < this.blocks.length; index++) {
  22311. var block = this.blocks[index];
  22312. block.addEntry(entry);
  22313. }
  22314. };
  22315. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  22316. this._selectionContent.reset();
  22317. for (var index = 0; index < this.blocks.length; index++) {
  22318. var block = this.blocks[index];
  22319. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  22320. }
  22321. if (allowDuplicate) {
  22322. this._selectionContent.concat(this.dynamicContent);
  22323. }
  22324. else {
  22325. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22326. }
  22327. return this._selectionContent;
  22328. };
  22329. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  22330. this._selectionContent.reset();
  22331. for (var index = 0; index < this.blocks.length; index++) {
  22332. var block = this.blocks[index];
  22333. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  22334. }
  22335. if (allowDuplicate) {
  22336. this._selectionContent.concat(this.dynamicContent);
  22337. }
  22338. else {
  22339. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22340. }
  22341. return this._selectionContent;
  22342. };
  22343. Octree.prototype.intersectsRay = function (ray) {
  22344. this._selectionContent.reset();
  22345. for (var index = 0; index < this.blocks.length; index++) {
  22346. var block = this.blocks[index];
  22347. block.intersectsRay(ray, this._selectionContent);
  22348. }
  22349. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  22350. return this._selectionContent;
  22351. };
  22352. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  22353. target.blocks = new Array();
  22354. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  22355. // Segmenting space
  22356. for (var x = 0; x < 2; x++) {
  22357. for (var y = 0; y < 2; y++) {
  22358. for (var z = 0; z < 2; z++) {
  22359. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  22360. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  22361. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  22362. block.addEntries(entries);
  22363. target.blocks.push(block);
  22364. }
  22365. }
  22366. }
  22367. };
  22368. Octree.CreationFuncForMeshes = function (entry, block) {
  22369. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22370. block.entries.push(entry);
  22371. }
  22372. };
  22373. Octree.CreationFuncForSubMeshes = function (entry, block) {
  22374. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  22375. block.entries.push(entry);
  22376. }
  22377. };
  22378. return Octree;
  22379. })();
  22380. BABYLON.Octree = Octree;
  22381. })(BABYLON || (BABYLON = {}));
  22382. var BABYLON;
  22383. (function (BABYLON) {
  22384. var OctreeBlock = (function () {
  22385. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  22386. this.entries = new Array();
  22387. this._boundingVectors = new Array();
  22388. this._capacity = capacity;
  22389. this._depth = depth;
  22390. this._maxDepth = maxDepth;
  22391. this._creationFunc = creationFunc;
  22392. this._minPoint = minPoint;
  22393. this._maxPoint = maxPoint;
  22394. this._boundingVectors.push(minPoint.clone());
  22395. this._boundingVectors.push(maxPoint.clone());
  22396. this._boundingVectors.push(minPoint.clone());
  22397. this._boundingVectors[2].x = maxPoint.x;
  22398. this._boundingVectors.push(minPoint.clone());
  22399. this._boundingVectors[3].y = maxPoint.y;
  22400. this._boundingVectors.push(minPoint.clone());
  22401. this._boundingVectors[4].z = maxPoint.z;
  22402. this._boundingVectors.push(maxPoint.clone());
  22403. this._boundingVectors[5].z = minPoint.z;
  22404. this._boundingVectors.push(maxPoint.clone());
  22405. this._boundingVectors[6].x = minPoint.x;
  22406. this._boundingVectors.push(maxPoint.clone());
  22407. this._boundingVectors[7].y = minPoint.y;
  22408. }
  22409. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  22410. // Property
  22411. get: function () {
  22412. return this._capacity;
  22413. },
  22414. enumerable: true,
  22415. configurable: true
  22416. });
  22417. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  22418. get: function () {
  22419. return this._minPoint;
  22420. },
  22421. enumerable: true,
  22422. configurable: true
  22423. });
  22424. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  22425. get: function () {
  22426. return this._maxPoint;
  22427. },
  22428. enumerable: true,
  22429. configurable: true
  22430. });
  22431. // Methods
  22432. OctreeBlock.prototype.addEntry = function (entry) {
  22433. if (this.blocks) {
  22434. for (var index = 0; index < this.blocks.length; index++) {
  22435. var block = this.blocks[index];
  22436. block.addEntry(entry);
  22437. }
  22438. return;
  22439. }
  22440. this._creationFunc(entry, this);
  22441. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  22442. this.createInnerBlocks();
  22443. }
  22444. };
  22445. OctreeBlock.prototype.addEntries = function (entries) {
  22446. for (var index = 0; index < entries.length; index++) {
  22447. var mesh = entries[index];
  22448. this.addEntry(mesh);
  22449. }
  22450. };
  22451. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  22452. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  22453. if (this.blocks) {
  22454. for (var index = 0; index < this.blocks.length; index++) {
  22455. var block = this.blocks[index];
  22456. block.select(frustumPlanes, selection, allowDuplicate);
  22457. }
  22458. return;
  22459. }
  22460. if (allowDuplicate) {
  22461. selection.concat(this.entries);
  22462. }
  22463. else {
  22464. selection.concatWithNoDuplicate(this.entries);
  22465. }
  22466. }
  22467. };
  22468. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  22469. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  22470. if (this.blocks) {
  22471. for (var index = 0; index < this.blocks.length; index++) {
  22472. var block = this.blocks[index];
  22473. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  22474. }
  22475. return;
  22476. }
  22477. if (allowDuplicate) {
  22478. selection.concat(this.entries);
  22479. }
  22480. else {
  22481. selection.concatWithNoDuplicate(this.entries);
  22482. }
  22483. }
  22484. };
  22485. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  22486. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  22487. if (this.blocks) {
  22488. for (var index = 0; index < this.blocks.length; index++) {
  22489. var block = this.blocks[index];
  22490. block.intersectsRay(ray, selection);
  22491. }
  22492. return;
  22493. }
  22494. selection.concatWithNoDuplicate(this.entries);
  22495. }
  22496. };
  22497. OctreeBlock.prototype.createInnerBlocks = function () {
  22498. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  22499. };
  22500. return OctreeBlock;
  22501. })();
  22502. BABYLON.OctreeBlock = OctreeBlock;
  22503. })(BABYLON || (BABYLON = {}));
  22504. var BABYLON;
  22505. (function (BABYLON) {
  22506. var Bone = (function (_super) {
  22507. __extends(Bone, _super);
  22508. function Bone(name, skeleton, parentBone, matrix) {
  22509. _super.call(this, name, skeleton.getScene());
  22510. this.name = name;
  22511. this.children = new Array();
  22512. this.animations = new Array();
  22513. this._worldTransform = new BABYLON.Matrix();
  22514. this._absoluteTransform = new BABYLON.Matrix();
  22515. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  22516. this._skeleton = skeleton;
  22517. this._matrix = matrix;
  22518. this._baseMatrix = matrix;
  22519. skeleton.bones.push(this);
  22520. if (parentBone) {
  22521. this._parent = parentBone;
  22522. parentBone.children.push(this);
  22523. }
  22524. else {
  22525. this._parent = null;
  22526. }
  22527. this._updateDifferenceMatrix();
  22528. }
  22529. // Members
  22530. Bone.prototype.getParent = function () {
  22531. return this._parent;
  22532. };
  22533. Bone.prototype.getLocalMatrix = function () {
  22534. return this._matrix;
  22535. };
  22536. Bone.prototype.getBaseMatrix = function () {
  22537. return this._baseMatrix;
  22538. };
  22539. Bone.prototype.getWorldMatrix = function () {
  22540. return this._worldTransform;
  22541. };
  22542. Bone.prototype.getInvertedAbsoluteTransform = function () {
  22543. return this._invertedAbsoluteTransform;
  22544. };
  22545. Bone.prototype.getAbsoluteMatrix = function () {
  22546. var matrix = this._matrix.clone();
  22547. var parent = this._parent;
  22548. while (parent) {
  22549. matrix = matrix.multiply(parent.getLocalMatrix());
  22550. parent = parent.getParent();
  22551. }
  22552. return matrix;
  22553. };
  22554. // Methods
  22555. Bone.prototype.updateMatrix = function (matrix) {
  22556. this._matrix = matrix;
  22557. this._skeleton._markAsDirty();
  22558. this._updateDifferenceMatrix();
  22559. };
  22560. Bone.prototype._updateDifferenceMatrix = function () {
  22561. if (this._parent) {
  22562. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  22563. }
  22564. else {
  22565. this._absoluteTransform.copyFrom(this._matrix);
  22566. }
  22567. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  22568. for (var index = 0; index < this.children.length; index++) {
  22569. this.children[index]._updateDifferenceMatrix();
  22570. }
  22571. };
  22572. Bone.prototype.markAsDirty = function () {
  22573. this._currentRenderId++;
  22574. this._skeleton._markAsDirty();
  22575. };
  22576. return Bone;
  22577. })(BABYLON.Node);
  22578. BABYLON.Bone = Bone;
  22579. })(BABYLON || (BABYLON = {}));
  22580. var BABYLON;
  22581. (function (BABYLON) {
  22582. var Skeleton = (function () {
  22583. function Skeleton(name, id, scene) {
  22584. this.name = name;
  22585. this.id = id;
  22586. this.bones = new Array();
  22587. this._isDirty = true;
  22588. this._identity = BABYLON.Matrix.Identity();
  22589. this.bones = [];
  22590. this._scene = scene;
  22591. scene.skeletons.push(this);
  22592. this.prepare();
  22593. //make sure it will recalculate the matrix next time prepare is called.
  22594. this._isDirty = true;
  22595. }
  22596. // Members
  22597. Skeleton.prototype.getTransformMatrices = function () {
  22598. return this._transformMatrices;
  22599. };
  22600. Skeleton.prototype.getScene = function () {
  22601. return this._scene;
  22602. };
  22603. // Methods
  22604. Skeleton.prototype._markAsDirty = function () {
  22605. this._isDirty = true;
  22606. };
  22607. Skeleton.prototype.prepare = function () {
  22608. if (!this._isDirty) {
  22609. return;
  22610. }
  22611. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  22612. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  22613. }
  22614. for (var index = 0; index < this.bones.length; index++) {
  22615. var bone = this.bones[index];
  22616. var parentBone = bone.getParent();
  22617. if (parentBone) {
  22618. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  22619. }
  22620. else {
  22621. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  22622. }
  22623. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  22624. }
  22625. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  22626. this._isDirty = false;
  22627. this._scene._activeBones += this.bones.length;
  22628. };
  22629. Skeleton.prototype.getAnimatables = function () {
  22630. if (!this._animatables || this._animatables.length !== this.bones.length) {
  22631. this._animatables = [];
  22632. for (var index = 0; index < this.bones.length; index++) {
  22633. this._animatables.push(this.bones[index]);
  22634. }
  22635. }
  22636. return this._animatables;
  22637. };
  22638. Skeleton.prototype.clone = function (name, id) {
  22639. var result = new Skeleton(name, id || name, this._scene);
  22640. for (var index = 0; index < this.bones.length; index++) {
  22641. var source = this.bones[index];
  22642. var parentBone = null;
  22643. if (source.getParent()) {
  22644. var parentIndex = this.bones.indexOf(source.getParent());
  22645. parentBone = result.bones[parentIndex];
  22646. }
  22647. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  22648. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  22649. }
  22650. return result;
  22651. };
  22652. return Skeleton;
  22653. })();
  22654. BABYLON.Skeleton = Skeleton;
  22655. })(BABYLON || (BABYLON = {}));
  22656. var BABYLON;
  22657. (function (BABYLON) {
  22658. var PostProcess = (function () {
  22659. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  22660. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  22661. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22662. this.name = name;
  22663. this.width = -1;
  22664. this.height = -1;
  22665. this._reusable = false;
  22666. this._textures = new BABYLON.SmartArray(2);
  22667. this._currentRenderTextureInd = 0;
  22668. if (camera != null) {
  22669. this._camera = camera;
  22670. this._scene = camera.getScene();
  22671. camera.attachPostProcess(this);
  22672. this._engine = this._scene.getEngine();
  22673. }
  22674. else {
  22675. this._engine = engine;
  22676. }
  22677. this._renderRatio = ratio;
  22678. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  22679. this._reusable = reusable || false;
  22680. this._textureType = textureType;
  22681. samplers = samplers || [];
  22682. samplers.push("textureSampler");
  22683. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  22684. }
  22685. PostProcess.prototype.isReusable = function () {
  22686. return this._reusable;
  22687. };
  22688. PostProcess.prototype.activate = function (camera, sourceTexture) {
  22689. camera = camera || this._camera;
  22690. var scene = camera.getScene();
  22691. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  22692. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  22693. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  22694. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  22695. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  22696. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  22697. if (this._textures.length > 0) {
  22698. for (var i = 0; i < this._textures.length; i++) {
  22699. this._engine._releaseTexture(this._textures.data[i]);
  22700. }
  22701. this._textures.reset();
  22702. }
  22703. this.width = desiredWidth;
  22704. this.height = desiredHeight;
  22705. 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 }));
  22706. if (this._reusable) {
  22707. 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 }));
  22708. }
  22709. if (this.onSizeChanged) {
  22710. this.onSizeChanged();
  22711. }
  22712. }
  22713. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  22714. if (this.onActivate) {
  22715. this.onActivate(camera);
  22716. }
  22717. // Clear
  22718. if (this.clearColor) {
  22719. this._engine.clear(this.clearColor, true, true);
  22720. }
  22721. else {
  22722. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  22723. }
  22724. if (this._reusable) {
  22725. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  22726. }
  22727. };
  22728. PostProcess.prototype.apply = function () {
  22729. // Check
  22730. if (!this._effect.isReady())
  22731. return null;
  22732. // States
  22733. this._engine.enableEffect(this._effect);
  22734. this._engine.setState(false);
  22735. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22736. this._engine.setDepthBuffer(false);
  22737. this._engine.setDepthWrite(false);
  22738. // Texture
  22739. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  22740. // Parameters
  22741. if (this.onApply) {
  22742. this.onApply(this._effect);
  22743. }
  22744. return this._effect;
  22745. };
  22746. PostProcess.prototype.dispose = function (camera) {
  22747. camera = camera || this._camera;
  22748. if (this._textures.length > 0) {
  22749. for (var i = 0; i < this._textures.length; i++) {
  22750. this._engine._releaseTexture(this._textures.data[i]);
  22751. }
  22752. this._textures.reset();
  22753. }
  22754. if (!camera) {
  22755. return;
  22756. }
  22757. camera.detachPostProcess(this);
  22758. var index = camera._postProcesses.indexOf(this);
  22759. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  22760. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  22761. }
  22762. };
  22763. return PostProcess;
  22764. })();
  22765. BABYLON.PostProcess = PostProcess;
  22766. })(BABYLON || (BABYLON = {}));
  22767. var BABYLON;
  22768. (function (BABYLON) {
  22769. var PostProcessManager = (function () {
  22770. function PostProcessManager(scene) {
  22771. this._vertexDeclaration = [2];
  22772. this._vertexStrideSize = 2 * 4;
  22773. this._scene = scene;
  22774. }
  22775. PostProcessManager.prototype._prepareBuffers = function () {
  22776. if (this._vertexBuffer) {
  22777. return;
  22778. }
  22779. // VBO
  22780. var vertices = [];
  22781. vertices.push(1, 1);
  22782. vertices.push(-1, 1);
  22783. vertices.push(-1, -1);
  22784. vertices.push(1, -1);
  22785. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  22786. // Indices
  22787. var indices = [];
  22788. indices.push(0);
  22789. indices.push(1);
  22790. indices.push(2);
  22791. indices.push(0);
  22792. indices.push(2);
  22793. indices.push(3);
  22794. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  22795. };
  22796. // Methods
  22797. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  22798. var postProcesses = this._scene.activeCamera._postProcesses;
  22799. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22800. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22801. return false;
  22802. }
  22803. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  22804. return true;
  22805. };
  22806. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  22807. var engine = this._scene.getEngine();
  22808. for (var index = 0; index < postProcesses.length; index++) {
  22809. if (index < postProcesses.length - 1) {
  22810. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  22811. }
  22812. else {
  22813. if (targetTexture) {
  22814. engine.bindFramebuffer(targetTexture);
  22815. }
  22816. else {
  22817. engine.restoreDefaultFramebuffer();
  22818. }
  22819. }
  22820. var pp = postProcesses[index];
  22821. var effect = pp.apply();
  22822. if (effect) {
  22823. if (pp.onBeforeRender) {
  22824. pp.onBeforeRender(effect);
  22825. }
  22826. // VBOs
  22827. this._prepareBuffers();
  22828. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22829. // Draw order
  22830. engine.draw(true, 0, 6);
  22831. if (pp.onAfterRender) {
  22832. pp.onAfterRender(effect);
  22833. }
  22834. }
  22835. }
  22836. // Restore depth buffer
  22837. engine.setDepthBuffer(true);
  22838. engine.setDepthWrite(true);
  22839. };
  22840. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  22841. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  22842. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  22843. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  22844. return;
  22845. }
  22846. var engine = this._scene.getEngine();
  22847. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  22848. if (index < postProcessesTakenIndices.length - 1) {
  22849. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  22850. }
  22851. else {
  22852. if (targetTexture) {
  22853. engine.bindFramebuffer(targetTexture);
  22854. }
  22855. else {
  22856. engine.restoreDefaultFramebuffer();
  22857. }
  22858. }
  22859. if (doNotPresent) {
  22860. break;
  22861. }
  22862. var pp = postProcesses[postProcessesTakenIndices[index]];
  22863. var effect = pp.apply();
  22864. if (effect) {
  22865. if (pp.onBeforeRender) {
  22866. pp.onBeforeRender(effect);
  22867. }
  22868. // VBOs
  22869. this._prepareBuffers();
  22870. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22871. // Draw order
  22872. engine.draw(true, 0, 6);
  22873. if (pp.onAfterRender) {
  22874. pp.onAfterRender(effect);
  22875. }
  22876. }
  22877. }
  22878. // Restore depth buffer
  22879. engine.setDepthBuffer(true);
  22880. engine.setDepthWrite(true);
  22881. };
  22882. PostProcessManager.prototype.dispose = function () {
  22883. if (this._vertexBuffer) {
  22884. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22885. this._vertexBuffer = null;
  22886. }
  22887. if (this._indexBuffer) {
  22888. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22889. this._indexBuffer = null;
  22890. }
  22891. };
  22892. return PostProcessManager;
  22893. })();
  22894. BABYLON.PostProcessManager = PostProcessManager;
  22895. })(BABYLON || (BABYLON = {}));
  22896. var BABYLON;
  22897. (function (BABYLON) {
  22898. var PassPostProcess = (function (_super) {
  22899. __extends(PassPostProcess, _super);
  22900. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22901. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22902. }
  22903. return PassPostProcess;
  22904. })(BABYLON.PostProcess);
  22905. BABYLON.PassPostProcess = PassPostProcess;
  22906. })(BABYLON || (BABYLON = {}));
  22907. var BABYLON;
  22908. (function (BABYLON) {
  22909. var BlurPostProcess = (function (_super) {
  22910. __extends(BlurPostProcess, _super);
  22911. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22912. var _this = this;
  22913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22914. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22915. this.direction = direction;
  22916. this.blurWidth = blurWidth;
  22917. this.onApply = function (effect) {
  22918. effect.setFloat2("screenSize", _this.width, _this.height);
  22919. effect.setVector2("direction", _this.direction);
  22920. effect.setFloat("blurWidth", _this.blurWidth);
  22921. };
  22922. }
  22923. return BlurPostProcess;
  22924. })(BABYLON.PostProcess);
  22925. BABYLON.BlurPostProcess = BlurPostProcess;
  22926. })(BABYLON || (BABYLON = {}));
  22927. var BABYLON;
  22928. (function (BABYLON) {
  22929. var RefractionPostProcess = (function (_super) {
  22930. __extends(RefractionPostProcess, _super);
  22931. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22932. var _this = this;
  22933. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22934. this.color = color;
  22935. this.depth = depth;
  22936. this.colorLevel = colorLevel;
  22937. this.onActivate = function (cam) {
  22938. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22939. };
  22940. this.onApply = function (effect) {
  22941. effect.setColor3("baseColor", _this.color);
  22942. effect.setFloat("depth", _this.depth);
  22943. effect.setFloat("colorLevel", _this.colorLevel);
  22944. effect.setTexture("refractionSampler", _this._refRexture);
  22945. };
  22946. }
  22947. // Methods
  22948. RefractionPostProcess.prototype.dispose = function (camera) {
  22949. if (this._refRexture) {
  22950. this._refRexture.dispose();
  22951. }
  22952. _super.prototype.dispose.call(this, camera);
  22953. };
  22954. return RefractionPostProcess;
  22955. })(BABYLON.PostProcess);
  22956. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22957. })(BABYLON || (BABYLON = {}));
  22958. var BABYLON;
  22959. (function (BABYLON) {
  22960. var BlackAndWhitePostProcess = (function (_super) {
  22961. __extends(BlackAndWhitePostProcess, _super);
  22962. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22963. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22964. }
  22965. return BlackAndWhitePostProcess;
  22966. })(BABYLON.PostProcess);
  22967. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22968. })(BABYLON || (BABYLON = {}));
  22969. var BABYLON;
  22970. (function (BABYLON) {
  22971. var ConvolutionPostProcess = (function (_super) {
  22972. __extends(ConvolutionPostProcess, _super);
  22973. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22974. var _this = this;
  22975. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22976. this.kernel = kernel;
  22977. this.onApply = function (effect) {
  22978. effect.setFloat2("screenSize", _this.width, _this.height);
  22979. effect.setArray("kernel", _this.kernel);
  22980. };
  22981. }
  22982. // Statics
  22983. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22984. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22985. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22986. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22987. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22988. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22989. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22990. return ConvolutionPostProcess;
  22991. })(BABYLON.PostProcess);
  22992. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22993. })(BABYLON || (BABYLON = {}));
  22994. var BABYLON;
  22995. (function (BABYLON) {
  22996. var FilterPostProcess = (function (_super) {
  22997. __extends(FilterPostProcess, _super);
  22998. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22999. var _this = this;
  23000. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  23001. this.kernelMatrix = kernelMatrix;
  23002. this.onApply = function (effect) {
  23003. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  23004. };
  23005. }
  23006. return FilterPostProcess;
  23007. })(BABYLON.PostProcess);
  23008. BABYLON.FilterPostProcess = FilterPostProcess;
  23009. })(BABYLON || (BABYLON = {}));
  23010. var BABYLON;
  23011. (function (BABYLON) {
  23012. var FxaaPostProcess = (function (_super) {
  23013. __extends(FxaaPostProcess, _super);
  23014. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23015. var _this = this;
  23016. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  23017. this.onSizeChanged = function () {
  23018. _this.texelWidth = 1.0 / _this.width;
  23019. _this.texelHeight = 1.0 / _this.height;
  23020. };
  23021. this.onApply = function (effect) {
  23022. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  23023. };
  23024. }
  23025. return FxaaPostProcess;
  23026. })(BABYLON.PostProcess);
  23027. BABYLON.FxaaPostProcess = FxaaPostProcess;
  23028. })(BABYLON || (BABYLON = {}));
  23029. var BABYLON;
  23030. (function (BABYLON) {
  23031. var StereoscopicInterlacePostProcess = (function (_super) {
  23032. __extends(StereoscopicInterlacePostProcess, _super);
  23033. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  23034. var _this = this;
  23035. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  23036. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  23037. this.onSizeChanged = function () {
  23038. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  23039. };
  23040. this.onApply = function (effect) {
  23041. effect.setTextureFromPostProcess("camASampler", postProcessA);
  23042. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  23043. };
  23044. }
  23045. return StereoscopicInterlacePostProcess;
  23046. })(BABYLON.PostProcess);
  23047. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  23048. })(BABYLON || (BABYLON = {}));
  23049. var BABYLON;
  23050. (function (BABYLON) {
  23051. var LensFlare = (function () {
  23052. function LensFlare(size, position, color, imgUrl, system) {
  23053. this.size = size;
  23054. this.position = position;
  23055. this.dispose = function () {
  23056. if (this.texture) {
  23057. this.texture.dispose();
  23058. }
  23059. // Remove from scene
  23060. var index = this._system.lensFlares.indexOf(this);
  23061. this._system.lensFlares.splice(index, 1);
  23062. };
  23063. this.color = color || new BABYLON.Color3(1, 1, 1);
  23064. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  23065. this._system = system;
  23066. system.lensFlares.push(this);
  23067. }
  23068. return LensFlare;
  23069. })();
  23070. BABYLON.LensFlare = LensFlare;
  23071. })(BABYLON || (BABYLON = {}));
  23072. var BABYLON;
  23073. (function (BABYLON) {
  23074. var LensFlareSystem = (function () {
  23075. function LensFlareSystem(name, emitter, scene) {
  23076. this.name = name;
  23077. this.lensFlares = new Array();
  23078. this.borderLimit = 300;
  23079. this._vertexDeclaration = [2];
  23080. this._vertexStrideSize = 2 * 4;
  23081. this._isEnabled = true;
  23082. this._scene = scene;
  23083. this._emitter = emitter;
  23084. scene.lensFlareSystems.push(this);
  23085. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  23086. // VBO
  23087. var vertices = [];
  23088. vertices.push(1, 1);
  23089. vertices.push(-1, 1);
  23090. vertices.push(-1, -1);
  23091. vertices.push(1, -1);
  23092. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  23093. // Indices
  23094. var indices = [];
  23095. indices.push(0);
  23096. indices.push(1);
  23097. indices.push(2);
  23098. indices.push(0);
  23099. indices.push(2);
  23100. indices.push(3);
  23101. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  23102. // Effects
  23103. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  23104. }
  23105. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  23106. get: function () {
  23107. return this._isEnabled;
  23108. },
  23109. set: function (value) {
  23110. this._isEnabled = value;
  23111. },
  23112. enumerable: true,
  23113. configurable: true
  23114. });
  23115. LensFlareSystem.prototype.getScene = function () {
  23116. return this._scene;
  23117. };
  23118. LensFlareSystem.prototype.getEmitter = function () {
  23119. return this._emitter;
  23120. };
  23121. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  23122. this._emitter = newEmitter;
  23123. };
  23124. LensFlareSystem.prototype.getEmitterPosition = function () {
  23125. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  23126. };
  23127. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  23128. var position = this.getEmitterPosition();
  23129. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  23130. this._positionX = position.x;
  23131. this._positionY = position.y;
  23132. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  23133. if (position.z > 0) {
  23134. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  23135. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  23136. return true;
  23137. }
  23138. }
  23139. return false;
  23140. };
  23141. LensFlareSystem.prototype._isVisible = function () {
  23142. if (!this._isEnabled) {
  23143. return false;
  23144. }
  23145. var emitterPosition = this.getEmitterPosition();
  23146. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  23147. var distance = direction.length();
  23148. direction.normalize();
  23149. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  23150. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  23151. return !pickInfo.hit || pickInfo.distance > distance;
  23152. };
  23153. LensFlareSystem.prototype.render = function () {
  23154. if (!this._effect.isReady())
  23155. return false;
  23156. var engine = this._scene.getEngine();
  23157. var viewport = this._scene.activeCamera.viewport;
  23158. var globalViewport = viewport.toGlobal(engine);
  23159. // Position
  23160. if (!this.computeEffectivePosition(globalViewport)) {
  23161. return false;
  23162. }
  23163. // Visibility
  23164. if (!this._isVisible()) {
  23165. return false;
  23166. }
  23167. // Intensity
  23168. var awayX;
  23169. var awayY;
  23170. if (this._positionX < this.borderLimit + globalViewport.x) {
  23171. awayX = this.borderLimit + globalViewport.x - this._positionX;
  23172. }
  23173. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  23174. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  23175. }
  23176. else {
  23177. awayX = 0;
  23178. }
  23179. if (this._positionY < this.borderLimit + globalViewport.y) {
  23180. awayY = this.borderLimit + globalViewport.y - this._positionY;
  23181. }
  23182. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  23183. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  23184. }
  23185. else {
  23186. awayY = 0;
  23187. }
  23188. var away = (awayX > awayY) ? awayX : awayY;
  23189. if (away > this.borderLimit) {
  23190. away = this.borderLimit;
  23191. }
  23192. var intensity = 1.0 - (away / this.borderLimit);
  23193. if (intensity < 0) {
  23194. return false;
  23195. }
  23196. if (intensity > 1.0) {
  23197. intensity = 1.0;
  23198. }
  23199. // Position
  23200. var centerX = globalViewport.x + globalViewport.width / 2;
  23201. var centerY = globalViewport.y + globalViewport.height / 2;
  23202. var distX = centerX - this._positionX;
  23203. var distY = centerY - this._positionY;
  23204. // Effects
  23205. engine.enableEffect(this._effect);
  23206. engine.setState(false);
  23207. engine.setDepthBuffer(false);
  23208. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  23209. // VBOs
  23210. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  23211. // Flares
  23212. for (var index = 0; index < this.lensFlares.length; index++) {
  23213. var flare = this.lensFlares[index];
  23214. var x = centerX - (distX * flare.position);
  23215. var y = centerY - (distY * flare.position);
  23216. var cw = flare.size;
  23217. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  23218. var cx = 2 * (x / globalViewport.width) - 1.0;
  23219. var cy = 1.0 - 2 * (y / globalViewport.height);
  23220. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  23221. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  23222. // Texture
  23223. this._effect.setTexture("textureSampler", flare.texture);
  23224. // Color
  23225. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  23226. // Draw order
  23227. engine.draw(true, 0, 6);
  23228. }
  23229. engine.setDepthBuffer(true);
  23230. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23231. return true;
  23232. };
  23233. LensFlareSystem.prototype.dispose = function () {
  23234. if (this._vertexBuffer) {
  23235. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  23236. this._vertexBuffer = null;
  23237. }
  23238. if (this._indexBuffer) {
  23239. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  23240. this._indexBuffer = null;
  23241. }
  23242. while (this.lensFlares.length) {
  23243. this.lensFlares[0].dispose();
  23244. }
  23245. // Remove from scene
  23246. var index = this._scene.lensFlareSystems.indexOf(this);
  23247. this._scene.lensFlareSystems.splice(index, 1);
  23248. };
  23249. return LensFlareSystem;
  23250. })();
  23251. BABYLON.LensFlareSystem = LensFlareSystem;
  23252. })(BABYLON || (BABYLON = {}));
  23253. var BABYLON;
  23254. (function (BABYLON) {
  23255. var CannonJSPlugin = (function () {
  23256. function CannonJSPlugin() {
  23257. this._registeredMeshes = [];
  23258. this._physicsMaterials = [];
  23259. this.updateBodyPosition = function (mesh) {
  23260. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23261. var registeredMesh = this._registeredMeshes[index];
  23262. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23263. var body = registeredMesh.body;
  23264. var center = mesh.getBoundingInfo().boundingBox.center;
  23265. body.position.set(center.x, center.z, center.y);
  23266. body.quaternion.x = mesh.rotationQuaternion.x;
  23267. body.quaternion.z = mesh.rotationQuaternion.y;
  23268. body.quaternion.y = mesh.rotationQuaternion.z;
  23269. body.quaternion.w = -mesh.rotationQuaternion.w;
  23270. return;
  23271. }
  23272. }
  23273. };
  23274. }
  23275. CannonJSPlugin.prototype.initialize = function (iterations) {
  23276. if (iterations === void 0) { iterations = 10; }
  23277. this._world = new CANNON.World();
  23278. this._world.broadphase = new CANNON.NaiveBroadphase();
  23279. this._world.solver.iterations = iterations;
  23280. };
  23281. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23282. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23283. };
  23284. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23285. this._world.step(delta);
  23286. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23287. var registeredMesh = this._registeredMeshes[index];
  23288. if (registeredMesh.isChild) {
  23289. continue;
  23290. }
  23291. // Body position
  23292. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23293. var deltaPos = registeredMesh.delta;
  23294. if (deltaPos) {
  23295. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23296. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23297. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23298. }
  23299. else {
  23300. registeredMesh.mesh.position.x = bodyX;
  23301. registeredMesh.mesh.position.y = bodyZ;
  23302. registeredMesh.mesh.position.z = bodyY;
  23303. }
  23304. if (!registeredMesh.mesh.rotationQuaternion) {
  23305. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23306. }
  23307. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23308. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23309. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23310. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23311. }
  23312. };
  23313. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23314. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23315. };
  23316. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23317. this.unregisterMesh(mesh);
  23318. mesh.computeWorldMatrix(true);
  23319. switch (impostor) {
  23320. case BABYLON.PhysicsEngine.SphereImpostor:
  23321. var bbox = mesh.getBoundingInfo().boundingBox;
  23322. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23323. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23324. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23325. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23326. case BABYLON.PhysicsEngine.BoxImpostor:
  23327. bbox = mesh.getBoundingInfo().boundingBox;
  23328. var min = bbox.minimumWorld;
  23329. var max = bbox.maximumWorld;
  23330. var box = max.subtract(min).scale(0.5);
  23331. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23332. case BABYLON.PhysicsEngine.PlaneImpostor:
  23333. return this._createPlane(mesh, options);
  23334. case BABYLON.PhysicsEngine.MeshImpostor:
  23335. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23336. var rawFaces = mesh.getIndices();
  23337. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23338. }
  23339. return null;
  23340. };
  23341. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23342. var shape = new CANNON.Sphere(radius);
  23343. if (!options) {
  23344. return shape;
  23345. }
  23346. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23347. };
  23348. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23349. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23350. if (!options) {
  23351. return shape;
  23352. }
  23353. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23354. };
  23355. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23356. var shape = new CANNON.Plane();
  23357. if (!options) {
  23358. return shape;
  23359. }
  23360. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23361. };
  23362. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23363. var verts = [], faces = [];
  23364. mesh.computeWorldMatrix(true);
  23365. // Get vertices
  23366. for (var i = 0; i < rawVerts.length; i += 3) {
  23367. var transformed = BABYLON.Vector3.Zero();
  23368. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23369. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23370. }
  23371. // Get faces
  23372. for (var j = 0; j < rawFaces.length; j += 3) {
  23373. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23374. }
  23375. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23376. if (!options) {
  23377. return shape;
  23378. }
  23379. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23380. };
  23381. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23382. var index;
  23383. var mat;
  23384. for (index = 0; index < this._physicsMaterials.length; index++) {
  23385. mat = this._physicsMaterials[index];
  23386. if (mat.friction === friction && mat.restitution === restitution) {
  23387. return mat;
  23388. }
  23389. }
  23390. var currentMat = new CANNON.Material();
  23391. currentMat.friction = friction;
  23392. currentMat.restitution = restitution;
  23393. this._physicsMaterials.push(currentMat);
  23394. for (index = 0; index < this._physicsMaterials.length; index++) {
  23395. mat = this._physicsMaterials[index];
  23396. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23397. contactMaterial.contactEquationStiffness = 1e10;
  23398. contactMaterial.contactEquationRegularizationTime = 10;
  23399. this._world.addContactMaterial(contactMaterial);
  23400. }
  23401. return currentMat;
  23402. };
  23403. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23404. var initialRotation = null;
  23405. if (mesh.rotationQuaternion) {
  23406. initialRotation = mesh.rotationQuaternion.clone();
  23407. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23408. }
  23409. // The delta between the mesh position and the mesh bounding box center
  23410. var bbox = mesh.getBoundingInfo().boundingBox;
  23411. var deltaPosition = mesh.position.subtract(bbox.center);
  23412. var material = this._addMaterial(friction, restitution);
  23413. var body = new CANNON.RigidBody(mass, shape, material);
  23414. if (initialRotation) {
  23415. body.quaternion.x = initialRotation.x;
  23416. body.quaternion.z = initialRotation.y;
  23417. body.quaternion.y = initialRotation.z;
  23418. body.quaternion.w = -initialRotation.w;
  23419. }
  23420. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23421. this._world.add(body);
  23422. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23423. return body;
  23424. };
  23425. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23426. var compoundShape = new CANNON.Compound();
  23427. for (var index = 0; index < parts.length; index++) {
  23428. var mesh = parts[index].mesh;
  23429. var shape = this.registerMesh(mesh, parts[index].impostor);
  23430. if (index == 0) {
  23431. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23432. }
  23433. else {
  23434. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23435. }
  23436. }
  23437. var initialMesh = parts[0].mesh;
  23438. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23439. body.parts = parts;
  23440. return body;
  23441. };
  23442. CannonJSPlugin.prototype._unbindBody = function (body) {
  23443. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23444. var registeredMesh = this._registeredMeshes[index];
  23445. if (registeredMesh.body === body) {
  23446. registeredMesh.body = null;
  23447. registeredMesh.delta = 0;
  23448. }
  23449. }
  23450. };
  23451. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23452. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23453. var registeredMesh = this._registeredMeshes[index];
  23454. if (registeredMesh.mesh === mesh) {
  23455. // Remove body
  23456. if (registeredMesh.body) {
  23457. this._world.remove(registeredMesh.body);
  23458. this._unbindBody(registeredMesh.body);
  23459. }
  23460. this._registeredMeshes.splice(index, 1);
  23461. return;
  23462. }
  23463. }
  23464. };
  23465. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23466. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23467. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23468. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23469. var registeredMesh = this._registeredMeshes[index];
  23470. if (registeredMesh.mesh === mesh) {
  23471. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23472. return;
  23473. }
  23474. }
  23475. };
  23476. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23477. var body1 = null, body2 = null;
  23478. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23479. var registeredMesh = this._registeredMeshes[index];
  23480. if (registeredMesh.mesh === mesh1) {
  23481. body1 = registeredMesh.body;
  23482. }
  23483. else if (registeredMesh.mesh === mesh2) {
  23484. body2 = registeredMesh.body;
  23485. }
  23486. }
  23487. if (!body1 || !body2) {
  23488. return false;
  23489. }
  23490. 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));
  23491. this._world.addConstraint(constraint);
  23492. return true;
  23493. };
  23494. CannonJSPlugin.prototype.dispose = function () {
  23495. while (this._registeredMeshes.length) {
  23496. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23497. }
  23498. };
  23499. CannonJSPlugin.prototype.isSupported = function () {
  23500. return window.CANNON !== undefined;
  23501. };
  23502. return CannonJSPlugin;
  23503. })();
  23504. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23505. })(BABYLON || (BABYLON = {}));
  23506. var BABYLON;
  23507. (function (BABYLON) {
  23508. var OimoJSPlugin = (function () {
  23509. function OimoJSPlugin() {
  23510. this._registeredMeshes = [];
  23511. /**
  23512. * Update the body position according to the mesh position
  23513. * @param mesh
  23514. */
  23515. this.updateBodyPosition = function (mesh) {
  23516. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23517. var registeredMesh = this._registeredMeshes[index];
  23518. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23519. var body = registeredMesh.body.body;
  23520. mesh.computeWorldMatrix(true);
  23521. var center = mesh.getBoundingInfo().boundingBox.center;
  23522. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  23523. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  23524. body.sleeping = false;
  23525. return;
  23526. }
  23527. // Case where the parent has been updated
  23528. if (registeredMesh.mesh.parent === mesh) {
  23529. mesh.computeWorldMatrix(true);
  23530. registeredMesh.mesh.computeWorldMatrix(true);
  23531. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  23532. var absoluteRotation = mesh.rotation;
  23533. body = registeredMesh.body.body;
  23534. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  23535. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  23536. body.sleeping = false;
  23537. return;
  23538. }
  23539. }
  23540. };
  23541. }
  23542. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  23543. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23544. };
  23545. OimoJSPlugin.prototype.initialize = function (iterations) {
  23546. this._world = new OIMO.World();
  23547. this._world.clear();
  23548. };
  23549. OimoJSPlugin.prototype.setGravity = function (gravity) {
  23550. this._world.gravity = gravity;
  23551. };
  23552. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23553. var body = null;
  23554. this.unregisterMesh(mesh);
  23555. mesh.computeWorldMatrix(true);
  23556. var initialRotation = null;
  23557. if (mesh.rotationQuaternion) {
  23558. initialRotation = mesh.rotationQuaternion.clone();
  23559. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23560. mesh.computeWorldMatrix(true);
  23561. }
  23562. var bbox = mesh.getBoundingInfo().boundingBox;
  23563. // The delta between the mesh position and the mesh bounding box center
  23564. var deltaPosition = mesh.position.subtract(bbox.center);
  23565. // Transform delta position with the rotation
  23566. if (initialRotation) {
  23567. var m = new BABYLON.Matrix();
  23568. initialRotation.toRotationMatrix(m);
  23569. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  23570. }
  23571. // register mesh
  23572. switch (impostor) {
  23573. case BABYLON.PhysicsEngine.SphereImpostor:
  23574. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23575. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23576. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23577. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23578. body = new OIMO.Body({
  23579. type: 'sphere',
  23580. size: [size],
  23581. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23582. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23583. move: options.mass != 0,
  23584. config: [options.mass, options.friction, options.restitution],
  23585. world: this._world
  23586. });
  23587. break;
  23588. case BABYLON.PhysicsEngine.PlaneImpostor:
  23589. //Oimo "fakes" a cylinder as a box, so why don't we!
  23590. case BABYLON.PhysicsEngine.CylinderImpostor:
  23591. case BABYLON.PhysicsEngine.BoxImpostor:
  23592. var min = bbox.minimumWorld;
  23593. var max = bbox.maximumWorld;
  23594. var box = max.subtract(min);
  23595. var sizeX = this._checkWithEpsilon(box.x);
  23596. var sizeY = this._checkWithEpsilon(box.y);
  23597. var sizeZ = this._checkWithEpsilon(box.z);
  23598. body = new OIMO.Body({
  23599. type: 'box',
  23600. size: [sizeX, sizeY, sizeZ],
  23601. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  23602. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  23603. move: options.mass != 0,
  23604. config: [options.mass, options.friction, options.restitution],
  23605. world: this._world
  23606. });
  23607. break;
  23608. }
  23609. //If quaternion was set as the rotation of the object
  23610. if (initialRotation) {
  23611. //We have to access the rigid body's properties to set the quaternion.
  23612. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  23613. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  23614. //update the internal rotation matrix
  23615. body.body.syncShapes();
  23616. }
  23617. this._registeredMeshes.push({
  23618. mesh: mesh,
  23619. body: body,
  23620. delta: deltaPosition
  23621. });
  23622. return body;
  23623. };
  23624. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23625. var types = [], sizes = [], positions = [], rotations = [];
  23626. var initialMesh = parts[0].mesh;
  23627. for (var index = 0; index < parts.length; index++) {
  23628. var part = parts[index];
  23629. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  23630. types.push(bodyParameters.type);
  23631. sizes.push.apply(sizes, bodyParameters.size);
  23632. positions.push.apply(positions, bodyParameters.pos);
  23633. rotations.push.apply(rotations, bodyParameters.rot);
  23634. }
  23635. var body = new OIMO.Body({
  23636. type: types,
  23637. size: sizes,
  23638. pos: positions,
  23639. rot: rotations,
  23640. move: options.mass != 0,
  23641. config: [options.mass, options.friction, options.restitution],
  23642. world: this._world
  23643. });
  23644. this._registeredMeshes.push({
  23645. mesh: initialMesh,
  23646. body: body
  23647. });
  23648. return body;
  23649. };
  23650. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  23651. var bodyParameters = null;
  23652. var mesh = part.mesh;
  23653. // We need the bounding box/sphere info to compute the physics body
  23654. mesh.computeWorldMatrix();
  23655. switch (part.impostor) {
  23656. case BABYLON.PhysicsEngine.SphereImpostor:
  23657. var bbox = mesh.getBoundingInfo().boundingBox;
  23658. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23659. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23660. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23661. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  23662. bodyParameters = {
  23663. type: 'sphere',
  23664. /* bug with oimo : sphere needs 3 sizes in this case */
  23665. size: [size, -1, -1],
  23666. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  23667. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23668. };
  23669. break;
  23670. case BABYLON.PhysicsEngine.PlaneImpostor:
  23671. case BABYLON.PhysicsEngine.BoxImpostor:
  23672. bbox = mesh.getBoundingInfo().boundingBox;
  23673. var min = bbox.minimumWorld;
  23674. var max = bbox.maximumWorld;
  23675. var box = max.subtract(min);
  23676. var sizeX = this._checkWithEpsilon(box.x);
  23677. var sizeY = this._checkWithEpsilon(box.y);
  23678. var sizeZ = this._checkWithEpsilon(box.z);
  23679. var relativePosition = mesh.position;
  23680. bodyParameters = {
  23681. type: 'box',
  23682. size: [sizeX, sizeY, sizeZ],
  23683. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  23684. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  23685. };
  23686. break;
  23687. }
  23688. return bodyParameters;
  23689. };
  23690. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  23691. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23692. var registeredMesh = this._registeredMeshes[index];
  23693. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23694. if (registeredMesh.body) {
  23695. this._world.removeRigidBody(registeredMesh.body.body);
  23696. this._unbindBody(registeredMesh.body);
  23697. }
  23698. this._registeredMeshes.splice(index, 1);
  23699. return;
  23700. }
  23701. }
  23702. };
  23703. OimoJSPlugin.prototype._unbindBody = function (body) {
  23704. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23705. var registeredMesh = this._registeredMeshes[index];
  23706. if (registeredMesh.body === body) {
  23707. registeredMesh.body = null;
  23708. }
  23709. }
  23710. };
  23711. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23712. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23713. var registeredMesh = this._registeredMeshes[index];
  23714. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23715. // Get object mass to have a behaviour similar to cannon.js
  23716. var mass = registeredMesh.body.body.massInfo.mass;
  23717. // The force is scaled with the mass of object
  23718. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  23719. return;
  23720. }
  23721. }
  23722. };
  23723. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23724. var body1 = null, body2 = null;
  23725. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23726. var registeredMesh = this._registeredMeshes[index];
  23727. if (registeredMesh.mesh === mesh1) {
  23728. body1 = registeredMesh.body.body;
  23729. }
  23730. else if (registeredMesh.mesh === mesh2) {
  23731. body2 = registeredMesh.body.body;
  23732. }
  23733. }
  23734. if (!body1 || !body2) {
  23735. return false;
  23736. }
  23737. if (!options) {
  23738. options = {};
  23739. }
  23740. new OIMO.Link({
  23741. type: options.type,
  23742. body1: body1,
  23743. body2: body2,
  23744. min: options.min,
  23745. max: options.max,
  23746. axe1: options.axe1,
  23747. axe2: options.axe2,
  23748. pos1: [pivot1.x, pivot1.y, pivot1.z],
  23749. pos2: [pivot2.x, pivot2.y, pivot2.z],
  23750. collision: options.collision,
  23751. spring: options.spring,
  23752. world: this._world
  23753. });
  23754. return true;
  23755. };
  23756. OimoJSPlugin.prototype.dispose = function () {
  23757. this._world.clear();
  23758. while (this._registeredMeshes.length) {
  23759. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23760. }
  23761. };
  23762. OimoJSPlugin.prototype.isSupported = function () {
  23763. return OIMO !== undefined;
  23764. };
  23765. OimoJSPlugin.prototype._getLastShape = function (body) {
  23766. var lastShape = body.shapes;
  23767. while (lastShape.next) {
  23768. lastShape = lastShape.next;
  23769. }
  23770. return lastShape;
  23771. };
  23772. OimoJSPlugin.prototype.runOneStep = function (time) {
  23773. this._world.step();
  23774. // Update the position of all registered meshes
  23775. var i = this._registeredMeshes.length;
  23776. var m;
  23777. while (i--) {
  23778. var body = this._registeredMeshes[i].body.body;
  23779. var mesh = this._registeredMeshes[i].mesh;
  23780. var delta = this._registeredMeshes[i].delta;
  23781. if (!body.sleeping) {
  23782. if (body.shapes.next) {
  23783. var parentShape = this._getLastShape(body);
  23784. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  23785. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  23786. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  23787. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  23788. if (!mesh.rotationQuaternion) {
  23789. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23790. }
  23791. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  23792. mesh.computeWorldMatrix();
  23793. }
  23794. else {
  23795. m = body.getMatrix();
  23796. mtx = BABYLON.Matrix.FromArray(m);
  23797. // Body position
  23798. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  23799. if (!delta) {
  23800. mesh.position.x = bodyX;
  23801. mesh.position.y = bodyY;
  23802. mesh.position.z = bodyZ;
  23803. }
  23804. else {
  23805. mesh.position.x = bodyX + delta.x;
  23806. mesh.position.y = bodyY + delta.y;
  23807. mesh.position.z = bodyZ + delta.z;
  23808. }
  23809. if (!mesh.rotationQuaternion) {
  23810. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23811. }
  23812. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  23813. mesh.computeWorldMatrix();
  23814. }
  23815. }
  23816. }
  23817. };
  23818. return OimoJSPlugin;
  23819. })();
  23820. BABYLON.OimoJSPlugin = OimoJSPlugin;
  23821. })(BABYLON || (BABYLON = {}));
  23822. var BABYLON;
  23823. (function (BABYLON) {
  23824. var PhysicsEngine = (function () {
  23825. function PhysicsEngine(plugin) {
  23826. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  23827. }
  23828. PhysicsEngine.prototype._initialize = function (gravity) {
  23829. this._currentPlugin.initialize();
  23830. this._setGravity(gravity);
  23831. };
  23832. PhysicsEngine.prototype._runOneStep = function (delta) {
  23833. if (delta > 0.1) {
  23834. delta = 0.1;
  23835. }
  23836. else if (delta <= 0) {
  23837. delta = 1.0 / 60.0;
  23838. }
  23839. this._currentPlugin.runOneStep(delta);
  23840. };
  23841. PhysicsEngine.prototype._setGravity = function (gravity) {
  23842. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  23843. this._currentPlugin.setGravity(this.gravity);
  23844. };
  23845. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  23846. return this._currentPlugin.registerMesh(mesh, impostor, options);
  23847. };
  23848. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  23849. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  23850. };
  23851. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  23852. this._currentPlugin.unregisterMesh(mesh);
  23853. };
  23854. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  23855. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  23856. };
  23857. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  23858. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  23859. };
  23860. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  23861. this._currentPlugin.updateBodyPosition(mesh);
  23862. };
  23863. PhysicsEngine.prototype.dispose = function () {
  23864. this._currentPlugin.dispose();
  23865. };
  23866. PhysicsEngine.prototype.isSupported = function () {
  23867. return this._currentPlugin.isSupported();
  23868. };
  23869. // Statics
  23870. PhysicsEngine.NoImpostor = 0;
  23871. PhysicsEngine.SphereImpostor = 1;
  23872. PhysicsEngine.BoxImpostor = 2;
  23873. PhysicsEngine.PlaneImpostor = 3;
  23874. PhysicsEngine.MeshImpostor = 4;
  23875. PhysicsEngine.CapsuleImpostor = 5;
  23876. PhysicsEngine.ConeImpostor = 6;
  23877. PhysicsEngine.CylinderImpostor = 7;
  23878. PhysicsEngine.ConvexHullImpostor = 8;
  23879. PhysicsEngine.Epsilon = 0.001;
  23880. return PhysicsEngine;
  23881. })();
  23882. BABYLON.PhysicsEngine = PhysicsEngine;
  23883. })(BABYLON || (BABYLON = {}));
  23884. var BABYLON;
  23885. (function (BABYLON) {
  23886. var serializeLight = function (light) {
  23887. var serializationObject = {};
  23888. serializationObject.name = light.name;
  23889. serializationObject.id = light.id;
  23890. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23891. if (light instanceof BABYLON.PointLight) {
  23892. serializationObject.type = 0;
  23893. serializationObject.position = light.position.asArray();
  23894. }
  23895. else if (light instanceof BABYLON.DirectionalLight) {
  23896. serializationObject.type = 1;
  23897. var directionalLight = light;
  23898. serializationObject.position = directionalLight.position.asArray();
  23899. serializationObject.direction = directionalLight.direction.asArray();
  23900. }
  23901. else if (light instanceof BABYLON.SpotLight) {
  23902. serializationObject.type = 2;
  23903. var spotLight = light;
  23904. serializationObject.position = spotLight.position.asArray();
  23905. serializationObject.direction = spotLight.position.asArray();
  23906. serializationObject.angle = spotLight.angle;
  23907. serializationObject.exponent = spotLight.exponent;
  23908. }
  23909. else if (light instanceof BABYLON.HemisphericLight) {
  23910. serializationObject.type = 3;
  23911. var hemisphericLight = light;
  23912. serializationObject.direction = hemisphericLight.direction.asArray();
  23913. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23914. }
  23915. if (light.intensity) {
  23916. serializationObject.intensity = light.intensity;
  23917. }
  23918. serializationObject.range = light.range;
  23919. serializationObject.diffuse = light.diffuse.asArray();
  23920. serializationObject.specular = light.specular.asArray();
  23921. return serializationObject;
  23922. };
  23923. var serializeFresnelParameter = function (fresnelParameter) {
  23924. var serializationObject = {};
  23925. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23926. serializationObject.leftColor = fresnelParameter.leftColor;
  23927. serializationObject.rightColor = fresnelParameter.rightColor;
  23928. serializationObject.bias = fresnelParameter.bias;
  23929. serializationObject.power = fresnelParameter.power;
  23930. return serializationObject;
  23931. };
  23932. var appendAnimations = function (source, destination) {
  23933. if (source.animations) {
  23934. destination.animations = [];
  23935. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23936. var animation = source.animations[animationIndex];
  23937. destination.animations.push(serializeAnimation(animation));
  23938. }
  23939. }
  23940. };
  23941. var serializeCamera = function (camera) {
  23942. var serializationObject = {};
  23943. serializationObject.name = camera.name;
  23944. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23945. serializationObject.id = camera.id;
  23946. serializationObject.position = camera.position.asArray();
  23947. // Parent
  23948. if (camera.parent) {
  23949. serializationObject.parentId = camera.parent.id;
  23950. }
  23951. serializationObject.fov = camera.fov;
  23952. serializationObject.minZ = camera.minZ;
  23953. serializationObject.maxZ = camera.maxZ;
  23954. serializationObject.inertia = camera.inertia;
  23955. //setting the type
  23956. if (camera instanceof BABYLON.FreeCamera) {
  23957. serializationObject.type = "FreeCamera";
  23958. }
  23959. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23960. serializationObject.type = "ArcRotateCamera";
  23961. }
  23962. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23963. serializationObject.type = "AnaglyphArcRotateCamera";
  23964. }
  23965. else if (camera instanceof BABYLON.GamepadCamera) {
  23966. serializationObject.type = "GamepadCamera";
  23967. }
  23968. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23969. serializationObject.type = "AnaglyphFreeCamera";
  23970. }
  23971. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23972. serializationObject.type = "DeviceOrientationCamera";
  23973. }
  23974. else if (camera instanceof BABYLON.FollowCamera) {
  23975. serializationObject.type = "FollowCamera";
  23976. }
  23977. else if (camera instanceof BABYLON.TouchCamera) {
  23978. serializationObject.type = "TouchCamera";
  23979. }
  23980. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23981. serializationObject.type = "VirtualJoysticksCamera";
  23982. }
  23983. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23984. serializationObject.type = "WebVRFreeCamera";
  23985. }
  23986. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23987. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23988. }
  23989. //special properties of specific cameras
  23990. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23991. var arcCamera = camera;
  23992. serializationObject.alpha = arcCamera.alpha;
  23993. serializationObject.beta = arcCamera.beta;
  23994. serializationObject.radius = arcCamera.radius;
  23995. if (arcCamera.target && arcCamera.target.id) {
  23996. serializationObject.lockedTargetId = arcCamera.target.id;
  23997. }
  23998. }
  23999. else if (camera instanceof BABYLON.FollowCamera) {
  24000. var followCam = camera;
  24001. serializationObject.radius = followCam.radius;
  24002. serializationObject.heightOffset = followCam.heightOffset;
  24003. serializationObject.rotationOffset = followCam.rotationOffset;
  24004. }
  24005. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  24006. //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.
  24007. if (camera['_interaxialDistance'] !== undefined) {
  24008. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  24009. }
  24010. }
  24011. //general properties that not all cameras have. The [] is due to typescript's type safety
  24012. if (camera['speed'] !== undefined) {
  24013. serializationObject.speed = camera['speed'];
  24014. }
  24015. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  24016. serializationObject.target = camera['target'].asArray();
  24017. }
  24018. // Target
  24019. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  24020. serializationObject.rotation = camera['rotation'].asArray();
  24021. }
  24022. // Locked target
  24023. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  24024. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  24025. }
  24026. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  24027. serializationObject.applyGravity = camera['applyGravity'] || false;
  24028. if (camera['ellipsoid']) {
  24029. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  24030. }
  24031. // Animations
  24032. appendAnimations(camera, serializationObject);
  24033. // Layer mask
  24034. serializationObject.layerMask = camera.layerMask;
  24035. return serializationObject;
  24036. };
  24037. var serializeAnimation = function (animation) {
  24038. var serializationObject = {};
  24039. serializationObject.name = animation.name;
  24040. serializationObject.property = animation.targetProperty;
  24041. serializationObject.framePerSecond = animation.framePerSecond;
  24042. serializationObject.dataType = animation.dataType;
  24043. serializationObject.loopBehavior = animation.loopMode;
  24044. var dataType = animation.dataType;
  24045. serializationObject.keys = [];
  24046. var keys = animation.getKeys();
  24047. for (var index = 0; index < keys.length; index++) {
  24048. var animationKey = keys[index];
  24049. var key = {};
  24050. key.frame = animationKey.frame;
  24051. switch (dataType) {
  24052. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  24053. key.values = [animationKey.value];
  24054. break;
  24055. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  24056. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  24057. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  24058. key.values = animationKey.value.asArray();
  24059. break;
  24060. }
  24061. serializationObject.keys.push(key);
  24062. }
  24063. return serializationObject;
  24064. };
  24065. var serializeMultiMaterial = function (material) {
  24066. var serializationObject = {};
  24067. serializationObject.name = material.name;
  24068. serializationObject.id = material.id;
  24069. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24070. serializationObject.materials = [];
  24071. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  24072. var subMat = material.subMaterials[matIndex];
  24073. if (subMat) {
  24074. serializationObject.materials.push(subMat.id);
  24075. }
  24076. else {
  24077. serializationObject.materials.push(null);
  24078. }
  24079. }
  24080. return serializationObject;
  24081. };
  24082. var serializeMaterial = function (material) {
  24083. var serializationObject = {};
  24084. serializationObject.name = material.name;
  24085. serializationObject.ambient = material.ambientColor.asArray();
  24086. serializationObject.diffuse = material.diffuseColor.asArray();
  24087. serializationObject.specular = material.specularColor.asArray();
  24088. serializationObject.specularPower = material.specularPower;
  24089. serializationObject.emissive = material.emissiveColor.asArray();
  24090. serializationObject.alpha = material.alpha;
  24091. serializationObject.id = material.id;
  24092. serializationObject.tags = BABYLON.Tags.GetTags(material);
  24093. serializationObject.backFaceCulling = material.backFaceCulling;
  24094. if (material.diffuseTexture) {
  24095. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  24096. }
  24097. if (material.diffuseFresnelParameters) {
  24098. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  24099. }
  24100. if (material.ambientTexture) {
  24101. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  24102. }
  24103. if (material.opacityTexture) {
  24104. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  24105. }
  24106. if (material.opacityFresnelParameters) {
  24107. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  24108. }
  24109. if (material.reflectionTexture) {
  24110. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  24111. }
  24112. if (material.reflectionFresnelParameters) {
  24113. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  24114. }
  24115. if (material.emissiveTexture) {
  24116. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  24117. }
  24118. if (material.emissiveFresnelParameters) {
  24119. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  24120. }
  24121. if (material.specularTexture) {
  24122. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  24123. }
  24124. if (material.bumpTexture) {
  24125. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  24126. }
  24127. return serializationObject;
  24128. };
  24129. var serializeTexture = function (texture) {
  24130. var serializationObject = {};
  24131. if (!texture.name) {
  24132. return null;
  24133. }
  24134. if (texture instanceof BABYLON.CubeTexture) {
  24135. serializationObject.name = texture.name;
  24136. serializationObject.hasAlpha = texture.hasAlpha;
  24137. serializationObject.isCube = true;
  24138. serializationObject.level = texture.level;
  24139. serializationObject.coordinatesMode = texture.coordinatesMode;
  24140. return serializationObject;
  24141. }
  24142. if (texture instanceof BABYLON.MirrorTexture) {
  24143. var mirrorTexture = texture;
  24144. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  24145. serializationObject.renderList = [];
  24146. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  24147. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  24148. }
  24149. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  24150. }
  24151. else if (texture instanceof BABYLON.RenderTargetTexture) {
  24152. var renderTargetTexture = texture;
  24153. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  24154. serializationObject.renderList = [];
  24155. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  24156. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  24157. }
  24158. }
  24159. var regularTexture = texture;
  24160. serializationObject.name = texture.name;
  24161. serializationObject.hasAlpha = texture.hasAlpha;
  24162. serializationObject.level = texture.level;
  24163. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  24164. serializationObject.coordinatesMode = texture.coordinatesMode;
  24165. serializationObject.uOffset = regularTexture.uOffset;
  24166. serializationObject.vOffset = regularTexture.vOffset;
  24167. serializationObject.uScale = regularTexture.uScale;
  24168. serializationObject.vScale = regularTexture.vScale;
  24169. serializationObject.uAng = regularTexture.uAng;
  24170. serializationObject.vAng = regularTexture.vAng;
  24171. serializationObject.wAng = regularTexture.wAng;
  24172. serializationObject.wrapU = texture.wrapU;
  24173. serializationObject.wrapV = texture.wrapV;
  24174. // Animations
  24175. appendAnimations(texture, serializationObject);
  24176. return serializationObject;
  24177. };
  24178. var serializeSkeleton = function (skeleton) {
  24179. var serializationObject = {};
  24180. serializationObject.name = skeleton.name;
  24181. serializationObject.id = skeleton.id;
  24182. serializationObject.bones = [];
  24183. for (var index = 0; index < skeleton.bones.length; index++) {
  24184. var bone = skeleton.bones[index];
  24185. var serializedBone = {
  24186. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  24187. name: bone.name,
  24188. matrix: bone.getLocalMatrix().toArray()
  24189. };
  24190. serializationObject.bones.push(serializedBone);
  24191. if (bone.animations && bone.animations.length > 0) {
  24192. serializedBone.animation = serializeAnimation(bone.animations[0]);
  24193. }
  24194. }
  24195. return serializationObject;
  24196. };
  24197. var serializeParticleSystem = function (particleSystem) {
  24198. var serializationObject = {};
  24199. serializationObject.emitterId = particleSystem.emitter.id;
  24200. serializationObject.capacity = particleSystem.getCapacity();
  24201. if (particleSystem.particleTexture) {
  24202. serializationObject.textureName = particleSystem.particleTexture.name;
  24203. }
  24204. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  24205. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  24206. serializationObject.minSize = particleSystem.minSize;
  24207. serializationObject.maxSize = particleSystem.maxSize;
  24208. serializationObject.minLifeTime = particleSystem.minLifeTime;
  24209. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  24210. serializationObject.emitRate = particleSystem.emitRate;
  24211. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  24212. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  24213. serializationObject.gravity = particleSystem.gravity.asArray();
  24214. serializationObject.direction1 = particleSystem.direction1.asArray();
  24215. serializationObject.direction2 = particleSystem.direction2.asArray();
  24216. serializationObject.color1 = particleSystem.color1.asArray();
  24217. serializationObject.color2 = particleSystem.color2.asArray();
  24218. serializationObject.colorDead = particleSystem.colorDead.asArray();
  24219. serializationObject.updateSpeed = particleSystem.updateSpeed;
  24220. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  24221. serializationObject.textureMask = particleSystem.textureMask.asArray();
  24222. serializationObject.blendMode = particleSystem.blendMode;
  24223. return serializationObject;
  24224. };
  24225. var serializeLensFlareSystem = function (lensFlareSystem) {
  24226. var serializationObject = {};
  24227. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  24228. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  24229. serializationObject.flares = [];
  24230. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  24231. var flare = lensFlareSystem.lensFlares[index];
  24232. serializationObject.flares.push({
  24233. size: flare.size,
  24234. position: flare.position,
  24235. color: flare.color.asArray(),
  24236. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  24237. });
  24238. }
  24239. return serializationObject;
  24240. };
  24241. var serializeShadowGenerator = function (light) {
  24242. var serializationObject = {};
  24243. var shadowGenerator = light.getShadowGenerator();
  24244. serializationObject.lightId = light.id;
  24245. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  24246. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  24247. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  24248. serializationObject.renderList = [];
  24249. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  24250. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  24251. serializationObject.renderList.push(mesh.id);
  24252. }
  24253. return serializationObject;
  24254. };
  24255. var serializedGeometries = [];
  24256. var serializeGeometry = function (geometry, serializationGeometries) {
  24257. if (serializedGeometries[geometry.id]) {
  24258. return;
  24259. }
  24260. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  24261. serializationGeometries.boxes.push(serializeBox(geometry));
  24262. }
  24263. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  24264. serializationGeometries.spheres.push(serializeSphere(geometry));
  24265. }
  24266. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  24267. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  24268. }
  24269. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  24270. serializationGeometries.toruses.push(serializeTorus(geometry));
  24271. }
  24272. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  24273. serializationGeometries.grounds.push(serializeGround(geometry));
  24274. }
  24275. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  24276. serializationGeometries.planes.push(serializePlane(geometry));
  24277. }
  24278. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  24279. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  24280. }
  24281. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  24282. throw new Error("Unknown primitive type");
  24283. }
  24284. else {
  24285. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  24286. }
  24287. serializedGeometries[geometry.id] = true;
  24288. };
  24289. var serializeGeometryBase = function (geometry) {
  24290. var serializationObject = {};
  24291. serializationObject.id = geometry.id;
  24292. if (BABYLON.Tags.HasTags(geometry)) {
  24293. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  24294. }
  24295. return serializationObject;
  24296. };
  24297. var serializeVertexData = function (vertexData) {
  24298. var serializationObject = serializeGeometryBase(vertexData);
  24299. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24300. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24301. }
  24302. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24303. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24304. }
  24305. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24306. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24307. }
  24308. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24309. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  24310. }
  24311. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24312. serializationObject.uvs3 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  24313. }
  24314. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24315. serializationObject.uvs4 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  24316. }
  24317. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24318. serializationObject.uvs5 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  24319. }
  24320. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24321. serializationObject.uvs6 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  24322. }
  24323. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24324. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  24325. }
  24326. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24327. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24328. serializationObject.matricesIndices._isExpanded = true;
  24329. }
  24330. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24331. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24332. }
  24333. serializationObject.indices = vertexData.getIndices();
  24334. return serializationObject;
  24335. };
  24336. var serializePrimitive = function (primitive) {
  24337. var serializationObject = serializeGeometryBase(primitive);
  24338. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  24339. return serializationObject;
  24340. };
  24341. var serializeBox = function (box) {
  24342. var serializationObject = serializePrimitive(box);
  24343. serializationObject.size = box.size;
  24344. return serializationObject;
  24345. };
  24346. var serializeSphere = function (sphere) {
  24347. var serializationObject = serializePrimitive(sphere);
  24348. serializationObject.segments = sphere.segments;
  24349. serializationObject.diameter = sphere.diameter;
  24350. return serializationObject;
  24351. };
  24352. var serializeCylinder = function (cylinder) {
  24353. var serializationObject = serializePrimitive(cylinder);
  24354. serializationObject.height = cylinder.height;
  24355. serializationObject.diameterTop = cylinder.diameterTop;
  24356. serializationObject.diameterBottom = cylinder.diameterBottom;
  24357. serializationObject.tessellation = cylinder.tessellation;
  24358. return serializationObject;
  24359. };
  24360. var serializeTorus = function (torus) {
  24361. var serializationObject = serializePrimitive(torus);
  24362. serializationObject.diameter = torus.diameter;
  24363. serializationObject.thickness = torus.thickness;
  24364. serializationObject.tessellation = torus.tessellation;
  24365. return serializationObject;
  24366. };
  24367. var serializeGround = function (ground) {
  24368. var serializationObject = serializePrimitive(ground);
  24369. serializationObject.width = ground.width;
  24370. serializationObject.height = ground.height;
  24371. serializationObject.subdivisions = ground.subdivisions;
  24372. return serializationObject;
  24373. };
  24374. var serializePlane = function (plane) {
  24375. var serializationObject = serializePrimitive(plane);
  24376. serializationObject.size = plane.size;
  24377. return serializationObject;
  24378. };
  24379. var serializeTorusKnot = function (torusKnot) {
  24380. var serializationObject = serializePrimitive(torusKnot);
  24381. serializationObject.radius = torusKnot.radius;
  24382. serializationObject.tube = torusKnot.tube;
  24383. serializationObject.radialSegments = torusKnot.radialSegments;
  24384. serializationObject.tubularSegments = torusKnot.tubularSegments;
  24385. serializationObject.p = torusKnot.p;
  24386. serializationObject.q = torusKnot.q;
  24387. return serializationObject;
  24388. };
  24389. var serializeMesh = function (mesh, serializationScene) {
  24390. var serializationObject = {};
  24391. serializationObject.name = mesh.name;
  24392. serializationObject.id = mesh.id;
  24393. if (BABYLON.Tags.HasTags(mesh)) {
  24394. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  24395. }
  24396. serializationObject.position = mesh.position.asArray();
  24397. if (mesh.rotationQuaternion) {
  24398. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  24399. }
  24400. else if (mesh.rotation) {
  24401. serializationObject.rotation = mesh.rotation.asArray();
  24402. }
  24403. serializationObject.scaling = mesh.scaling.asArray();
  24404. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  24405. serializationObject.isEnabled = mesh.isEnabled();
  24406. serializationObject.isVisible = mesh.isVisible;
  24407. serializationObject.infiniteDistance = mesh.infiniteDistance;
  24408. serializationObject.pickable = mesh.isPickable;
  24409. serializationObject.receiveShadows = mesh.receiveShadows;
  24410. serializationObject.billboardMode = mesh.billboardMode;
  24411. serializationObject.visibility = mesh.visibility;
  24412. serializationObject.checkCollisions = mesh.checkCollisions;
  24413. // Parent
  24414. if (mesh.parent) {
  24415. serializationObject.parentId = mesh.parent.id;
  24416. }
  24417. // Geometry
  24418. var geometry = mesh._geometry;
  24419. if (geometry) {
  24420. var geometryId = geometry.id;
  24421. serializationObject.geometryId = geometryId;
  24422. if (!mesh.getScene().getGeometryByID(geometryId)) {
  24423. // 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
  24424. serializeGeometry(geometry, serializationScene.geometries);
  24425. }
  24426. // SubMeshes
  24427. serializationObject.subMeshes = [];
  24428. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24429. var subMesh = mesh.subMeshes[subIndex];
  24430. serializationObject.subMeshes.push({
  24431. materialIndex: subMesh.materialIndex,
  24432. verticesStart: subMesh.verticesStart,
  24433. verticesCount: subMesh.verticesCount,
  24434. indexStart: subMesh.indexStart,
  24435. indexCount: subMesh.indexCount
  24436. });
  24437. }
  24438. }
  24439. // Material
  24440. if (mesh.material) {
  24441. serializationObject.materialId = mesh.material.id;
  24442. }
  24443. else {
  24444. mesh.material = null;
  24445. }
  24446. // Skeleton
  24447. if (mesh.skeleton) {
  24448. serializationObject.skeletonId = mesh.skeleton.id;
  24449. }
  24450. // Physics
  24451. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  24452. serializationObject.physicsMass = mesh.getPhysicsMass();
  24453. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  24454. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  24455. switch (mesh.getPhysicsImpostor()) {
  24456. case BABYLON.PhysicsEngine.BoxImpostor:
  24457. serializationObject.physicsImpostor = 1;
  24458. break;
  24459. case BABYLON.PhysicsEngine.SphereImpostor:
  24460. serializationObject.physicsImpostor = 2;
  24461. break;
  24462. }
  24463. }
  24464. // Instances
  24465. serializationObject.instances = [];
  24466. for (var index = 0; index < mesh.instances.length; index++) {
  24467. var instance = mesh.instances[index];
  24468. var serializationInstance = {
  24469. name: instance.name,
  24470. position: instance.position,
  24471. rotation: instance.rotation,
  24472. rotationQuaternion: instance.rotationQuaternion,
  24473. scaling: instance.scaling
  24474. };
  24475. serializationObject.instances.push(serializationInstance);
  24476. // Animations
  24477. appendAnimations(instance, serializationInstance);
  24478. }
  24479. // Animations
  24480. appendAnimations(mesh, serializationObject);
  24481. // Layer mask
  24482. serializationObject.layerMask = mesh.layerMask;
  24483. return serializationObject;
  24484. };
  24485. var finalizeSingleMesh = function (mesh, serializationObject) {
  24486. //only works if the mesh is already loaded
  24487. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24488. //serialize material
  24489. if (mesh.material) {
  24490. if (mesh.material instanceof BABYLON.StandardMaterial) {
  24491. serializationObject.materials = serializationObject.materials || [];
  24492. if (!serializationObject.materials.some(function (mat) {
  24493. return mat.id == mesh.material.id;
  24494. })) {
  24495. serializationObject.materials.push(serializeMaterial(mesh.material));
  24496. }
  24497. }
  24498. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  24499. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  24500. if (!serializationObject.multiMaterials.some(function (mat) {
  24501. return mat.id == mesh.material.id;
  24502. })) {
  24503. serializationObject.multiMaterials.push(serializeMultiMaterial(mesh.material));
  24504. }
  24505. }
  24506. }
  24507. //serialize geometry
  24508. var geometry = mesh._geometry;
  24509. if (geometry) {
  24510. if (!serializationObject.geometries) {
  24511. serializationObject.geometries = {};
  24512. serializationObject.geometries.boxes = [];
  24513. serializationObject.geometries.spheres = [];
  24514. serializationObject.geometries.cylinders = [];
  24515. serializationObject.geometries.toruses = [];
  24516. serializationObject.geometries.grounds = [];
  24517. serializationObject.geometries.planes = [];
  24518. serializationObject.geometries.torusKnots = [];
  24519. serializationObject.geometries.vertexData = [];
  24520. }
  24521. serializeGeometry(geometry, serializationObject.geometries);
  24522. }
  24523. // Skeletons
  24524. if (mesh.skeleton) {
  24525. serializationObject.skeletons = serializationObject.skeletons || [];
  24526. serializationObject.skeletons.push(serializeSkeleton(mesh.skeleton));
  24527. }
  24528. //serialize the actual mesh
  24529. serializationObject.meshes = serializationObject.meshes || [];
  24530. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24531. }
  24532. };
  24533. var SceneSerializer = (function () {
  24534. function SceneSerializer() {
  24535. }
  24536. SceneSerializer.Serialize = function (scene) {
  24537. var serializationObject = {};
  24538. // Scene
  24539. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  24540. serializationObject.autoClear = scene.autoClear;
  24541. serializationObject.clearColor = scene.clearColor.asArray();
  24542. serializationObject.ambientColor = scene.ambientColor.asArray();
  24543. serializationObject.gravity = scene.gravity.asArray();
  24544. // Fog
  24545. if (scene.fogMode && scene.fogMode !== 0) {
  24546. serializationObject.fogMode = scene.fogMode;
  24547. serializationObject.fogColor = scene.fogColor.asArray();
  24548. serializationObject.fogStart = scene.fogStart;
  24549. serializationObject.fogEnd = scene.fogEnd;
  24550. serializationObject.fogDensity = scene.fogDensity;
  24551. }
  24552. // Lights
  24553. serializationObject.lights = [];
  24554. for (var index = 0; index < scene.lights.length; index++) {
  24555. var light = scene.lights[index];
  24556. serializationObject.lights.push(serializeLight(light));
  24557. }
  24558. // Cameras
  24559. serializationObject.cameras = [];
  24560. for (index = 0; index < scene.cameras.length; index++) {
  24561. var camera = scene.cameras[index];
  24562. serializationObject.cameras.push(serializeCamera(camera));
  24563. }
  24564. if (scene.activeCamera) {
  24565. serializationObject.activeCameraID = scene.activeCamera.id;
  24566. }
  24567. // Materials
  24568. serializationObject.materials = [];
  24569. serializationObject.multiMaterials = [];
  24570. for (index = 0; index < scene.materials.length; index++) {
  24571. var material = scene.materials[index];
  24572. if (material instanceof BABYLON.StandardMaterial) {
  24573. serializationObject.materials.push(serializeMaterial(material));
  24574. }
  24575. else if (material instanceof BABYLON.MultiMaterial) {
  24576. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  24577. }
  24578. }
  24579. // Skeletons
  24580. serializationObject.skeletons = [];
  24581. for (index = 0; index < scene.skeletons.length; index++) {
  24582. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  24583. }
  24584. // Geometries
  24585. serializationObject.geometries = {};
  24586. serializationObject.geometries.boxes = [];
  24587. serializationObject.geometries.spheres = [];
  24588. serializationObject.geometries.cylinders = [];
  24589. serializationObject.geometries.toruses = [];
  24590. serializationObject.geometries.grounds = [];
  24591. serializationObject.geometries.planes = [];
  24592. serializationObject.geometries.torusKnots = [];
  24593. serializationObject.geometries.vertexData = [];
  24594. serializedGeometries = [];
  24595. var geometries = scene.getGeometries();
  24596. for (index = 0; index < geometries.length; index++) {
  24597. var geometry = geometries[index];
  24598. if (geometry.isReady()) {
  24599. serializeGeometry(geometry, serializationObject.geometries);
  24600. }
  24601. }
  24602. // Meshes
  24603. serializationObject.meshes = [];
  24604. for (index = 0; index < scene.meshes.length; index++) {
  24605. var abstractMesh = scene.meshes[index];
  24606. if (abstractMesh instanceof BABYLON.Mesh) {
  24607. var mesh = abstractMesh;
  24608. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  24609. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  24610. }
  24611. }
  24612. }
  24613. // Particles Systems
  24614. serializationObject.particleSystems = [];
  24615. for (index = 0; index < scene.particleSystems.length; index++) {
  24616. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  24617. }
  24618. // Lens flares
  24619. serializationObject.lensFlareSystems = [];
  24620. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  24621. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  24622. }
  24623. // Shadows
  24624. serializationObject.shadowGenerators = [];
  24625. for (index = 0; index < scene.lights.length; index++) {
  24626. light = scene.lights[index];
  24627. if (light.getShadowGenerator()) {
  24628. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  24629. }
  24630. }
  24631. return serializationObject;
  24632. };
  24633. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  24634. if (withParents === void 0) { withParents = false; }
  24635. if (withChildren === void 0) { withChildren = false; }
  24636. var serializationObject = {};
  24637. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  24638. if (withParents || withChildren) {
  24639. //deliberate for loop! not for each, appended should be processed as well.
  24640. for (var i = 0; i < toSerialize.length; ++i) {
  24641. if (withChildren) {
  24642. toSerialize[i].getDescendants().forEach(function (node) {
  24643. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  24644. toSerialize.push(node);
  24645. }
  24646. });
  24647. }
  24648. //make sure the array doesn't contain the object already
  24649. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  24650. toSerialize.push(toSerialize[i].parent);
  24651. }
  24652. }
  24653. }
  24654. toSerialize.forEach(function (mesh) {
  24655. finalizeSingleMesh(mesh, serializationObject);
  24656. });
  24657. return serializationObject;
  24658. };
  24659. return SceneSerializer;
  24660. })();
  24661. BABYLON.SceneSerializer = SceneSerializer;
  24662. })(BABYLON || (BABYLON = {}));
  24663. var BABYLON;
  24664. (function (BABYLON) {
  24665. // Unique ID when we import meshes from Babylon to CSG
  24666. var currentCSGMeshId = 0;
  24667. // # class Vertex
  24668. // Represents a vertex of a polygon. Use your own vertex class instead of this
  24669. // one to provide additional features like texture coordinates and vertex
  24670. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  24671. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  24672. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  24673. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  24674. // is not used anywhere else.
  24675. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  24676. var Vertex = (function () {
  24677. function Vertex(pos, normal, uv) {
  24678. this.pos = pos;
  24679. this.normal = normal;
  24680. this.uv = uv;
  24681. }
  24682. Vertex.prototype.clone = function () {
  24683. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  24684. };
  24685. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  24686. // orientation of a polygon is flipped.
  24687. Vertex.prototype.flip = function () {
  24688. this.normal = this.normal.scale(-1);
  24689. };
  24690. // Create a new vertex between this vertex and `other` by linearly
  24691. // interpolating all properties using a parameter of `t`. Subclasses should
  24692. // override this to interpolate additional properties.
  24693. Vertex.prototype.interpolate = function (other, t) {
  24694. 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));
  24695. };
  24696. return Vertex;
  24697. })();
  24698. // # class Plane
  24699. // Represents a plane in 3D space.
  24700. var Plane = (function () {
  24701. function Plane(normal, w) {
  24702. this.normal = normal;
  24703. this.w = w;
  24704. }
  24705. Plane.FromPoints = function (a, b, c) {
  24706. var v0 = c.subtract(a);
  24707. var v1 = b.subtract(a);
  24708. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  24709. return null;
  24710. }
  24711. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  24712. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  24713. };
  24714. Plane.prototype.clone = function () {
  24715. return new Plane(this.normal.clone(), this.w);
  24716. };
  24717. Plane.prototype.flip = function () {
  24718. this.normal.scaleInPlace(-1);
  24719. this.w = -this.w;
  24720. };
  24721. // Split `polygon` by this plane if needed, then put the polygon or polygon
  24722. // fragments in the appropriate lists. Coplanar polygons go into either
  24723. // `coplanarFront` or `coplanarBack` depending on their orientation with
  24724. // respect to this plane. Polygons in front or in back of this plane go into
  24725. // either `front` or `back`.
  24726. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  24727. var COPLANAR = 0;
  24728. var FRONT = 1;
  24729. var BACK = 2;
  24730. var SPANNING = 3;
  24731. // Classify each point as well as the entire polygon into one of the above
  24732. // four classes.
  24733. var polygonType = 0;
  24734. var types = [];
  24735. for (var i = 0; i < polygon.vertices.length; i++) {
  24736. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  24737. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  24738. polygonType |= type;
  24739. types.push(type);
  24740. }
  24741. // Put the polygon in the correct list, splitting it when necessary.
  24742. switch (polygonType) {
  24743. case COPLANAR:
  24744. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  24745. break;
  24746. case FRONT:
  24747. front.push(polygon);
  24748. break;
  24749. case BACK:
  24750. back.push(polygon);
  24751. break;
  24752. case SPANNING:
  24753. var f = [], b = [];
  24754. for (i = 0; i < polygon.vertices.length; i++) {
  24755. var j = (i + 1) % polygon.vertices.length;
  24756. var ti = types[i], tj = types[j];
  24757. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  24758. if (ti != BACK)
  24759. f.push(vi);
  24760. if (ti != FRONT)
  24761. b.push(ti != BACK ? vi.clone() : vi);
  24762. if ((ti | tj) == SPANNING) {
  24763. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  24764. var v = vi.interpolate(vj, t);
  24765. f.push(v);
  24766. b.push(v.clone());
  24767. }
  24768. }
  24769. if (f.length >= 3) {
  24770. var poly = new Polygon(f, polygon.shared);
  24771. if (poly.plane)
  24772. front.push(poly);
  24773. }
  24774. if (b.length >= 3) {
  24775. poly = new Polygon(b, polygon.shared);
  24776. if (poly.plane)
  24777. back.push(poly);
  24778. }
  24779. break;
  24780. }
  24781. };
  24782. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  24783. // point is on the plane.
  24784. Plane.EPSILON = 1e-5;
  24785. return Plane;
  24786. })();
  24787. // # class Polygon
  24788. // Represents a convex polygon. The vertices used to initialize a polygon must
  24789. // be coplanar and form a convex loop.
  24790. //
  24791. // Each convex polygon has a `shared` property, which is shared between all
  24792. // polygons that are clones of each other or were split from the same polygon.
  24793. // This can be used to define per-polygon properties (such as surface color).
  24794. var Polygon = (function () {
  24795. function Polygon(vertices, shared) {
  24796. this.vertices = vertices;
  24797. this.shared = shared;
  24798. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  24799. }
  24800. Polygon.prototype.clone = function () {
  24801. var vertices = this.vertices.map(function (v) { return v.clone(); });
  24802. return new Polygon(vertices, this.shared);
  24803. };
  24804. Polygon.prototype.flip = function () {
  24805. this.vertices.reverse().map(function (v) { v.flip(); });
  24806. this.plane.flip();
  24807. };
  24808. return Polygon;
  24809. })();
  24810. // # class Node
  24811. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  24812. // by picking a polygon to split along. That polygon (and all other coplanar
  24813. // polygons) are added directly to that node and the other polygons are added to
  24814. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  24815. // no distinction between internal and leaf nodes.
  24816. var Node = (function () {
  24817. function Node(polygons) {
  24818. this.plane = null;
  24819. this.front = null;
  24820. this.back = null;
  24821. this.polygons = [];
  24822. if (polygons) {
  24823. this.build(polygons);
  24824. }
  24825. }
  24826. Node.prototype.clone = function () {
  24827. var node = new Node();
  24828. node.plane = this.plane && this.plane.clone();
  24829. node.front = this.front && this.front.clone();
  24830. node.back = this.back && this.back.clone();
  24831. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  24832. return node;
  24833. };
  24834. // Convert solid space to empty space and empty space to solid space.
  24835. Node.prototype.invert = function () {
  24836. for (var i = 0; i < this.polygons.length; i++) {
  24837. this.polygons[i].flip();
  24838. }
  24839. if (this.plane) {
  24840. this.plane.flip();
  24841. }
  24842. if (this.front) {
  24843. this.front.invert();
  24844. }
  24845. if (this.back) {
  24846. this.back.invert();
  24847. }
  24848. var temp = this.front;
  24849. this.front = this.back;
  24850. this.back = temp;
  24851. };
  24852. // Recursively remove all polygons in `polygons` that are inside this BSP
  24853. // tree.
  24854. Node.prototype.clipPolygons = function (polygons) {
  24855. if (!this.plane)
  24856. return polygons.slice();
  24857. var front = [], back = [];
  24858. for (var i = 0; i < polygons.length; i++) {
  24859. this.plane.splitPolygon(polygons[i], front, back, front, back);
  24860. }
  24861. if (this.front) {
  24862. front = this.front.clipPolygons(front);
  24863. }
  24864. if (this.back) {
  24865. back = this.back.clipPolygons(back);
  24866. }
  24867. else {
  24868. back = [];
  24869. }
  24870. return front.concat(back);
  24871. };
  24872. // Remove all polygons in this BSP tree that are inside the other BSP tree
  24873. // `bsp`.
  24874. Node.prototype.clipTo = function (bsp) {
  24875. this.polygons = bsp.clipPolygons(this.polygons);
  24876. if (this.front)
  24877. this.front.clipTo(bsp);
  24878. if (this.back)
  24879. this.back.clipTo(bsp);
  24880. };
  24881. // Return a list of all polygons in this BSP tree.
  24882. Node.prototype.allPolygons = function () {
  24883. var polygons = this.polygons.slice();
  24884. if (this.front)
  24885. polygons = polygons.concat(this.front.allPolygons());
  24886. if (this.back)
  24887. polygons = polygons.concat(this.back.allPolygons());
  24888. return polygons;
  24889. };
  24890. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  24891. // new polygons are filtered down to the bottom of the tree and become new
  24892. // nodes there. Each set of polygons is partitioned using the first polygon
  24893. // (no heuristic is used to pick a good split).
  24894. Node.prototype.build = function (polygons) {
  24895. if (!polygons.length)
  24896. return;
  24897. if (!this.plane)
  24898. this.plane = polygons[0].plane.clone();
  24899. var front = [], back = [];
  24900. for (var i = 0; i < polygons.length; i++) {
  24901. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  24902. }
  24903. if (front.length) {
  24904. if (!this.front)
  24905. this.front = new Node();
  24906. this.front.build(front);
  24907. }
  24908. if (back.length) {
  24909. if (!this.back)
  24910. this.back = new Node();
  24911. this.back.build(back);
  24912. }
  24913. };
  24914. return Node;
  24915. })();
  24916. var CSG = (function () {
  24917. function CSG() {
  24918. this.polygons = new Array();
  24919. }
  24920. // Convert BABYLON.Mesh to BABYLON.CSG
  24921. CSG.FromMesh = function (mesh) {
  24922. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  24923. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  24924. if (mesh instanceof BABYLON.Mesh) {
  24925. mesh.computeWorldMatrix(true);
  24926. matrix = mesh.getWorldMatrix();
  24927. meshPosition = mesh.position.clone();
  24928. meshRotation = mesh.rotation.clone();
  24929. if (mesh.rotationQuaternion) {
  24930. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  24931. }
  24932. meshScaling = mesh.scaling.clone();
  24933. }
  24934. else {
  24935. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  24936. }
  24937. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  24938. var subMeshes = mesh.subMeshes;
  24939. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  24940. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  24941. vertices = [];
  24942. for (var j = 0; j < 3; j++) {
  24943. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  24944. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  24945. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  24946. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  24947. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  24948. vertex = new Vertex(position, normal, uv);
  24949. vertices.push(vertex);
  24950. }
  24951. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  24952. // To handle the case of degenerated triangle
  24953. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  24954. if (polygon.plane)
  24955. polygons.push(polygon);
  24956. }
  24957. }
  24958. var csg = CSG.FromPolygons(polygons);
  24959. csg.matrix = matrix;
  24960. csg.position = meshPosition;
  24961. csg.rotation = meshRotation;
  24962. csg.scaling = meshScaling;
  24963. csg.rotationQuaternion = meshRotationQuaternion;
  24964. currentCSGMeshId++;
  24965. return csg;
  24966. };
  24967. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  24968. CSG.FromPolygons = function (polygons) {
  24969. var csg = new CSG();
  24970. csg.polygons = polygons;
  24971. return csg;
  24972. };
  24973. CSG.prototype.clone = function () {
  24974. var csg = new CSG();
  24975. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  24976. csg.copyTransformAttributes(this);
  24977. return csg;
  24978. };
  24979. CSG.prototype.toPolygons = function () {
  24980. return this.polygons;
  24981. };
  24982. CSG.prototype.union = function (csg) {
  24983. var a = new Node(this.clone().polygons);
  24984. var b = new Node(csg.clone().polygons);
  24985. a.clipTo(b);
  24986. b.clipTo(a);
  24987. b.invert();
  24988. b.clipTo(a);
  24989. b.invert();
  24990. a.build(b.allPolygons());
  24991. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24992. };
  24993. CSG.prototype.unionInPlace = function (csg) {
  24994. var a = new Node(this.polygons);
  24995. var b = new Node(csg.polygons);
  24996. a.clipTo(b);
  24997. b.clipTo(a);
  24998. b.invert();
  24999. b.clipTo(a);
  25000. b.invert();
  25001. a.build(b.allPolygons());
  25002. this.polygons = a.allPolygons();
  25003. };
  25004. CSG.prototype.subtract = function (csg) {
  25005. var a = new Node(this.clone().polygons);
  25006. var b = new Node(csg.clone().polygons);
  25007. a.invert();
  25008. a.clipTo(b);
  25009. b.clipTo(a);
  25010. b.invert();
  25011. b.clipTo(a);
  25012. b.invert();
  25013. a.build(b.allPolygons());
  25014. a.invert();
  25015. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25016. };
  25017. CSG.prototype.subtractInPlace = function (csg) {
  25018. var a = new Node(this.polygons);
  25019. var b = new Node(csg.polygons);
  25020. a.invert();
  25021. a.clipTo(b);
  25022. b.clipTo(a);
  25023. b.invert();
  25024. b.clipTo(a);
  25025. b.invert();
  25026. a.build(b.allPolygons());
  25027. a.invert();
  25028. this.polygons = a.allPolygons();
  25029. };
  25030. CSG.prototype.intersect = function (csg) {
  25031. var a = new Node(this.clone().polygons);
  25032. var b = new Node(csg.clone().polygons);
  25033. a.invert();
  25034. b.clipTo(a);
  25035. b.invert();
  25036. a.clipTo(b);
  25037. b.clipTo(a);
  25038. a.build(b.allPolygons());
  25039. a.invert();
  25040. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  25041. };
  25042. CSG.prototype.intersectInPlace = function (csg) {
  25043. var a = new Node(this.polygons);
  25044. var b = new Node(csg.polygons);
  25045. a.invert();
  25046. b.clipTo(a);
  25047. b.invert();
  25048. a.clipTo(b);
  25049. b.clipTo(a);
  25050. a.build(b.allPolygons());
  25051. a.invert();
  25052. this.polygons = a.allPolygons();
  25053. };
  25054. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  25055. // not modified.
  25056. CSG.prototype.inverse = function () {
  25057. var csg = this.clone();
  25058. csg.inverseInPlace();
  25059. return csg;
  25060. };
  25061. CSG.prototype.inverseInPlace = function () {
  25062. this.polygons.map(function (p) { p.flip(); });
  25063. };
  25064. // This is used to keep meshes transformations so they can be restored
  25065. // when we build back a Babylon Mesh
  25066. // NB : All CSG operations are performed in world coordinates
  25067. CSG.prototype.copyTransformAttributes = function (csg) {
  25068. this.matrix = csg.matrix;
  25069. this.position = csg.position;
  25070. this.rotation = csg.rotation;
  25071. this.scaling = csg.scaling;
  25072. this.rotationQuaternion = csg.rotationQuaternion;
  25073. return this;
  25074. };
  25075. // Build Raw mesh from CSG
  25076. // Coordinates here are in world space
  25077. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  25078. var matrix = this.matrix.clone();
  25079. matrix.invert();
  25080. 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;
  25081. if (keepSubMeshes) {
  25082. // Sort Polygons, since subMeshes are indices range
  25083. polygons.sort(function (a, b) {
  25084. if (a.shared.meshId === b.shared.meshId) {
  25085. return a.shared.subMeshId - b.shared.subMeshId;
  25086. }
  25087. else {
  25088. return a.shared.meshId - b.shared.meshId;
  25089. }
  25090. });
  25091. }
  25092. for (var i = 0, il = polygons.length; i < il; i++) {
  25093. polygon = polygons[i];
  25094. // Building SubMeshes
  25095. if (!subMesh_dict[polygon.shared.meshId]) {
  25096. subMesh_dict[polygon.shared.meshId] = {};
  25097. }
  25098. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  25099. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  25100. indexStart: +Infinity,
  25101. indexEnd: -Infinity,
  25102. materialIndex: polygon.shared.materialIndex
  25103. };
  25104. }
  25105. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  25106. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  25107. polygonIndices[0] = 0;
  25108. polygonIndices[1] = j - 1;
  25109. polygonIndices[2] = j;
  25110. for (var k = 0; k < 3; k++) {
  25111. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  25112. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  25113. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  25114. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  25115. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  25116. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  25117. // Check if 2 points can be merged
  25118. if (!(typeof vertex_idx !== 'undefined' &&
  25119. normals[vertex_idx * 3] === localNormal.x &&
  25120. normals[vertex_idx * 3 + 1] === localNormal.y &&
  25121. normals[vertex_idx * 3 + 2] === localNormal.z &&
  25122. uvs[vertex_idx * 2] === uv.x &&
  25123. uvs[vertex_idx * 2 + 1] === uv.y)) {
  25124. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  25125. uvs.push(uv.x, uv.y);
  25126. normals.push(normal.x, normal.y, normal.z);
  25127. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  25128. }
  25129. indices.push(vertex_idx);
  25130. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  25131. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  25132. currentIndex++;
  25133. }
  25134. }
  25135. }
  25136. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  25137. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25138. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  25139. mesh.setIndices(indices);
  25140. if (keepSubMeshes) {
  25141. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  25142. var materialIndexOffset = 0, materialMaxIndex;
  25143. mesh.subMeshes.length = 0;
  25144. for (var m in subMesh_dict) {
  25145. materialMaxIndex = -1;
  25146. for (var sm in subMesh_dict[m]) {
  25147. subMesh_obj = subMesh_dict[m][sm];
  25148. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  25149. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  25150. }
  25151. materialIndexOffset += ++materialMaxIndex;
  25152. }
  25153. }
  25154. return mesh;
  25155. };
  25156. // Build Mesh from CSG taking material and transforms into account
  25157. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  25158. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  25159. mesh.material = material;
  25160. mesh.position.copyFrom(this.position);
  25161. mesh.rotation.copyFrom(this.rotation);
  25162. if (this.rotationQuaternion) {
  25163. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  25164. }
  25165. mesh.scaling.copyFrom(this.scaling);
  25166. mesh.computeWorldMatrix(true);
  25167. return mesh;
  25168. };
  25169. return CSG;
  25170. })();
  25171. BABYLON.CSG = CSG;
  25172. })(BABYLON || (BABYLON = {}));
  25173. var BABYLON;
  25174. (function (BABYLON) {
  25175. var VRDistortionCorrectionPostProcess = (function (_super) {
  25176. __extends(VRDistortionCorrectionPostProcess, _super);
  25177. //ANY
  25178. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  25179. var _this = this;
  25180. _super.call(this, name, "vrDistortionCorrection", [
  25181. 'LensCenter',
  25182. 'Scale',
  25183. 'ScaleIn',
  25184. 'HmdWarpParam'
  25185. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  25186. this._isRightEye = isRightEye;
  25187. this._distortionFactors = vrMetrics.distortionK;
  25188. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  25189. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  25190. this.onSizeChanged = function () {
  25191. _this.aspectRatio = _this.width * .5 / _this.height;
  25192. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  25193. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  25194. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  25195. };
  25196. this.onApply = function (effect) {
  25197. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  25198. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  25199. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  25200. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  25201. };
  25202. }
  25203. return VRDistortionCorrectionPostProcess;
  25204. })(BABYLON.PostProcess);
  25205. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  25206. })(BABYLON || (BABYLON = {}));
  25207. // Mainly based on these 2 articles :
  25208. // 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
  25209. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  25210. var BABYLON;
  25211. (function (BABYLON) {
  25212. (function (JoystickAxis) {
  25213. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  25214. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  25215. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  25216. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  25217. var JoystickAxis = BABYLON.JoystickAxis;
  25218. var VirtualJoystick = (function () {
  25219. function VirtualJoystick(leftJoystick) {
  25220. var _this = this;
  25221. if (leftJoystick) {
  25222. this._leftJoystick = true;
  25223. }
  25224. else {
  25225. this._leftJoystick = false;
  25226. }
  25227. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  25228. VirtualJoystick._globalJoystickIndex++;
  25229. // By default left & right arrow keys are moving the X
  25230. // and up & down keys are moving the Y
  25231. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25232. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25233. this.reverseLeftRight = false;
  25234. this.reverseUpDown = false;
  25235. // collections of pointers
  25236. this._touches = new BABYLON.SmartCollection();
  25237. this.deltaPosition = BABYLON.Vector3.Zero();
  25238. this._joystickSensibility = 25;
  25239. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25240. this._rotationSpeed = 25;
  25241. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  25242. this._rotateOnAxisRelativeToMesh = false;
  25243. this._onResize = function (evt) {
  25244. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25245. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25246. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  25247. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  25248. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  25249. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  25250. };
  25251. // injecting a canvas element on top of the canvas 3D game
  25252. if (!VirtualJoystick.vjCanvas) {
  25253. window.addEventListener("resize", this._onResize, false);
  25254. VirtualJoystick.vjCanvas = document.createElement("canvas");
  25255. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  25256. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  25257. VirtualJoystick.vjCanvas.width = window.innerWidth;
  25258. VirtualJoystick.vjCanvas.height = window.innerHeight;
  25259. VirtualJoystick.vjCanvas.style.width = "100%";
  25260. VirtualJoystick.vjCanvas.style.height = "100%";
  25261. VirtualJoystick.vjCanvas.style.position = "absolute";
  25262. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  25263. VirtualJoystick.vjCanvas.style.top = "0px";
  25264. VirtualJoystick.vjCanvas.style.left = "0px";
  25265. VirtualJoystick.vjCanvas.style.zIndex = "5";
  25266. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  25267. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  25268. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  25269. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25270. document.body.appendChild(VirtualJoystick.vjCanvas);
  25271. }
  25272. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  25273. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  25274. this.pressed = false;
  25275. // default joystick color
  25276. this._joystickColor = "cyan";
  25277. this._joystickPointerID = -1;
  25278. // current joystick position
  25279. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  25280. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  25281. // origin joystick position
  25282. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  25283. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  25284. this._onPointerDownHandlerRef = function (evt) {
  25285. _this._onPointerDown(evt);
  25286. };
  25287. this._onPointerMoveHandlerRef = function (evt) {
  25288. _this._onPointerMove(evt);
  25289. };
  25290. this._onPointerOutHandlerRef = function (evt) {
  25291. _this._onPointerUp(evt);
  25292. };
  25293. this._onPointerUpHandlerRef = function (evt) {
  25294. _this._onPointerUp(evt);
  25295. };
  25296. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  25297. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  25298. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  25299. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  25300. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  25301. evt.preventDefault(); // Disables system menu
  25302. }, false);
  25303. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25304. }
  25305. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  25306. this._joystickSensibility = newJoystickSensibility;
  25307. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  25308. };
  25309. VirtualJoystick.prototype._onPointerDown = function (e) {
  25310. var positionOnScreenCondition;
  25311. e.preventDefault();
  25312. if (this._leftJoystick === true) {
  25313. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  25314. }
  25315. else {
  25316. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  25317. }
  25318. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  25319. // First contact will be dedicated to the virtual joystick
  25320. this._joystickPointerID = e.pointerId;
  25321. this._joystickPointerStartPos.x = e.clientX;
  25322. this._joystickPointerStartPos.y = e.clientY;
  25323. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  25324. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  25325. this._deltaJoystickVector.x = 0;
  25326. this._deltaJoystickVector.y = 0;
  25327. this.pressed = true;
  25328. this._touches.add(e.pointerId.toString(), e);
  25329. }
  25330. else {
  25331. // You can only trigger the action buttons with a joystick declared
  25332. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  25333. this._action();
  25334. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  25335. }
  25336. }
  25337. };
  25338. VirtualJoystick.prototype._onPointerMove = function (e) {
  25339. // If the current pointer is the one associated to the joystick (first touch contact)
  25340. if (this._joystickPointerID == e.pointerId) {
  25341. this._joystickPointerPos.x = e.clientX;
  25342. this._joystickPointerPos.y = e.clientY;
  25343. this._deltaJoystickVector = this._joystickPointerPos.clone();
  25344. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  25345. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  25346. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  25347. switch (this._axisTargetedByLeftAndRight) {
  25348. case JoystickAxis.X:
  25349. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  25350. break;
  25351. case JoystickAxis.Y:
  25352. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  25353. break;
  25354. case JoystickAxis.Z:
  25355. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  25356. break;
  25357. }
  25358. var directionUpDown = this.reverseUpDown ? 1 : -1;
  25359. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  25360. switch (this._axisTargetedByUpAndDown) {
  25361. case JoystickAxis.X:
  25362. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  25363. break;
  25364. case JoystickAxis.Y:
  25365. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  25366. break;
  25367. case JoystickAxis.Z:
  25368. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  25369. break;
  25370. }
  25371. }
  25372. else {
  25373. if (this._touches.item(e.pointerId.toString())) {
  25374. this._touches.item(e.pointerId.toString()).x = e.clientX;
  25375. this._touches.item(e.pointerId.toString()).y = e.clientY;
  25376. }
  25377. }
  25378. };
  25379. VirtualJoystick.prototype._onPointerUp = function (e) {
  25380. if (this._joystickPointerID == e.pointerId) {
  25381. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  25382. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  25383. this._joystickPointerID = -1;
  25384. this.pressed = false;
  25385. }
  25386. else {
  25387. var touch = this._touches.item(e.pointerId.toString());
  25388. if (touch) {
  25389. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25390. }
  25391. }
  25392. this._deltaJoystickVector.x = 0;
  25393. this._deltaJoystickVector.y = 0;
  25394. this._touches.remove(e.pointerId.toString());
  25395. };
  25396. /**
  25397. * Change the color of the virtual joystick
  25398. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  25399. */
  25400. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  25401. this._joystickColor = newColor;
  25402. };
  25403. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  25404. this._action = action;
  25405. };
  25406. // Define which axis you'd like to control for left & right
  25407. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  25408. switch (axis) {
  25409. case JoystickAxis.X:
  25410. case JoystickAxis.Y:
  25411. case JoystickAxis.Z:
  25412. this._axisTargetedByLeftAndRight = axis;
  25413. break;
  25414. default:
  25415. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  25416. break;
  25417. }
  25418. };
  25419. // Define which axis you'd like to control for up & down
  25420. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  25421. switch (axis) {
  25422. case JoystickAxis.X:
  25423. case JoystickAxis.Y:
  25424. case JoystickAxis.Z:
  25425. this._axisTargetedByUpAndDown = axis;
  25426. break;
  25427. default:
  25428. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  25429. break;
  25430. }
  25431. };
  25432. VirtualJoystick.prototype._clearCanvas = function () {
  25433. if (this._leftJoystick) {
  25434. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  25435. }
  25436. else {
  25437. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  25438. }
  25439. };
  25440. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  25441. var _this = this;
  25442. if (this.pressed) {
  25443. this._touches.forEach(function (touch) {
  25444. if (touch.pointerId === _this._joystickPointerID) {
  25445. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  25446. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  25447. VirtualJoystick.vjCanvasContext.beginPath();
  25448. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25449. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25450. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  25451. VirtualJoystick.vjCanvasContext.stroke();
  25452. VirtualJoystick.vjCanvasContext.closePath();
  25453. VirtualJoystick.vjCanvasContext.beginPath();
  25454. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25455. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  25456. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  25457. VirtualJoystick.vjCanvasContext.stroke();
  25458. VirtualJoystick.vjCanvasContext.closePath();
  25459. VirtualJoystick.vjCanvasContext.beginPath();
  25460. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  25461. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  25462. VirtualJoystick.vjCanvasContext.stroke();
  25463. VirtualJoystick.vjCanvasContext.closePath();
  25464. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  25465. }
  25466. else {
  25467. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  25468. VirtualJoystick.vjCanvasContext.beginPath();
  25469. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  25470. VirtualJoystick.vjCanvasContext.beginPath();
  25471. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  25472. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  25473. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  25474. VirtualJoystick.vjCanvasContext.stroke();
  25475. VirtualJoystick.vjCanvasContext.closePath();
  25476. touch.prevX = touch.x;
  25477. touch.prevY = touch.y;
  25478. }
  25479. ;
  25480. });
  25481. }
  25482. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  25483. };
  25484. VirtualJoystick.prototype.releaseCanvas = function () {
  25485. if (VirtualJoystick.vjCanvas) {
  25486. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  25487. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  25488. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  25489. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  25490. window.removeEventListener("resize", this._onResize);
  25491. document.body.removeChild(VirtualJoystick.vjCanvas);
  25492. VirtualJoystick.vjCanvas = null;
  25493. }
  25494. };
  25495. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  25496. VirtualJoystick._globalJoystickIndex = 0;
  25497. return VirtualJoystick;
  25498. })();
  25499. BABYLON.VirtualJoystick = VirtualJoystick;
  25500. })(BABYLON || (BABYLON = {}));
  25501. var BABYLON;
  25502. (function (BABYLON) {
  25503. // We're mainly based on the logic defined into the FreeCamera code
  25504. var VirtualJoysticksCamera = (function (_super) {
  25505. __extends(VirtualJoysticksCamera, _super);
  25506. function VirtualJoysticksCamera(name, position, scene) {
  25507. _super.call(this, name, position, scene);
  25508. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  25509. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  25510. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  25511. this._leftjoystick.setJoystickSensibility(0.15);
  25512. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  25513. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  25514. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  25515. this._rightjoystick.reverseUpDown = true;
  25516. this._rightjoystick.setJoystickSensibility(0.05);
  25517. this._rightjoystick.setJoystickColor("yellow");
  25518. }
  25519. VirtualJoysticksCamera.prototype.getLeftJoystick = function () {
  25520. return this._leftjoystick;
  25521. };
  25522. VirtualJoysticksCamera.prototype.getRightJoystick = function () {
  25523. return this._rightjoystick;
  25524. };
  25525. VirtualJoysticksCamera.prototype._checkInputs = function () {
  25526. var speed = this._computeLocalCameraSpeed() * 50;
  25527. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25528. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  25529. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25530. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  25531. if (!this._leftjoystick.pressed) {
  25532. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  25533. }
  25534. if (!this._rightjoystick.pressed) {
  25535. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  25536. }
  25537. _super.prototype._checkInputs.call(this);
  25538. };
  25539. VirtualJoysticksCamera.prototype.dispose = function () {
  25540. this._leftjoystick.releaseCanvas();
  25541. _super.prototype.dispose.call(this);
  25542. };
  25543. return VirtualJoysticksCamera;
  25544. })(BABYLON.FreeCamera);
  25545. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  25546. })(BABYLON || (BABYLON = {}));
  25547. var BABYLON;
  25548. (function (BABYLON) {
  25549. var ShaderMaterial = (function (_super) {
  25550. __extends(ShaderMaterial, _super);
  25551. function ShaderMaterial(name, scene, shaderPath, options) {
  25552. _super.call(this, name, scene);
  25553. this._textures = new Array();
  25554. this._floats = new Array();
  25555. this._floatsArrays = {};
  25556. this._colors3 = new Array();
  25557. this._colors4 = new Array();
  25558. this._vectors2 = new Array();
  25559. this._vectors3 = new Array();
  25560. this._vectors4 = new Array();
  25561. this._matrices = new Array();
  25562. this._matrices3x3 = new Array();
  25563. this._matrices2x2 = new Array();
  25564. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  25565. this._shaderPath = shaderPath;
  25566. options.needAlphaBlending = options.needAlphaBlending || false;
  25567. options.needAlphaTesting = options.needAlphaTesting || false;
  25568. options.attributes = options.attributes || ["position", "normal", "uv"];
  25569. options.uniforms = options.uniforms || ["worldViewProjection"];
  25570. options.samplers = options.samplers || [];
  25571. options.defines = options.defines || [];
  25572. this._options = options;
  25573. }
  25574. ShaderMaterial.prototype.needAlphaBlending = function () {
  25575. return this._options.needAlphaBlending;
  25576. };
  25577. ShaderMaterial.prototype.needAlphaTesting = function () {
  25578. return this._options.needAlphaTesting;
  25579. };
  25580. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  25581. if (this._options.uniforms.indexOf(uniformName) === -1) {
  25582. this._options.uniforms.push(uniformName);
  25583. }
  25584. };
  25585. ShaderMaterial.prototype.setTexture = function (name, texture) {
  25586. if (this._options.samplers.indexOf(name) === -1) {
  25587. this._options.samplers.push(name);
  25588. }
  25589. this._textures[name] = texture;
  25590. return this;
  25591. };
  25592. ShaderMaterial.prototype.setFloat = function (name, value) {
  25593. this._checkUniform(name);
  25594. this._floats[name] = value;
  25595. return this;
  25596. };
  25597. ShaderMaterial.prototype.setFloats = function (name, value) {
  25598. this._checkUniform(name);
  25599. this._floatsArrays[name] = value;
  25600. return this;
  25601. };
  25602. ShaderMaterial.prototype.setColor3 = function (name, value) {
  25603. this._checkUniform(name);
  25604. this._colors3[name] = value;
  25605. return this;
  25606. };
  25607. ShaderMaterial.prototype.setColor4 = function (name, value) {
  25608. this._checkUniform(name);
  25609. this._colors4[name] = value;
  25610. return this;
  25611. };
  25612. ShaderMaterial.prototype.setVector2 = function (name, value) {
  25613. this._checkUniform(name);
  25614. this._vectors2[name] = value;
  25615. return this;
  25616. };
  25617. ShaderMaterial.prototype.setVector3 = function (name, value) {
  25618. this._checkUniform(name);
  25619. this._vectors3[name] = value;
  25620. return this;
  25621. };
  25622. ShaderMaterial.prototype.setVector4 = function (name, value) {
  25623. this._checkUniform(name);
  25624. this._vectors4[name] = value;
  25625. return this;
  25626. };
  25627. ShaderMaterial.prototype.setMatrix = function (name, value) {
  25628. this._checkUniform(name);
  25629. this._matrices[name] = value;
  25630. return this;
  25631. };
  25632. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  25633. this._checkUniform(name);
  25634. this._matrices3x3[name] = value;
  25635. return this;
  25636. };
  25637. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  25638. this._checkUniform(name);
  25639. this._matrices2x2[name] = value;
  25640. return this;
  25641. };
  25642. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  25643. var scene = this.getScene();
  25644. var engine = scene.getEngine();
  25645. if (!this.checkReadyOnEveryCall) {
  25646. if (this._renderId === scene.getRenderId()) {
  25647. return true;
  25648. }
  25649. }
  25650. // Instances
  25651. var defines = [];
  25652. var fallbacks = new BABYLON.EffectFallbacks();
  25653. if (useInstances) {
  25654. defines.push("#define INSTANCES");
  25655. }
  25656. for (var index = 0; index < this._options.defines.length; index++) {
  25657. defines.push(this._options.defines[index]);
  25658. }
  25659. // Bones
  25660. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25661. defines.push("#define BONES");
  25662. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25663. defines.push("#define BONES4");
  25664. fallbacks.addFallback(0, "BONES4");
  25665. }
  25666. // Alpha test
  25667. if (engine.getAlphaTesting()) {
  25668. defines.push("#define ALPHATEST");
  25669. }
  25670. var previousEffect = this._effect;
  25671. var join = defines.join("\n");
  25672. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  25673. if (!this._effect.isReady()) {
  25674. return false;
  25675. }
  25676. if (previousEffect !== this._effect) {
  25677. scene.resetCachedMaterial();
  25678. }
  25679. this._renderId = scene.getRenderId();
  25680. return true;
  25681. };
  25682. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25683. var scene = this.getScene();
  25684. if (this._options.uniforms.indexOf("world") !== -1) {
  25685. this._effect.setMatrix("world", world);
  25686. }
  25687. if (this._options.uniforms.indexOf("worldView") !== -1) {
  25688. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  25689. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  25690. }
  25691. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  25692. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  25693. }
  25694. };
  25695. ShaderMaterial.prototype.bind = function (world, mesh) {
  25696. // Std values
  25697. this.bindOnlyWorldMatrix(world);
  25698. if (this.getScene().getCachedMaterial() !== this) {
  25699. if (this._options.uniforms.indexOf("view") !== -1) {
  25700. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  25701. }
  25702. if (this._options.uniforms.indexOf("projection") !== -1) {
  25703. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  25704. }
  25705. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  25706. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25707. }
  25708. // Bones
  25709. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25710. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25711. }
  25712. // Texture
  25713. for (var name in this._textures) {
  25714. this._effect.setTexture(name, this._textures[name]);
  25715. }
  25716. // Float
  25717. for (name in this._floats) {
  25718. this._effect.setFloat(name, this._floats[name]);
  25719. }
  25720. // Float s
  25721. for (name in this._floatsArrays) {
  25722. this._effect.setArray(name, this._floatsArrays[name]);
  25723. }
  25724. // Color3
  25725. for (name in this._colors3) {
  25726. this._effect.setColor3(name, this._colors3[name]);
  25727. }
  25728. // Color4
  25729. for (name in this._colors4) {
  25730. var color = this._colors4[name];
  25731. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25732. }
  25733. // Vector2
  25734. for (name in this._vectors2) {
  25735. this._effect.setVector2(name, this._vectors2[name]);
  25736. }
  25737. // Vector3
  25738. for (name in this._vectors3) {
  25739. this._effect.setVector3(name, this._vectors3[name]);
  25740. }
  25741. // Vector4
  25742. for (name in this._vectors4) {
  25743. this._effect.setVector4(name, this._vectors4[name]);
  25744. }
  25745. // Matrix
  25746. for (name in this._matrices) {
  25747. this._effect.setMatrix(name, this._matrices[name]);
  25748. }
  25749. // Matrix 3x3
  25750. for (name in this._matrices3x3) {
  25751. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  25752. }
  25753. // Matrix 2x2
  25754. for (name in this._matrices2x2) {
  25755. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  25756. }
  25757. }
  25758. _super.prototype.bind.call(this, world, mesh);
  25759. };
  25760. ShaderMaterial.prototype.clone = function (name) {
  25761. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  25762. return newShaderMaterial;
  25763. };
  25764. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  25765. for (var name in this._textures) {
  25766. this._textures[name].dispose();
  25767. }
  25768. this._textures = [];
  25769. _super.prototype.dispose.call(this, forceDisposeEffect);
  25770. };
  25771. return ShaderMaterial;
  25772. })(BABYLON.Material);
  25773. BABYLON.ShaderMaterial = ShaderMaterial;
  25774. })(BABYLON || (BABYLON = {}));
  25775. var BABYLON;
  25776. (function (BABYLON) {
  25777. var VertexData = (function () {
  25778. function VertexData() {
  25779. }
  25780. VertexData.prototype.set = function (data, kind) {
  25781. switch (kind) {
  25782. case BABYLON.VertexBuffer.PositionKind:
  25783. this.positions = data;
  25784. break;
  25785. case BABYLON.VertexBuffer.NormalKind:
  25786. this.normals = data;
  25787. break;
  25788. case BABYLON.VertexBuffer.UVKind:
  25789. this.uvs = data;
  25790. break;
  25791. case BABYLON.VertexBuffer.UV2Kind:
  25792. this.uvs2 = data;
  25793. break;
  25794. case BABYLON.VertexBuffer.UV3Kind:
  25795. this.uvs3 = data;
  25796. break;
  25797. case BABYLON.VertexBuffer.UV4Kind:
  25798. this.uvs4 = data;
  25799. break;
  25800. case BABYLON.VertexBuffer.UV5Kind:
  25801. this.uvs5 = data;
  25802. break;
  25803. case BABYLON.VertexBuffer.UV6Kind:
  25804. this.uvs6 = data;
  25805. break;
  25806. case BABYLON.VertexBuffer.ColorKind:
  25807. this.colors = data;
  25808. break;
  25809. case BABYLON.VertexBuffer.MatricesIndicesKind:
  25810. this.matricesIndices = data;
  25811. break;
  25812. case BABYLON.VertexBuffer.MatricesWeightsKind:
  25813. this.matricesWeights = data;
  25814. break;
  25815. }
  25816. };
  25817. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  25818. this._applyTo(mesh, updatable);
  25819. };
  25820. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  25821. this._applyTo(geometry, updatable);
  25822. };
  25823. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  25824. this._update(mesh);
  25825. };
  25826. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  25827. this._update(geometry);
  25828. };
  25829. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  25830. if (this.positions) {
  25831. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  25832. }
  25833. if (this.normals) {
  25834. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  25835. }
  25836. if (this.uvs) {
  25837. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  25838. }
  25839. if (this.uvs2) {
  25840. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  25841. }
  25842. if (this.uvs3) {
  25843. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  25844. }
  25845. if (this.uvs4) {
  25846. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  25847. }
  25848. if (this.uvs5) {
  25849. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  25850. }
  25851. if (this.uvs6) {
  25852. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  25853. }
  25854. if (this.colors) {
  25855. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  25856. }
  25857. if (this.matricesIndices) {
  25858. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  25859. }
  25860. if (this.matricesWeights) {
  25861. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  25862. }
  25863. if (this.indices) {
  25864. meshOrGeometry.setIndices(this.indices);
  25865. }
  25866. };
  25867. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  25868. if (this.positions) {
  25869. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  25870. }
  25871. if (this.normals) {
  25872. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  25873. }
  25874. if (this.uvs) {
  25875. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  25876. }
  25877. if (this.uvs2) {
  25878. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  25879. }
  25880. if (this.uvs3) {
  25881. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  25882. }
  25883. if (this.uvs4) {
  25884. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  25885. }
  25886. if (this.uvs5) {
  25887. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  25888. }
  25889. if (this.uvs6) {
  25890. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  25891. }
  25892. if (this.colors) {
  25893. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  25894. }
  25895. if (this.matricesIndices) {
  25896. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  25897. }
  25898. if (this.matricesWeights) {
  25899. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  25900. }
  25901. if (this.indices) {
  25902. meshOrGeometry.setIndices(this.indices);
  25903. }
  25904. };
  25905. VertexData.prototype.transform = function (matrix) {
  25906. var transformed = BABYLON.Vector3.Zero();
  25907. if (this.positions) {
  25908. var position = BABYLON.Vector3.Zero();
  25909. for (var index = 0; index < this.positions.length; index += 3) {
  25910. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  25911. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  25912. this.positions[index] = transformed.x;
  25913. this.positions[index + 1] = transformed.y;
  25914. this.positions[index + 2] = transformed.z;
  25915. }
  25916. }
  25917. if (this.normals) {
  25918. var normal = BABYLON.Vector3.Zero();
  25919. for (index = 0; index < this.normals.length; index += 3) {
  25920. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  25921. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  25922. this.normals[index] = transformed.x;
  25923. this.normals[index + 1] = transformed.y;
  25924. this.normals[index + 2] = transformed.z;
  25925. }
  25926. }
  25927. };
  25928. VertexData.prototype.merge = function (other) {
  25929. if (other.indices) {
  25930. if (!this.indices) {
  25931. this.indices = [];
  25932. }
  25933. var offset = this.positions ? this.positions.length / 3 : 0;
  25934. for (var index = 0; index < other.indices.length; index++) {
  25935. this.indices.push(other.indices[index] + offset);
  25936. }
  25937. }
  25938. if (other.positions) {
  25939. if (!this.positions) {
  25940. this.positions = [];
  25941. }
  25942. for (index = 0; index < other.positions.length; index++) {
  25943. this.positions.push(other.positions[index]);
  25944. }
  25945. }
  25946. if (other.normals) {
  25947. if (!this.normals) {
  25948. this.normals = [];
  25949. }
  25950. for (index = 0; index < other.normals.length; index++) {
  25951. this.normals.push(other.normals[index]);
  25952. }
  25953. }
  25954. if (other.uvs) {
  25955. if (!this.uvs) {
  25956. this.uvs = [];
  25957. }
  25958. for (index = 0; index < other.uvs.length; index++) {
  25959. this.uvs.push(other.uvs[index]);
  25960. }
  25961. }
  25962. if (other.uvs2) {
  25963. if (!this.uvs2) {
  25964. this.uvs2 = [];
  25965. }
  25966. for (index = 0; index < other.uvs2.length; index++) {
  25967. this.uvs2.push(other.uvs2[index]);
  25968. }
  25969. }
  25970. if (other.uvs3) {
  25971. if (!this.uvs3) {
  25972. this.uvs3 = [];
  25973. }
  25974. for (index = 0; index < other.uvs3.length; index++) {
  25975. this.uvs3.push(other.uvs3[index]);
  25976. }
  25977. }
  25978. if (other.uvs4) {
  25979. if (!this.uvs4) {
  25980. this.uvs4 = [];
  25981. }
  25982. for (index = 0; index < other.uvs4.length; index++) {
  25983. this.uvs4.push(other.uvs4[index]);
  25984. }
  25985. }
  25986. if (other.uvs5) {
  25987. if (!this.uvs5) {
  25988. this.uvs5 = [];
  25989. }
  25990. for (index = 0; index < other.uvs5.length; index++) {
  25991. this.uvs5.push(other.uvs5[index]);
  25992. }
  25993. }
  25994. if (other.uvs6) {
  25995. if (!this.uvs6) {
  25996. this.uvs6 = [];
  25997. }
  25998. for (index = 0; index < other.uvs6.length; index++) {
  25999. this.uvs6.push(other.uvs6[index]);
  26000. }
  26001. }
  26002. if (other.matricesIndices) {
  26003. if (!this.matricesIndices) {
  26004. this.matricesIndices = [];
  26005. }
  26006. for (index = 0; index < other.matricesIndices.length; index++) {
  26007. this.matricesIndices.push(other.matricesIndices[index]);
  26008. }
  26009. }
  26010. if (other.matricesWeights) {
  26011. if (!this.matricesWeights) {
  26012. this.matricesWeights = [];
  26013. }
  26014. for (index = 0; index < other.matricesWeights.length; index++) {
  26015. this.matricesWeights.push(other.matricesWeights[index]);
  26016. }
  26017. }
  26018. if (other.colors) {
  26019. if (!this.colors) {
  26020. this.colors = [];
  26021. }
  26022. for (index = 0; index < other.colors.length; index++) {
  26023. this.colors.push(other.colors[index]);
  26024. }
  26025. }
  26026. };
  26027. // Statics
  26028. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  26029. return VertexData._ExtractFrom(mesh, copyWhenShared);
  26030. };
  26031. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  26032. return VertexData._ExtractFrom(geometry, copyWhenShared);
  26033. };
  26034. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  26035. var result = new VertexData();
  26036. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26037. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  26038. }
  26039. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26040. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  26041. }
  26042. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26043. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  26044. }
  26045. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26046. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  26047. }
  26048. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26049. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  26050. }
  26051. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26052. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  26053. }
  26054. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26055. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  26056. }
  26057. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26058. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  26059. }
  26060. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26061. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  26062. }
  26063. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26064. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  26065. }
  26066. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26067. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  26068. }
  26069. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26070. return result;
  26071. };
  26072. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  26073. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26074. closeArray = closeArray || false;
  26075. closePath = closePath || false;
  26076. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26077. offset = offset || defaultOffset;
  26078. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26079. var positions = [];
  26080. var indices = [];
  26081. var normals = [];
  26082. var uvs = [];
  26083. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26084. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26085. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26086. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26087. var minlg; // minimal length among all paths from pathArray
  26088. var lg = []; // array of path lengths : nb of vertex per path
  26089. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26090. var p; // path iterator
  26091. var i; // point iterator
  26092. var j; // point iterator
  26093. // if single path in pathArray
  26094. if (pathArray.length < 2) {
  26095. var ar1 = [];
  26096. var ar2 = [];
  26097. for (i = 0; i < pathArray[0].length - offset; i++) {
  26098. ar1.push(pathArray[0][i]);
  26099. ar2.push(pathArray[0][i + offset]);
  26100. }
  26101. pathArray = [ar1, ar2];
  26102. }
  26103. // positions and horizontal distances (u)
  26104. var idc = 0;
  26105. var closePathCorr = (closePath) ? 1 : 0;
  26106. var path;
  26107. var l;
  26108. minlg = pathArray[0].length;
  26109. for (p = 0; p < pathArray.length; p++) {
  26110. uTotalDistance[p] = 0;
  26111. us[p] = [0];
  26112. path = pathArray[p];
  26113. l = path.length;
  26114. minlg = (minlg < l) ? minlg : l;
  26115. j = 0;
  26116. while (j < l) {
  26117. positions.push(path[j].x, path[j].y, path[j].z);
  26118. if (j > 0) {
  26119. var vectlg = path[j].subtract(path[j - 1]).length();
  26120. var dist = vectlg + uTotalDistance[p];
  26121. us[p].push(dist);
  26122. uTotalDistance[p] = dist;
  26123. }
  26124. j++;
  26125. }
  26126. if (closePath) {
  26127. j--;
  26128. positions.push(path[0].x, path[0].y, path[0].z);
  26129. vectlg = path[j].subtract(path[0]).length();
  26130. dist = vectlg + uTotalDistance[p];
  26131. us[p].push(dist);
  26132. uTotalDistance[p] = dist;
  26133. }
  26134. lg[p] = l + closePathCorr;
  26135. idx[p] = idc;
  26136. idc += (l + closePathCorr);
  26137. }
  26138. // vertical distances (v)
  26139. var path1;
  26140. var path2;
  26141. var vertex1;
  26142. var vertex2;
  26143. for (i = 0; i < minlg + closePathCorr; i++) {
  26144. vTotalDistance[i] = 0;
  26145. vs[i] = [0];
  26146. for (p = 0; p < pathArray.length - 1; p++) {
  26147. path1 = pathArray[p];
  26148. path2 = pathArray[p + 1];
  26149. if (i === minlg) {
  26150. vertex1 = path1[0];
  26151. vertex2 = path2[0];
  26152. }
  26153. else {
  26154. vertex1 = path1[i];
  26155. vertex2 = path2[i];
  26156. }
  26157. vectlg = vertex2.subtract(vertex1).length();
  26158. dist = vectlg + vTotalDistance[i];
  26159. vs[i].push(dist);
  26160. vTotalDistance[i] = dist;
  26161. }
  26162. if (closeArray) {
  26163. path1 = pathArray[p];
  26164. path2 = pathArray[0];
  26165. vectlg = path2[i].subtract(path1[i]).length();
  26166. dist = vectlg + vTotalDistance[i];
  26167. vTotalDistance[i] = dist;
  26168. }
  26169. }
  26170. // uvs
  26171. var u;
  26172. var v;
  26173. for (p = 0; p < pathArray.length; p++) {
  26174. for (i = 0; i < minlg + closePathCorr; i++) {
  26175. u = us[p][i] / uTotalDistance[p];
  26176. v = vs[i][p] / vTotalDistance[i];
  26177. uvs.push(u, v);
  26178. }
  26179. }
  26180. // indices
  26181. p = 0; // path index
  26182. var pi = 0; // positions array index
  26183. var l1 = lg[p] - 1; // path1 length
  26184. var l2 = lg[p + 1] - 1; // path2 length
  26185. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26186. var shft = idx[1] - idx[0]; // shift
  26187. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26188. while (pi <= min && p < path1nb) {
  26189. // 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
  26190. indices.push(pi, pi + shft, pi + 1);
  26191. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26192. pi += 1;
  26193. if (pi === min) {
  26194. p++;
  26195. if (p === lg.length - 1) {
  26196. shft = idx[0] - idx[p];
  26197. l1 = lg[p] - 1;
  26198. l2 = lg[0] - 1;
  26199. }
  26200. else {
  26201. shft = idx[p + 1] - idx[p];
  26202. l1 = lg[p] - 1;
  26203. l2 = lg[p + 1] - 1;
  26204. }
  26205. pi = idx[p];
  26206. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26207. }
  26208. }
  26209. // normals
  26210. VertexData.ComputeNormals(positions, indices, normals);
  26211. if (closePath) {
  26212. var indexFirst = 0;
  26213. var indexLast = 0;
  26214. for (p = 0; p < pathArray.length; p++) {
  26215. indexFirst = idx[p] * 3;
  26216. if (p + 1 < pathArray.length) {
  26217. indexLast = (idx[p + 1] - 1) * 3;
  26218. }
  26219. else {
  26220. indexLast = normals.length - 3;
  26221. }
  26222. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26223. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26224. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26225. normals[indexLast] = normals[indexFirst];
  26226. normals[indexLast + 1] = normals[indexFirst + 1];
  26227. normals[indexLast + 2] = normals[indexFirst + 2];
  26228. }
  26229. }
  26230. // sides
  26231. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26232. // Result
  26233. var vertexData = new VertexData();
  26234. vertexData.indices = indices;
  26235. vertexData.positions = positions;
  26236. vertexData.normals = normals;
  26237. vertexData.uvs = uvs;
  26238. if (closePath) {
  26239. vertexData._idx = idx;
  26240. }
  26241. return vertexData;
  26242. };
  26243. VertexData.CreateBox = function (size, sideOrientation) {
  26244. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26245. var normalsSource = [
  26246. new BABYLON.Vector3(0, 0, 1),
  26247. new BABYLON.Vector3(0, 0, -1),
  26248. new BABYLON.Vector3(1, 0, 0),
  26249. new BABYLON.Vector3(-1, 0, 0),
  26250. new BABYLON.Vector3(0, 1, 0),
  26251. new BABYLON.Vector3(0, -1, 0)
  26252. ];
  26253. var indices = [];
  26254. var positions = [];
  26255. var normals = [];
  26256. var uvs = [];
  26257. size = size || 1;
  26258. // Create each face in turn.
  26259. for (var index = 0; index < normalsSource.length; index++) {
  26260. var normal = normalsSource[index];
  26261. // Get two vectors perpendicular to the face normal and to each other.
  26262. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26263. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26264. // Six indices (two triangles) per face.
  26265. var verticesLength = positions.length / 3;
  26266. indices.push(verticesLength);
  26267. indices.push(verticesLength + 1);
  26268. indices.push(verticesLength + 2);
  26269. indices.push(verticesLength);
  26270. indices.push(verticesLength + 2);
  26271. indices.push(verticesLength + 3);
  26272. // Four vertices per face.
  26273. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  26274. positions.push(vertex.x, vertex.y, vertex.z);
  26275. normals.push(normal.x, normal.y, normal.z);
  26276. uvs.push(1.0, 1.0);
  26277. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  26278. positions.push(vertex.x, vertex.y, vertex.z);
  26279. normals.push(normal.x, normal.y, normal.z);
  26280. uvs.push(0.0, 1.0);
  26281. vertex = normal.add(side1).add(side2).scale(size / 2);
  26282. positions.push(vertex.x, vertex.y, vertex.z);
  26283. normals.push(normal.x, normal.y, normal.z);
  26284. uvs.push(0.0, 0.0);
  26285. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  26286. positions.push(vertex.x, vertex.y, vertex.z);
  26287. normals.push(normal.x, normal.y, normal.z);
  26288. uvs.push(1.0, 0.0);
  26289. }
  26290. // sides
  26291. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26292. // Result
  26293. var vertexData = new VertexData();
  26294. vertexData.indices = indices;
  26295. vertexData.positions = positions;
  26296. vertexData.normals = normals;
  26297. vertexData.uvs = uvs;
  26298. return vertexData;
  26299. };
  26300. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  26301. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26302. segments = segments || 32;
  26303. diameter = diameter || 1;
  26304. var radius = diameter / 2;
  26305. var totalZRotationSteps = 2 + segments;
  26306. var totalYRotationSteps = 2 * totalZRotationSteps;
  26307. var indices = [];
  26308. var positions = [];
  26309. var normals = [];
  26310. var uvs = [];
  26311. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26312. var normalizedZ = zRotationStep / totalZRotationSteps;
  26313. var angleZ = (normalizedZ * Math.PI);
  26314. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26315. var normalizedY = yRotationStep / totalYRotationSteps;
  26316. var angleY = normalizedY * Math.PI * 2;
  26317. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26318. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26319. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26320. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26321. var vertex = complete.scale(radius);
  26322. var normal = BABYLON.Vector3.Normalize(vertex);
  26323. positions.push(vertex.x, vertex.y, vertex.z);
  26324. normals.push(normal.x, normal.y, normal.z);
  26325. uvs.push(normalizedZ, normalizedY);
  26326. }
  26327. if (zRotationStep > 0) {
  26328. var verticesCount = positions.length / 3;
  26329. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26330. indices.push((firstIndex));
  26331. indices.push((firstIndex + 1));
  26332. indices.push(firstIndex + totalYRotationSteps + 1);
  26333. indices.push((firstIndex + totalYRotationSteps + 1));
  26334. indices.push((firstIndex + 1));
  26335. indices.push((firstIndex + totalYRotationSteps + 2));
  26336. }
  26337. }
  26338. }
  26339. // Sides
  26340. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26341. // Result
  26342. var vertexData = new VertexData();
  26343. vertexData.indices = indices;
  26344. vertexData.positions = positions;
  26345. vertexData.normals = normals;
  26346. vertexData.uvs = uvs;
  26347. return vertexData;
  26348. };
  26349. // Cylinder and cone (made using ribbons)
  26350. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  26351. if (subdivisions === void 0) { subdivisions = 1; }
  26352. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26353. // setup tube creation parameters
  26354. var path = [];
  26355. for (var i = 0; i <= subdivisions; i++) {
  26356. path.push(new BABYLON.Vector3(0, height * (-0.5 + i / subdivisions), 0));
  26357. }
  26358. // this is what defines the radius along the cylinder
  26359. var radiusFunction = function (i, distance) {
  26360. return (diameterBottom + (diameterTop - diameterBottom) * distance / height) / 2;
  26361. };
  26362. // shortcut to 3d path data
  26363. var path3D = new BABYLON.Path3D(path);
  26364. var tangents = path3D.getTangents();
  26365. var normals = path3D.getNormals();
  26366. var distances = path3D.getDistances();
  26367. // let's build the array of paths (rings)
  26368. var pathArray = [];
  26369. var ringVertex;
  26370. var angle;
  26371. var angle_step = Math.PI * 2 / tessellation;
  26372. var distance = 0;
  26373. for (var i = 0; i <= subdivisions; i++) {
  26374. pathArray[i] = [];
  26375. for (var j = 0; j < tessellation; j++) {
  26376. angle = j * angle_step;
  26377. ringVertex = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26378. ringVertex.scaleInPlace(radiusFunction(i, distances[i])).addInPlace(path[i]);
  26379. pathArray[i].push(ringVertex);
  26380. }
  26381. }
  26382. // create ribbon based on computed paths (& close seam)
  26383. var vertexdata = VertexData.CreateRibbon(pathArray, false, true, 0, sideOrientation);
  26384. var createCylinderCap = function (isTop) {
  26385. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  26386. if (radius === 0) {
  26387. return;
  26388. }
  26389. var vbase = vertexdata.positions.length / 3;
  26390. var offset = new BABYLON.Vector3(0, isTop ? height / 2 : -height / 2, 0);
  26391. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  26392. // Positions, normals & uvs
  26393. var angle;
  26394. var circleVector;
  26395. for (var i = 0; i < tessellation; i++) {
  26396. angle = Math.PI * 2 * i / tessellation;
  26397. circleVector = new BABYLON.Vector3(Math.cos(-angle), 0, Math.sin(-angle));
  26398. var position = circleVector.scale(radius).add(offset);
  26399. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  26400. vertexdata.positions.push(position.x, position.y, position.z);
  26401. vertexdata.normals.push(0, isTop ? 1 : -1, 0);
  26402. vertexdata.uvs.push(textureCoordinate.x, textureCoordinate.y);
  26403. }
  26404. // Indices
  26405. for (i = 0; i < tessellation - 2; i++) {
  26406. if (!isTop) {
  26407. vertexdata.indices.push(vbase);
  26408. vertexdata.indices.push(vbase + (i + 1) % tessellation);
  26409. vertexdata.indices.push(vbase + (i + 2) % tessellation);
  26410. }
  26411. else {
  26412. vertexdata.indices.push(vbase);
  26413. vertexdata.indices.push(vbase + (i + 2) % tessellation);
  26414. vertexdata.indices.push(vbase + (i + 1) % tessellation);
  26415. }
  26416. }
  26417. };
  26418. // add caps to geometry
  26419. createCylinderCap(true);
  26420. createCylinderCap(false);
  26421. return vertexdata;
  26422. };
  26423. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  26424. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26425. var indices = [];
  26426. var positions = [];
  26427. var normals = [];
  26428. var uvs = [];
  26429. diameter = diameter || 1;
  26430. thickness = thickness || 0.5;
  26431. tessellation = tessellation || 16;
  26432. var stride = tessellation + 1;
  26433. for (var i = 0; i <= tessellation; i++) {
  26434. var u = i / tessellation;
  26435. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  26436. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  26437. for (var j = 0; j <= tessellation; j++) {
  26438. var v = 1 - j / tessellation;
  26439. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  26440. var dx = Math.cos(innerAngle);
  26441. var dy = Math.sin(innerAngle);
  26442. // Create a vertex.
  26443. var normal = new BABYLON.Vector3(dx, dy, 0);
  26444. var position = normal.scale(thickness / 2);
  26445. var textureCoordinate = new BABYLON.Vector2(u, v);
  26446. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  26447. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  26448. positions.push(position.x, position.y, position.z);
  26449. normals.push(normal.x, normal.y, normal.z);
  26450. uvs.push(textureCoordinate.x, textureCoordinate.y);
  26451. // And create indices for two triangles.
  26452. var nextI = (i + 1) % stride;
  26453. var nextJ = (j + 1) % stride;
  26454. indices.push(i * stride + j);
  26455. indices.push(i * stride + nextJ);
  26456. indices.push(nextI * stride + j);
  26457. indices.push(i * stride + nextJ);
  26458. indices.push(nextI * stride + nextJ);
  26459. indices.push(nextI * stride + j);
  26460. }
  26461. }
  26462. // Sides
  26463. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26464. // Result
  26465. var vertexData = new VertexData();
  26466. vertexData.indices = indices;
  26467. vertexData.positions = positions;
  26468. vertexData.normals = normals;
  26469. vertexData.uvs = uvs;
  26470. return vertexData;
  26471. };
  26472. VertexData.CreateLines = function (points) {
  26473. var indices = [];
  26474. var positions = [];
  26475. for (var index = 0; index < points.length; index++) {
  26476. positions.push(points[index].x, points[index].y, points[index].z);
  26477. if (index > 0) {
  26478. indices.push(index - 1);
  26479. indices.push(index);
  26480. }
  26481. }
  26482. // Result
  26483. var vertexData = new VertexData();
  26484. vertexData.indices = indices;
  26485. vertexData.positions = positions;
  26486. return vertexData;
  26487. };
  26488. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  26489. dashSize = dashSize || 3;
  26490. gapSize = gapSize || 1;
  26491. dashNb = dashNb || 200;
  26492. var positions = new Array();
  26493. var indices = new Array();
  26494. var curvect = BABYLON.Vector3.Zero();
  26495. var lg = 0;
  26496. var nb = 0;
  26497. var shft = 0;
  26498. var dashshft = 0;
  26499. var curshft = 0;
  26500. var idx = 0;
  26501. var i = 0;
  26502. for (i = 0; i < points.length - 1; i++) {
  26503. points[i + 1].subtractToRef(points[i], curvect);
  26504. lg += curvect.length();
  26505. }
  26506. shft = lg / dashNb;
  26507. dashshft = dashSize * shft / (dashSize + gapSize);
  26508. for (i = 0; i < points.length - 1; i++) {
  26509. points[i + 1].subtractToRef(points[i], curvect);
  26510. nb = Math.floor(curvect.length() / shft);
  26511. curvect.normalize();
  26512. for (var j = 0; j < nb; j++) {
  26513. curshft = shft * j;
  26514. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  26515. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  26516. indices.push(idx, idx + 1);
  26517. idx += 2;
  26518. }
  26519. }
  26520. // Result
  26521. var vertexData = new VertexData();
  26522. vertexData.positions = positions;
  26523. vertexData.indices = indices;
  26524. return vertexData;
  26525. };
  26526. VertexData.CreateGround = function (width, height, subdivisions) {
  26527. var indices = [];
  26528. var positions = [];
  26529. var normals = [];
  26530. var uvs = [];
  26531. var row, col;
  26532. width = width || 1;
  26533. height = height || 1;
  26534. subdivisions = subdivisions || 1;
  26535. for (row = 0; row <= subdivisions; row++) {
  26536. for (col = 0; col <= subdivisions; col++) {
  26537. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26538. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26539. positions.push(position.x, position.y, position.z);
  26540. normals.push(normal.x, normal.y, normal.z);
  26541. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26542. }
  26543. }
  26544. for (row = 0; row < subdivisions; row++) {
  26545. for (col = 0; col < subdivisions; col++) {
  26546. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26547. indices.push(col + 1 + row * (subdivisions + 1));
  26548. indices.push(col + row * (subdivisions + 1));
  26549. indices.push(col + (row + 1) * (subdivisions + 1));
  26550. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26551. indices.push(col + row * (subdivisions + 1));
  26552. }
  26553. }
  26554. // Result
  26555. var vertexData = new VertexData();
  26556. vertexData.indices = indices;
  26557. vertexData.positions = positions;
  26558. vertexData.normals = normals;
  26559. vertexData.uvs = uvs;
  26560. return vertexData;
  26561. };
  26562. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  26563. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  26564. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  26565. var indices = [];
  26566. var positions = [];
  26567. var normals = [];
  26568. var uvs = [];
  26569. var row, col, tileRow, tileCol;
  26570. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  26571. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  26572. precision.w = (precision.w < 1) ? 1 : precision.w;
  26573. precision.h = (precision.h < 1) ? 1 : precision.h;
  26574. var tileSize = {
  26575. 'w': (xmax - xmin) / subdivisions.w,
  26576. 'h': (zmax - zmin) / subdivisions.h
  26577. };
  26578. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  26579. // Indices
  26580. var base = positions.length / 3;
  26581. var rowLength = precision.w + 1;
  26582. for (row = 0; row < precision.h; row++) {
  26583. for (col = 0; col < precision.w; col++) {
  26584. var square = [
  26585. base + col + row * rowLength,
  26586. base + (col + 1) + row * rowLength,
  26587. base + (col + 1) + (row + 1) * rowLength,
  26588. base + col + (row + 1) * rowLength
  26589. ];
  26590. indices.push(square[1]);
  26591. indices.push(square[2]);
  26592. indices.push(square[3]);
  26593. indices.push(square[0]);
  26594. indices.push(square[1]);
  26595. indices.push(square[3]);
  26596. }
  26597. }
  26598. // Position, normals and uvs
  26599. var position = BABYLON.Vector3.Zero();
  26600. var normal = new BABYLON.Vector3(0, 1.0, 0);
  26601. for (row = 0; row <= precision.h; row++) {
  26602. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  26603. for (col = 0; col <= precision.w; col++) {
  26604. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  26605. position.y = 0;
  26606. positions.push(position.x, position.y, position.z);
  26607. normals.push(normal.x, normal.y, normal.z);
  26608. uvs.push(col / precision.w, row / precision.h);
  26609. }
  26610. }
  26611. }
  26612. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  26613. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  26614. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  26615. }
  26616. }
  26617. // Result
  26618. var vertexData = new VertexData();
  26619. vertexData.indices = indices;
  26620. vertexData.positions = positions;
  26621. vertexData.normals = normals;
  26622. vertexData.uvs = uvs;
  26623. return vertexData;
  26624. };
  26625. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  26626. var indices = [];
  26627. var positions = [];
  26628. var normals = [];
  26629. var uvs = [];
  26630. var row, col;
  26631. // Vertices
  26632. for (row = 0; row <= subdivisions; row++) {
  26633. for (col = 0; col <= subdivisions; col++) {
  26634. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  26635. // Compute height
  26636. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  26637. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  26638. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  26639. var r = buffer[pos] / 255.0;
  26640. var g = buffer[pos + 1] / 255.0;
  26641. var b = buffer[pos + 2] / 255.0;
  26642. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26643. position.y = minHeight + (maxHeight - minHeight) * gradient;
  26644. // Add vertex
  26645. positions.push(position.x, position.y, position.z);
  26646. normals.push(0, 0, 0);
  26647. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  26648. }
  26649. }
  26650. // Indices
  26651. for (row = 0; row < subdivisions; row++) {
  26652. for (col = 0; col < subdivisions; col++) {
  26653. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26654. indices.push(col + 1 + row * (subdivisions + 1));
  26655. indices.push(col + row * (subdivisions + 1));
  26656. indices.push(col + (row + 1) * (subdivisions + 1));
  26657. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  26658. indices.push(col + row * (subdivisions + 1));
  26659. }
  26660. }
  26661. // Normals
  26662. VertexData.ComputeNormals(positions, indices, normals);
  26663. // Result
  26664. var vertexData = new VertexData();
  26665. vertexData.indices = indices;
  26666. vertexData.positions = positions;
  26667. vertexData.normals = normals;
  26668. vertexData.uvs = uvs;
  26669. return vertexData;
  26670. };
  26671. VertexData.CreatePlane = function (size, sideOrientation) {
  26672. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26673. var indices = [];
  26674. var positions = [];
  26675. var normals = [];
  26676. var uvs = [];
  26677. size = size || 1;
  26678. // Vertices
  26679. var halfSize = size / 2.0;
  26680. positions.push(-halfSize, -halfSize, 0);
  26681. normals.push(0, 0, -1.0);
  26682. uvs.push(0.0, 0.0);
  26683. positions.push(halfSize, -halfSize, 0);
  26684. normals.push(0, 0, -1.0);
  26685. uvs.push(1.0, 0.0);
  26686. positions.push(halfSize, halfSize, 0);
  26687. normals.push(0, 0, -1.0);
  26688. uvs.push(1.0, 1.0);
  26689. positions.push(-halfSize, halfSize, 0);
  26690. normals.push(0, 0, -1.0);
  26691. uvs.push(0.0, 1.0);
  26692. // Indices
  26693. indices.push(0);
  26694. indices.push(1);
  26695. indices.push(2);
  26696. indices.push(0);
  26697. indices.push(2);
  26698. indices.push(3);
  26699. // Sides
  26700. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26701. // Result
  26702. var vertexData = new VertexData();
  26703. vertexData.indices = indices;
  26704. vertexData.positions = positions;
  26705. vertexData.normals = normals;
  26706. vertexData.uvs = uvs;
  26707. return vertexData;
  26708. };
  26709. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  26710. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26711. var positions = [];
  26712. var indices = [];
  26713. var normals = [];
  26714. var uvs = [];
  26715. // positions and uvs
  26716. positions.push(0, 0, 0); // disc center first
  26717. uvs.push(0.5, 0.5);
  26718. var step = Math.PI * 2 / tessellation;
  26719. for (var a = 0; a < Math.PI * 2; a += step) {
  26720. var x = Math.cos(a);
  26721. var y = Math.sin(a);
  26722. var u = (x + 1) / 2;
  26723. var v = (1 - y) / 2;
  26724. positions.push(radius * x, radius * y, 0);
  26725. uvs.push(u, v);
  26726. }
  26727. positions.push(positions[3], positions[4], positions[5]); // close the circle
  26728. uvs.push(uvs[2], uvs[3]);
  26729. //indices
  26730. var vertexNb = positions.length / 3;
  26731. for (var i = 1; i < vertexNb - 1; i++) {
  26732. indices.push(i + 1, 0, i);
  26733. }
  26734. // result
  26735. VertexData.ComputeNormals(positions, indices, normals);
  26736. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26737. var vertexData = new VertexData();
  26738. vertexData.indices = indices;
  26739. vertexData.positions = positions;
  26740. vertexData.normals = normals;
  26741. vertexData.uvs = uvs;
  26742. return vertexData;
  26743. };
  26744. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  26745. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  26746. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  26747. var indices = [];
  26748. var positions = [];
  26749. var normals = [];
  26750. var uvs = [];
  26751. radius = radius || 2;
  26752. tube = tube || 0.5;
  26753. radialSegments = radialSegments || 32;
  26754. tubularSegments = tubularSegments || 32;
  26755. p = p || 2;
  26756. q = q || 3;
  26757. // Helper
  26758. var getPos = function (angle) {
  26759. var cu = Math.cos(angle);
  26760. var su = Math.sin(angle);
  26761. var quOverP = q / p * angle;
  26762. var cs = Math.cos(quOverP);
  26763. var tx = radius * (2 + cs) * 0.5 * cu;
  26764. var ty = radius * (2 + cs) * su * 0.5;
  26765. var tz = radius * Math.sin(quOverP) * 0.5;
  26766. return new BABYLON.Vector3(tx, ty, tz);
  26767. };
  26768. // Vertices
  26769. for (var i = 0; i <= radialSegments; i++) {
  26770. var modI = i % radialSegments;
  26771. var u = modI / radialSegments * 2 * p * Math.PI;
  26772. var p1 = getPos(u);
  26773. var p2 = getPos(u + 0.01);
  26774. var tang = p2.subtract(p1);
  26775. var n = p2.add(p1);
  26776. var bitan = BABYLON.Vector3.Cross(tang, n);
  26777. n = BABYLON.Vector3.Cross(bitan, tang);
  26778. bitan.normalize();
  26779. n.normalize();
  26780. for (var j = 0; j < tubularSegments; j++) {
  26781. var modJ = j % tubularSegments;
  26782. var v = modJ / tubularSegments * 2 * Math.PI;
  26783. var cx = -tube * Math.cos(v);
  26784. var cy = tube * Math.sin(v);
  26785. positions.push(p1.x + cx * n.x + cy * bitan.x);
  26786. positions.push(p1.y + cx * n.y + cy * bitan.y);
  26787. positions.push(p1.z + cx * n.z + cy * bitan.z);
  26788. uvs.push(i / radialSegments);
  26789. uvs.push(j / tubularSegments);
  26790. }
  26791. }
  26792. for (i = 0; i < radialSegments; i++) {
  26793. for (j = 0; j < tubularSegments; j++) {
  26794. var jNext = (j + 1) % tubularSegments;
  26795. var a = i * tubularSegments + j;
  26796. var b = (i + 1) * tubularSegments + j;
  26797. var c = (i + 1) * tubularSegments + jNext;
  26798. var d = i * tubularSegments + jNext;
  26799. indices.push(d);
  26800. indices.push(b);
  26801. indices.push(a);
  26802. indices.push(d);
  26803. indices.push(c);
  26804. indices.push(b);
  26805. }
  26806. }
  26807. // Normals
  26808. VertexData.ComputeNormals(positions, indices, normals);
  26809. // Sides
  26810. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  26811. // Result
  26812. var vertexData = new VertexData();
  26813. vertexData.indices = indices;
  26814. vertexData.positions = positions;
  26815. vertexData.normals = normals;
  26816. vertexData.uvs = uvs;
  26817. return vertexData;
  26818. };
  26819. // Tools
  26820. /**
  26821. * @param {any} - positions (number[] or Float32Array)
  26822. * @param {any} - indices (number[] or Uint16Array)
  26823. * @param {any} - normals (number[] or Float32Array)
  26824. */
  26825. VertexData.ComputeNormals = function (positions, indices, normals) {
  26826. var index = 0;
  26827. // temp Vector3
  26828. var p1p2 = BABYLON.Vector3.Zero();
  26829. var p3p2 = BABYLON.Vector3.Zero();
  26830. var faceNormal = BABYLON.Vector3.Zero();
  26831. var vertexNormali1 = BABYLON.Vector3.Zero();
  26832. for (index = 0; index < positions.length; index++) {
  26833. normals[index] = 0.0;
  26834. }
  26835. // indice triplet = 1 face
  26836. var nbFaces = indices.length / 3;
  26837. for (index = 0; index < nbFaces; index++) {
  26838. var i1 = indices[index * 3];
  26839. var i2 = indices[index * 3 + 1];
  26840. var i3 = indices[index * 3 + 2];
  26841. p1p2.x = positions[i1 * 3] - positions[i2 * 3];
  26842. p1p2.y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  26843. p1p2.z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  26844. p3p2.x = positions[i3 * 3] - positions[i2 * 3];
  26845. p3p2.y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  26846. p3p2.z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  26847. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  26848. faceNormal.normalize();
  26849. normals[i1 * 3] += faceNormal.x;
  26850. normals[i1 * 3 + 1] += faceNormal.y;
  26851. normals[i1 * 3 + 2] += faceNormal.z;
  26852. normals[i2 * 3] += faceNormal.x;
  26853. normals[i2 * 3 + 1] += faceNormal.y;
  26854. normals[i2 * 3 + 2] += faceNormal.z;
  26855. normals[i3 * 3] += faceNormal.x;
  26856. normals[i3 * 3 + 1] += faceNormal.y;
  26857. normals[i3 * 3 + 2] += faceNormal.z;
  26858. }
  26859. // last normalization
  26860. for (index = 0; index < normals.length / 3; index++) {
  26861. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  26862. vertexNormali1.normalize();
  26863. normals[index * 3] = vertexNormali1.x;
  26864. normals[index * 3 + 1] = vertexNormali1.y;
  26865. normals[index * 3 + 2] = vertexNormali1.z;
  26866. }
  26867. };
  26868. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  26869. var li = indices.length;
  26870. var ln = normals.length;
  26871. var i;
  26872. var n;
  26873. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26874. switch (sideOrientation) {
  26875. case BABYLON.Mesh.FRONTSIDE:
  26876. // nothing changed
  26877. break;
  26878. case BABYLON.Mesh.BACKSIDE:
  26879. var tmp;
  26880. // indices
  26881. for (i = 0; i < li; i += 3) {
  26882. tmp = indices[i];
  26883. indices[i] = indices[i + 2];
  26884. indices[i + 2] = tmp;
  26885. }
  26886. // normals
  26887. for (n = 0; n < ln; n++) {
  26888. normals[n] = -normals[n];
  26889. }
  26890. break;
  26891. case BABYLON.Mesh.DOUBLESIDE:
  26892. // positions
  26893. var lp = positions.length;
  26894. var l = lp / 3;
  26895. for (var p = 0; p < lp; p++) {
  26896. positions[lp + p] = positions[p];
  26897. }
  26898. // indices
  26899. for (i = 0; i < li; i += 3) {
  26900. indices[i + li] = indices[i + 2] + l;
  26901. indices[i + 1 + li] = indices[i + 1] + l;
  26902. indices[i + 2 + li] = indices[i] + l;
  26903. }
  26904. // normals
  26905. for (n = 0; n < ln; n++) {
  26906. normals[ln + n] = -normals[n];
  26907. }
  26908. // uvs
  26909. var lu = uvs.length;
  26910. for (var u = 0; u < lu; u++) {
  26911. uvs[u + lu] = uvs[u];
  26912. }
  26913. break;
  26914. }
  26915. };
  26916. return VertexData;
  26917. })();
  26918. BABYLON.VertexData = VertexData;
  26919. })(BABYLON || (BABYLON = {}));
  26920. var BABYLON;
  26921. (function (BABYLON) {
  26922. var AnaglyphPostProcess = (function (_super) {
  26923. __extends(AnaglyphPostProcess, _super);
  26924. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26925. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  26926. }
  26927. return AnaglyphPostProcess;
  26928. })(BABYLON.PostProcess);
  26929. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  26930. })(BABYLON || (BABYLON = {}));
  26931. var BABYLON;
  26932. (function (BABYLON) {
  26933. var Tags = (function () {
  26934. function Tags() {
  26935. }
  26936. Tags.EnableFor = function (obj) {
  26937. obj._tags = obj._tags || {};
  26938. obj.hasTags = function () {
  26939. return Tags.HasTags(obj);
  26940. };
  26941. obj.addTags = function (tagsString) {
  26942. return Tags.AddTagsTo(obj, tagsString);
  26943. };
  26944. obj.removeTags = function (tagsString) {
  26945. return Tags.RemoveTagsFrom(obj, tagsString);
  26946. };
  26947. obj.matchesTagsQuery = function (tagsQuery) {
  26948. return Tags.MatchesQuery(obj, tagsQuery);
  26949. };
  26950. };
  26951. Tags.DisableFor = function (obj) {
  26952. delete obj._tags;
  26953. delete obj.hasTags;
  26954. delete obj.addTags;
  26955. delete obj.removeTags;
  26956. delete obj.matchesTagsQuery;
  26957. };
  26958. Tags.HasTags = function (obj) {
  26959. if (!obj._tags) {
  26960. return false;
  26961. }
  26962. return !BABYLON.Tools.IsEmpty(obj._tags);
  26963. };
  26964. Tags.GetTags = function (obj) {
  26965. if (!obj._tags) {
  26966. return null;
  26967. }
  26968. return obj._tags;
  26969. };
  26970. // the tags 'true' and 'false' are reserved and cannot be used as tags
  26971. // a tag cannot start with '||', '&&', and '!'
  26972. // it cannot contain whitespaces
  26973. Tags.AddTagsTo = function (obj, tagsString) {
  26974. if (!tagsString) {
  26975. return;
  26976. }
  26977. var tags = tagsString.split(" ");
  26978. for (var t in tags) {
  26979. Tags._AddTagTo(obj, tags[t]);
  26980. }
  26981. };
  26982. Tags._AddTagTo = function (obj, tag) {
  26983. tag = tag.trim();
  26984. if (tag === "" || tag === "true" || tag === "false") {
  26985. return;
  26986. }
  26987. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  26988. return;
  26989. }
  26990. Tags.EnableFor(obj);
  26991. obj._tags[tag] = true;
  26992. };
  26993. Tags.RemoveTagsFrom = function (obj, tagsString) {
  26994. if (!Tags.HasTags(obj)) {
  26995. return;
  26996. }
  26997. var tags = tagsString.split(" ");
  26998. for (var t in tags) {
  26999. Tags._RemoveTagFrom(obj, tags[t]);
  27000. }
  27001. };
  27002. Tags._RemoveTagFrom = function (obj, tag) {
  27003. delete obj._tags[tag];
  27004. };
  27005. Tags.MatchesQuery = function (obj, tagsQuery) {
  27006. if (tagsQuery === undefined) {
  27007. return true;
  27008. }
  27009. if (tagsQuery === "") {
  27010. return Tags.HasTags(obj);
  27011. }
  27012. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  27013. };
  27014. return Tags;
  27015. })();
  27016. BABYLON.Tags = Tags;
  27017. })(BABYLON || (BABYLON = {}));
  27018. var BABYLON;
  27019. (function (BABYLON) {
  27020. var Internals;
  27021. (function (Internals) {
  27022. var AndOrNotEvaluator = (function () {
  27023. function AndOrNotEvaluator() {
  27024. }
  27025. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  27026. if (!query.match(/\([^\(\)]*\)/g)) {
  27027. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  27028. }
  27029. else {
  27030. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  27031. // remove parenthesis
  27032. r = r.slice(1, r.length - 1);
  27033. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  27034. });
  27035. }
  27036. if (query === "true") {
  27037. return true;
  27038. }
  27039. if (query === "false") {
  27040. return false;
  27041. }
  27042. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  27043. };
  27044. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  27045. evaluateCallback = evaluateCallback || (function (r) {
  27046. return r === "true" ? true : false;
  27047. });
  27048. var result;
  27049. var or = parenthesisContent.split("||");
  27050. for (var i in or) {
  27051. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  27052. var and = ori.split("&&");
  27053. if (and.length > 1) {
  27054. for (var j = 0; j < and.length; ++j) {
  27055. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  27056. if (andj !== "true" && andj !== "false") {
  27057. if (andj[0] === "!") {
  27058. result = !evaluateCallback(andj.substring(1));
  27059. }
  27060. else {
  27061. result = evaluateCallback(andj);
  27062. }
  27063. }
  27064. else {
  27065. result = andj === "true" ? true : false;
  27066. }
  27067. if (!result) {
  27068. ori = "false";
  27069. break;
  27070. }
  27071. }
  27072. }
  27073. if (result || ori === "true") {
  27074. result = true;
  27075. break;
  27076. }
  27077. // result equals false (or undefined)
  27078. if (ori !== "true" && ori !== "false") {
  27079. if (ori[0] === "!") {
  27080. result = !evaluateCallback(ori.substring(1));
  27081. }
  27082. else {
  27083. result = evaluateCallback(ori);
  27084. }
  27085. }
  27086. else {
  27087. result = ori === "true" ? true : false;
  27088. }
  27089. }
  27090. // the whole parenthesis scope is replaced by 'true' or 'false'
  27091. return result ? "true" : "false";
  27092. };
  27093. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  27094. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  27095. // remove whitespaces
  27096. r = r.replace(/[\s]/g, function () { return ""; });
  27097. return r.length % 2 ? "!" : "";
  27098. });
  27099. booleanString = booleanString.trim();
  27100. if (booleanString === "!true") {
  27101. booleanString = "false";
  27102. }
  27103. else if (booleanString === "!false") {
  27104. booleanString = "true";
  27105. }
  27106. return booleanString;
  27107. };
  27108. return AndOrNotEvaluator;
  27109. })();
  27110. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  27111. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27112. })(BABYLON || (BABYLON = {}));
  27113. var BABYLON;
  27114. (function (BABYLON) {
  27115. var PostProcessRenderPass = (function () {
  27116. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  27117. this._enabled = true;
  27118. this._refCount = 0;
  27119. this._name = name;
  27120. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  27121. this.setRenderList(renderList);
  27122. this._renderTexture.onBeforeRender = beforeRender;
  27123. this._renderTexture.onAfterRender = afterRender;
  27124. this._scene = scene;
  27125. this._renderList = renderList;
  27126. }
  27127. // private
  27128. PostProcessRenderPass.prototype._incRefCount = function () {
  27129. if (this._refCount === 0) {
  27130. this._scene.customRenderTargets.push(this._renderTexture);
  27131. }
  27132. return ++this._refCount;
  27133. };
  27134. PostProcessRenderPass.prototype._decRefCount = function () {
  27135. this._refCount--;
  27136. if (this._refCount <= 0) {
  27137. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  27138. }
  27139. return this._refCount;
  27140. };
  27141. PostProcessRenderPass.prototype._update = function () {
  27142. this.setRenderList(this._renderList);
  27143. };
  27144. // public
  27145. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  27146. this._renderTexture.renderList = renderList;
  27147. };
  27148. PostProcessRenderPass.prototype.getRenderTexture = function () {
  27149. return this._renderTexture;
  27150. };
  27151. return PostProcessRenderPass;
  27152. })();
  27153. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  27154. })(BABYLON || (BABYLON = {}));
  27155. var BABYLON;
  27156. (function (BABYLON) {
  27157. var PostProcessRenderEffect = (function () {
  27158. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  27159. this._engine = engine;
  27160. this._name = name;
  27161. this._singleInstance = singleInstance || true;
  27162. this._getPostProcess = getPostProcess;
  27163. this._cameras = [];
  27164. this._indicesForCamera = [];
  27165. this._postProcesses = {};
  27166. this._renderPasses = {};
  27167. this._renderEffectAsPasses = {};
  27168. }
  27169. PostProcessRenderEffect.prototype._update = function () {
  27170. for (var renderPassName in this._renderPasses) {
  27171. this._renderPasses[renderPassName]._update();
  27172. }
  27173. };
  27174. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  27175. this._renderPasses[renderPass._name] = renderPass;
  27176. this._linkParameters();
  27177. };
  27178. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  27179. delete this._renderPasses[renderPass._name];
  27180. this._linkParameters();
  27181. };
  27182. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  27183. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  27184. this._linkParameters();
  27185. };
  27186. PostProcessRenderEffect.prototype.getPass = function (passName) {
  27187. for (var renderPassName in this._renderPasses) {
  27188. if (renderPassName === passName) {
  27189. return this._renderPasses[passName];
  27190. }
  27191. }
  27192. };
  27193. PostProcessRenderEffect.prototype.emptyPasses = function () {
  27194. this._renderPasses = {};
  27195. this._linkParameters();
  27196. };
  27197. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  27198. var cameraKey;
  27199. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27200. for (var i = 0; i < _cam.length; i++) {
  27201. var camera = _cam[i];
  27202. var cameraName = camera.name;
  27203. if (this._singleInstance) {
  27204. cameraKey = 0;
  27205. }
  27206. else {
  27207. cameraKey = cameraName;
  27208. }
  27209. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  27210. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  27211. if (!this._indicesForCamera[cameraName]) {
  27212. this._indicesForCamera[cameraName] = [];
  27213. }
  27214. this._indicesForCamera[cameraName].push(index);
  27215. if (this._cameras.indexOf(camera) === -1) {
  27216. this._cameras[cameraName] = camera;
  27217. }
  27218. for (var passName in this._renderPasses) {
  27219. this._renderPasses[passName]._incRefCount();
  27220. }
  27221. }
  27222. this._linkParameters();
  27223. };
  27224. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  27225. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27226. for (var i = 0; i < _cam.length; i++) {
  27227. var camera = _cam[i];
  27228. var cameraName = camera.name;
  27229. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27230. var index = this._cameras.indexOf(cameraName);
  27231. this._indicesForCamera.splice(index, 1);
  27232. this._cameras.splice(index, 1);
  27233. for (var passName in this._renderPasses) {
  27234. this._renderPasses[passName]._decRefCount();
  27235. }
  27236. }
  27237. };
  27238. PostProcessRenderEffect.prototype._enable = function (cameras) {
  27239. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27240. for (var i = 0; i < _cam.length; i++) {
  27241. var camera = _cam[i];
  27242. var cameraName = camera.name;
  27243. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  27244. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  27245. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  27246. }
  27247. }
  27248. for (var passName in this._renderPasses) {
  27249. this._renderPasses[passName]._incRefCount();
  27250. }
  27251. }
  27252. };
  27253. PostProcessRenderEffect.prototype._disable = function (cameras) {
  27254. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27255. for (var i = 0; i < _cam.length; i++) {
  27256. var camera = _cam[i];
  27257. var cameraName = camera.Name;
  27258. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  27259. for (var passName in this._renderPasses) {
  27260. this._renderPasses[passName]._decRefCount();
  27261. }
  27262. }
  27263. };
  27264. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  27265. if (this._singleInstance) {
  27266. return this._postProcesses[0];
  27267. }
  27268. else {
  27269. return this._postProcesses[camera.name];
  27270. }
  27271. };
  27272. PostProcessRenderEffect.prototype._linkParameters = function () {
  27273. var _this = this;
  27274. for (var index in this._postProcesses) {
  27275. if (this.applyParameters) {
  27276. this.applyParameters(this._postProcesses[index]);
  27277. }
  27278. this._postProcesses[index].onBeforeRender = function (effect) {
  27279. _this._linkTextures(effect);
  27280. };
  27281. }
  27282. };
  27283. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  27284. for (var renderPassName in this._renderPasses) {
  27285. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  27286. }
  27287. for (var renderEffectName in this._renderEffectAsPasses) {
  27288. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  27289. }
  27290. };
  27291. return PostProcessRenderEffect;
  27292. })();
  27293. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  27294. })(BABYLON || (BABYLON = {}));
  27295. var BABYLON;
  27296. (function (BABYLON) {
  27297. var PostProcessRenderPipeline = (function () {
  27298. function PostProcessRenderPipeline(engine, name) {
  27299. this._engine = engine;
  27300. this._name = name;
  27301. this._renderEffects = {};
  27302. this._renderEffectsForIsolatedPass = {};
  27303. this._cameras = [];
  27304. }
  27305. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  27306. this._renderEffects[renderEffect._name] = renderEffect;
  27307. };
  27308. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  27309. var renderEffects = this._renderEffects[renderEffectName];
  27310. if (!renderEffects) {
  27311. return;
  27312. }
  27313. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27314. };
  27315. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  27316. var renderEffects = this._renderEffects[renderEffectName];
  27317. if (!renderEffects) {
  27318. return;
  27319. }
  27320. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  27321. };
  27322. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  27323. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27324. var indicesToDelete = [];
  27325. for (var i = 0; i < _cam.length; i++) {
  27326. var camera = _cam[i];
  27327. var cameraName = camera.name;
  27328. if (this._cameras.indexOf(camera) === -1) {
  27329. this._cameras[cameraName] = camera;
  27330. }
  27331. else if (unique) {
  27332. indicesToDelete.push(i);
  27333. }
  27334. }
  27335. for (var i = 0; i < indicesToDelete.length; i++) {
  27336. cameras.splice(indicesToDelete[i], 1);
  27337. }
  27338. for (var renderEffectName in this._renderEffects) {
  27339. this._renderEffects[renderEffectName]._attachCameras(_cam);
  27340. }
  27341. };
  27342. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  27343. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27344. for (var renderEffectName in this._renderEffects) {
  27345. this._renderEffects[renderEffectName]._detachCameras(_cam);
  27346. }
  27347. for (var i = 0; i < _cam.length; i++) {
  27348. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  27349. }
  27350. };
  27351. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  27352. var _this = this;
  27353. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27354. var pass = null;
  27355. for (var renderEffectName in this._renderEffects) {
  27356. pass = this._renderEffects[renderEffectName].getPass(passName);
  27357. if (pass != null) {
  27358. break;
  27359. }
  27360. }
  27361. if (pass === null) {
  27362. return;
  27363. }
  27364. for (var renderEffectName in this._renderEffects) {
  27365. this._renderEffects[renderEffectName]._disable(_cam);
  27366. }
  27367. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  27368. for (var i = 0; i < _cam.length; i++) {
  27369. var camera = _cam[i];
  27370. var cameraName = camera.name;
  27371. 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); });
  27372. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  27373. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  27374. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  27375. }
  27376. };
  27377. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  27378. var _this = this;
  27379. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  27380. for (var i = 0; i < _cam.length; i++) {
  27381. var camera = _cam[i];
  27382. var cameraName = camera.name;
  27383. 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); });
  27384. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  27385. }
  27386. for (var renderEffectName in this._renderEffects) {
  27387. this._renderEffects[renderEffectName]._enable(_cam);
  27388. }
  27389. };
  27390. PostProcessRenderPipeline.prototype._update = function () {
  27391. for (var renderEffectName in this._renderEffects) {
  27392. this._renderEffects[renderEffectName]._update();
  27393. }
  27394. for (var i = 0; i < this._cameras.length; i++) {
  27395. var cameraName = this._cameras[i].name;
  27396. if (this._renderEffectsForIsolatedPass[cameraName]) {
  27397. this._renderEffectsForIsolatedPass[cameraName]._update();
  27398. }
  27399. }
  27400. };
  27401. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  27402. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  27403. return PostProcessRenderPipeline;
  27404. })();
  27405. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  27406. })(BABYLON || (BABYLON = {}));
  27407. var BABYLON;
  27408. (function (BABYLON) {
  27409. var PostProcessRenderPipelineManager = (function () {
  27410. function PostProcessRenderPipelineManager() {
  27411. this._renderPipelines = {};
  27412. }
  27413. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  27414. this._renderPipelines[renderPipeline._name] = renderPipeline;
  27415. };
  27416. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  27417. var renderPipeline = this._renderPipelines[renderPipelineName];
  27418. if (!renderPipeline) {
  27419. return;
  27420. }
  27421. renderPipeline._attachCameras(cameras, unique);
  27422. };
  27423. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  27424. var renderPipeline = this._renderPipelines[renderPipelineName];
  27425. if (!renderPipeline) {
  27426. return;
  27427. }
  27428. renderPipeline._detachCameras(cameras);
  27429. };
  27430. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27431. var renderPipeline = this._renderPipelines[renderPipelineName];
  27432. if (!renderPipeline) {
  27433. return;
  27434. }
  27435. renderPipeline._enableEffect(renderEffectName, cameras);
  27436. };
  27437. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  27438. var renderPipeline = this._renderPipelines[renderPipelineName];
  27439. if (!renderPipeline) {
  27440. return;
  27441. }
  27442. renderPipeline._disableEffect(renderEffectName, cameras);
  27443. };
  27444. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  27445. var renderPipeline = this._renderPipelines[renderPipelineName];
  27446. if (!renderPipeline) {
  27447. return;
  27448. }
  27449. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  27450. };
  27451. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  27452. var renderPipeline = this._renderPipelines[renderPipelineName];
  27453. if (!renderPipeline) {
  27454. return;
  27455. }
  27456. renderPipeline._disableDisplayOnlyPass(cameras);
  27457. };
  27458. PostProcessRenderPipelineManager.prototype.update = function () {
  27459. for (var renderPipelineName in this._renderPipelines) {
  27460. this._renderPipelines[renderPipelineName]._update();
  27461. }
  27462. };
  27463. return PostProcessRenderPipelineManager;
  27464. })();
  27465. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  27466. })(BABYLON || (BABYLON = {}));
  27467. var BABYLON;
  27468. (function (BABYLON) {
  27469. var DisplayPassPostProcess = (function (_super) {
  27470. __extends(DisplayPassPostProcess, _super);
  27471. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  27472. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  27473. }
  27474. return DisplayPassPostProcess;
  27475. })(BABYLON.PostProcess);
  27476. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  27477. })(BABYLON || (BABYLON = {}));
  27478. var BABYLON;
  27479. (function (BABYLON) {
  27480. var BoundingBoxRenderer = (function () {
  27481. function BoundingBoxRenderer(scene) {
  27482. this.frontColor = new BABYLON.Color3(1, 1, 1);
  27483. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  27484. this.showBackLines = true;
  27485. this.renderList = new BABYLON.SmartArray(32);
  27486. this._scene = scene;
  27487. }
  27488. BoundingBoxRenderer.prototype._prepareRessources = function () {
  27489. if (this._colorShader) {
  27490. return;
  27491. }
  27492. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  27493. attributes: ["position"],
  27494. uniforms: ["worldViewProjection", "color"]
  27495. });
  27496. var engine = this._scene.getEngine();
  27497. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  27498. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  27499. 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]);
  27500. };
  27501. BoundingBoxRenderer.prototype.reset = function () {
  27502. this.renderList.reset();
  27503. };
  27504. BoundingBoxRenderer.prototype.render = function () {
  27505. if (this.renderList.length === 0) {
  27506. return;
  27507. }
  27508. this._prepareRessources();
  27509. if (!this._colorShader.isReady()) {
  27510. return;
  27511. }
  27512. var engine = this._scene.getEngine();
  27513. engine.setDepthWrite(false);
  27514. this._colorShader._preBind();
  27515. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  27516. var boundingBox = this.renderList.data[boundingBoxIndex];
  27517. var min = boundingBox.minimum;
  27518. var max = boundingBox.maximum;
  27519. var diff = max.subtract(min);
  27520. var median = min.add(diff.scale(0.5));
  27521. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  27522. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  27523. .multiply(boundingBox.getWorldMatrix());
  27524. // VBOs
  27525. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  27526. if (this.showBackLines) {
  27527. // Back
  27528. engine.setDepthFunctionToGreaterOrEqual();
  27529. this._scene.resetCachedMaterial();
  27530. this._colorShader.setColor4("color", this.backColor.toColor4());
  27531. this._colorShader.bind(worldMatrix);
  27532. // Draw order
  27533. engine.draw(false, 0, 24);
  27534. }
  27535. // Front
  27536. engine.setDepthFunctionToLess();
  27537. this._scene.resetCachedMaterial();
  27538. this._colorShader.setColor4("color", this.frontColor.toColor4());
  27539. this._colorShader.bind(worldMatrix);
  27540. // Draw order
  27541. engine.draw(false, 0, 24);
  27542. }
  27543. this._colorShader.unbind();
  27544. engine.setDepthFunctionToLessOrEqual();
  27545. engine.setDepthWrite(true);
  27546. };
  27547. BoundingBoxRenderer.prototype.dispose = function () {
  27548. if (!this._colorShader) {
  27549. return;
  27550. }
  27551. this._colorShader.dispose();
  27552. this._vb.dispose();
  27553. this._scene.getEngine()._releaseBuffer(this._ib);
  27554. };
  27555. return BoundingBoxRenderer;
  27556. })();
  27557. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  27558. })(BABYLON || (BABYLON = {}));
  27559. var BABYLON;
  27560. (function (BABYLON) {
  27561. var Condition = (function () {
  27562. function Condition(actionManager) {
  27563. this._actionManager = actionManager;
  27564. }
  27565. Condition.prototype.isValid = function () {
  27566. return true;
  27567. };
  27568. Condition.prototype._getProperty = function (propertyPath) {
  27569. return this._actionManager._getProperty(propertyPath);
  27570. };
  27571. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  27572. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27573. };
  27574. return Condition;
  27575. })();
  27576. BABYLON.Condition = Condition;
  27577. var ValueCondition = (function (_super) {
  27578. __extends(ValueCondition, _super);
  27579. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  27580. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  27581. _super.call(this, actionManager);
  27582. this.propertyPath = propertyPath;
  27583. this.value = value;
  27584. this.operator = operator;
  27585. this._target = this._getEffectiveTarget(target, this.propertyPath);
  27586. this._property = this._getProperty(this.propertyPath);
  27587. }
  27588. Object.defineProperty(ValueCondition, "IsEqual", {
  27589. get: function () {
  27590. return ValueCondition._IsEqual;
  27591. },
  27592. enumerable: true,
  27593. configurable: true
  27594. });
  27595. Object.defineProperty(ValueCondition, "IsDifferent", {
  27596. get: function () {
  27597. return ValueCondition._IsDifferent;
  27598. },
  27599. enumerable: true,
  27600. configurable: true
  27601. });
  27602. Object.defineProperty(ValueCondition, "IsGreater", {
  27603. get: function () {
  27604. return ValueCondition._IsGreater;
  27605. },
  27606. enumerable: true,
  27607. configurable: true
  27608. });
  27609. Object.defineProperty(ValueCondition, "IsLesser", {
  27610. get: function () {
  27611. return ValueCondition._IsLesser;
  27612. },
  27613. enumerable: true,
  27614. configurable: true
  27615. });
  27616. // Methods
  27617. ValueCondition.prototype.isValid = function () {
  27618. switch (this.operator) {
  27619. case ValueCondition.IsGreater:
  27620. return this._target[this._property] > this.value;
  27621. case ValueCondition.IsLesser:
  27622. return this._target[this._property] < this.value;
  27623. case ValueCondition.IsEqual:
  27624. case ValueCondition.IsDifferent:
  27625. var check;
  27626. if (this.value.equals) {
  27627. check = this.value.equals(this._target[this._property]);
  27628. }
  27629. else {
  27630. check = this.value === this._target[this._property];
  27631. }
  27632. return this.operator === ValueCondition.IsEqual ? check : !check;
  27633. }
  27634. return false;
  27635. };
  27636. // Statics
  27637. ValueCondition._IsEqual = 0;
  27638. ValueCondition._IsDifferent = 1;
  27639. ValueCondition._IsGreater = 2;
  27640. ValueCondition._IsLesser = 3;
  27641. return ValueCondition;
  27642. })(Condition);
  27643. BABYLON.ValueCondition = ValueCondition;
  27644. var PredicateCondition = (function (_super) {
  27645. __extends(PredicateCondition, _super);
  27646. function PredicateCondition(actionManager, predicate) {
  27647. _super.call(this, actionManager);
  27648. this.predicate = predicate;
  27649. }
  27650. PredicateCondition.prototype.isValid = function () {
  27651. return this.predicate();
  27652. };
  27653. return PredicateCondition;
  27654. })(Condition);
  27655. BABYLON.PredicateCondition = PredicateCondition;
  27656. var StateCondition = (function (_super) {
  27657. __extends(StateCondition, _super);
  27658. function StateCondition(actionManager, target, value) {
  27659. _super.call(this, actionManager);
  27660. this.value = value;
  27661. this._target = target;
  27662. }
  27663. // Methods
  27664. StateCondition.prototype.isValid = function () {
  27665. return this._target.state === this.value;
  27666. };
  27667. return StateCondition;
  27668. })(Condition);
  27669. BABYLON.StateCondition = StateCondition;
  27670. })(BABYLON || (BABYLON = {}));
  27671. var BABYLON;
  27672. (function (BABYLON) {
  27673. var Action = (function () {
  27674. function Action(triggerOptions, condition) {
  27675. this.triggerOptions = triggerOptions;
  27676. if (triggerOptions.parameter) {
  27677. this.trigger = triggerOptions.trigger;
  27678. this._triggerParameter = triggerOptions.parameter;
  27679. }
  27680. else {
  27681. this.trigger = triggerOptions;
  27682. }
  27683. this._nextActiveAction = this;
  27684. this._condition = condition;
  27685. }
  27686. // Methods
  27687. Action.prototype._prepare = function () {
  27688. };
  27689. Action.prototype.getTriggerParameter = function () {
  27690. return this._triggerParameter;
  27691. };
  27692. Action.prototype._executeCurrent = function (evt) {
  27693. if (this._nextActiveAction._condition) {
  27694. var condition = this._nextActiveAction._condition;
  27695. var currentRenderId = this._actionManager.getScene().getRenderId();
  27696. // We cache the current evaluation for the current frame
  27697. if (condition._evaluationId === currentRenderId) {
  27698. if (!condition._currentResult) {
  27699. return;
  27700. }
  27701. }
  27702. else {
  27703. condition._evaluationId = currentRenderId;
  27704. if (!condition.isValid()) {
  27705. condition._currentResult = false;
  27706. return;
  27707. }
  27708. condition._currentResult = true;
  27709. }
  27710. }
  27711. this._nextActiveAction.execute(evt);
  27712. if (this._nextActiveAction._child) {
  27713. if (!this._nextActiveAction._child._actionManager) {
  27714. this._nextActiveAction._child._actionManager = this._actionManager;
  27715. }
  27716. this._nextActiveAction = this._nextActiveAction._child;
  27717. }
  27718. else {
  27719. this._nextActiveAction = this;
  27720. }
  27721. };
  27722. Action.prototype.execute = function (evt) {
  27723. };
  27724. Action.prototype.then = function (action) {
  27725. this._child = action;
  27726. action._actionManager = this._actionManager;
  27727. action._prepare();
  27728. return action;
  27729. };
  27730. Action.prototype._getProperty = function (propertyPath) {
  27731. return this._actionManager._getProperty(propertyPath);
  27732. };
  27733. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  27734. return this._actionManager._getEffectiveTarget(target, propertyPath);
  27735. };
  27736. return Action;
  27737. })();
  27738. BABYLON.Action = Action;
  27739. })(BABYLON || (BABYLON = {}));
  27740. var BABYLON;
  27741. (function (BABYLON) {
  27742. /**
  27743. * ActionEvent is the event beint sent when an action is triggered.
  27744. */
  27745. var ActionEvent = (function () {
  27746. /**
  27747. * @constructor
  27748. * @param source The mesh that triggered the action.
  27749. * @param pointerX the X mouse cursor position at the time of the event
  27750. * @param pointerY the Y mouse cursor position at the time of the event
  27751. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  27752. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  27753. */
  27754. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  27755. this.source = source;
  27756. this.pointerX = pointerX;
  27757. this.pointerY = pointerY;
  27758. this.meshUnderPointer = meshUnderPointer;
  27759. this.sourceEvent = sourceEvent;
  27760. this.additionalData = additionalData;
  27761. }
  27762. /**
  27763. * Helper function to auto-create an ActionEvent from a source mesh.
  27764. * @param source the source mesh that triggered the event
  27765. * @param evt {Event} The original (browser) event
  27766. */
  27767. ActionEvent.CreateNew = function (source, evt, additionalData) {
  27768. var scene = source.getScene();
  27769. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  27770. };
  27771. /**
  27772. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  27773. * @param scene the scene where the event occurred
  27774. * @param evt {Event} The original (browser) event
  27775. */
  27776. ActionEvent.CreateNewFromScene = function (scene, evt) {
  27777. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  27778. };
  27779. return ActionEvent;
  27780. })();
  27781. BABYLON.ActionEvent = ActionEvent;
  27782. /**
  27783. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  27784. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  27785. */
  27786. var ActionManager = (function () {
  27787. function ActionManager(scene) {
  27788. // Members
  27789. this.actions = new Array();
  27790. this._scene = scene;
  27791. scene._actionManagers.push(this);
  27792. }
  27793. Object.defineProperty(ActionManager, "NothingTrigger", {
  27794. get: function () {
  27795. return ActionManager._NothingTrigger;
  27796. },
  27797. enumerable: true,
  27798. configurable: true
  27799. });
  27800. Object.defineProperty(ActionManager, "OnPickTrigger", {
  27801. get: function () {
  27802. return ActionManager._OnPickTrigger;
  27803. },
  27804. enumerable: true,
  27805. configurable: true
  27806. });
  27807. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  27808. get: function () {
  27809. return ActionManager._OnLeftPickTrigger;
  27810. },
  27811. enumerable: true,
  27812. configurable: true
  27813. });
  27814. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  27815. get: function () {
  27816. return ActionManager._OnRightPickTrigger;
  27817. },
  27818. enumerable: true,
  27819. configurable: true
  27820. });
  27821. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  27822. get: function () {
  27823. return ActionManager._OnCenterPickTrigger;
  27824. },
  27825. enumerable: true,
  27826. configurable: true
  27827. });
  27828. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  27829. get: function () {
  27830. return ActionManager._OnPointerOverTrigger;
  27831. },
  27832. enumerable: true,
  27833. configurable: true
  27834. });
  27835. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  27836. get: function () {
  27837. return ActionManager._OnPointerOutTrigger;
  27838. },
  27839. enumerable: true,
  27840. configurable: true
  27841. });
  27842. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  27843. get: function () {
  27844. return ActionManager._OnEveryFrameTrigger;
  27845. },
  27846. enumerable: true,
  27847. configurable: true
  27848. });
  27849. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  27850. get: function () {
  27851. return ActionManager._OnIntersectionEnterTrigger;
  27852. },
  27853. enumerable: true,
  27854. configurable: true
  27855. });
  27856. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  27857. get: function () {
  27858. return ActionManager._OnIntersectionExitTrigger;
  27859. },
  27860. enumerable: true,
  27861. configurable: true
  27862. });
  27863. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  27864. get: function () {
  27865. return ActionManager._OnKeyDownTrigger;
  27866. },
  27867. enumerable: true,
  27868. configurable: true
  27869. });
  27870. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  27871. get: function () {
  27872. return ActionManager._OnKeyUpTrigger;
  27873. },
  27874. enumerable: true,
  27875. configurable: true
  27876. });
  27877. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  27878. get: function () {
  27879. return ActionManager._OnPickUpTrigger;
  27880. },
  27881. enumerable: true,
  27882. configurable: true
  27883. });
  27884. // Methods
  27885. ActionManager.prototype.dispose = function () {
  27886. var index = this._scene._actionManagers.indexOf(this);
  27887. if (index > -1) {
  27888. this._scene._actionManagers.splice(index, 1);
  27889. }
  27890. };
  27891. ActionManager.prototype.getScene = function () {
  27892. return this._scene;
  27893. };
  27894. /**
  27895. * Does this action manager handles actions of any of the given triggers
  27896. * @param {number[]} triggers - the triggers to be tested
  27897. * @return {boolean} whether one (or more) of the triggers is handeled
  27898. */
  27899. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  27900. for (var index = 0; index < this.actions.length; index++) {
  27901. var action = this.actions[index];
  27902. if (triggers.indexOf(action.trigger) > -1) {
  27903. return true;
  27904. }
  27905. }
  27906. return false;
  27907. };
  27908. /**
  27909. * Does this action manager handles actions of a given trigger
  27910. * @param {number} trigger - the trigger to be tested
  27911. * @return {boolean} whether the trigger is handeled
  27912. */
  27913. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  27914. for (var index = 0; index < this.actions.length; index++) {
  27915. var action = this.actions[index];
  27916. if (action.trigger === trigger) {
  27917. return true;
  27918. }
  27919. }
  27920. return false;
  27921. };
  27922. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  27923. /**
  27924. * Does this action manager has pointer triggers
  27925. * @return {boolean} whether or not it has pointer triggers
  27926. */
  27927. get: function () {
  27928. for (var index = 0; index < this.actions.length; index++) {
  27929. var action = this.actions[index];
  27930. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  27931. return true;
  27932. }
  27933. if (action.trigger == ActionManager._OnPickUpTrigger) {
  27934. return true;
  27935. }
  27936. }
  27937. return false;
  27938. },
  27939. enumerable: true,
  27940. configurable: true
  27941. });
  27942. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  27943. /**
  27944. * Does this action manager has pick triggers
  27945. * @return {boolean} whether or not it has pick triggers
  27946. */
  27947. get: function () {
  27948. for (var index = 0; index < this.actions.length; index++) {
  27949. var action = this.actions[index];
  27950. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  27951. return true;
  27952. }
  27953. }
  27954. return false;
  27955. },
  27956. enumerable: true,
  27957. configurable: true
  27958. });
  27959. /**
  27960. * Registers an action to this action manager
  27961. * @param {BABYLON.Action} action - the action to be registered
  27962. * @return {BABYLON.Action} the action amended (prepared) after registration
  27963. */
  27964. ActionManager.prototype.registerAction = function (action) {
  27965. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  27966. if (this.getScene().actionManager !== this) {
  27967. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  27968. return null;
  27969. }
  27970. }
  27971. this.actions.push(action);
  27972. action._actionManager = this;
  27973. action._prepare();
  27974. return action;
  27975. };
  27976. /**
  27977. * Process a specific trigger
  27978. * @param {number} trigger - the trigger to process
  27979. * @param evt {BABYLON.ActionEvent} the event details to be processed
  27980. */
  27981. ActionManager.prototype.processTrigger = function (trigger, evt) {
  27982. for (var index = 0; index < this.actions.length; index++) {
  27983. var action = this.actions[index];
  27984. if (action.trigger === trigger) {
  27985. if (trigger === ActionManager.OnKeyUpTrigger
  27986. || trigger === ActionManager.OnKeyDownTrigger) {
  27987. var parameter = action.getTriggerParameter();
  27988. if (parameter) {
  27989. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  27990. var actualkey = String.fromCharCode(unicode).toLowerCase();
  27991. if (actualkey !== parameter.toLowerCase()) {
  27992. continue;
  27993. }
  27994. }
  27995. }
  27996. action._executeCurrent(evt);
  27997. }
  27998. }
  27999. };
  28000. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  28001. var properties = propertyPath.split(".");
  28002. for (var index = 0; index < properties.length - 1; index++) {
  28003. target = target[properties[index]];
  28004. }
  28005. return target;
  28006. };
  28007. ActionManager.prototype._getProperty = function (propertyPath) {
  28008. var properties = propertyPath.split(".");
  28009. return properties[properties.length - 1];
  28010. };
  28011. // Statics
  28012. ActionManager._NothingTrigger = 0;
  28013. ActionManager._OnPickTrigger = 1;
  28014. ActionManager._OnLeftPickTrigger = 2;
  28015. ActionManager._OnRightPickTrigger = 3;
  28016. ActionManager._OnCenterPickTrigger = 4;
  28017. ActionManager._OnPointerOverTrigger = 5;
  28018. ActionManager._OnPointerOutTrigger = 6;
  28019. ActionManager._OnEveryFrameTrigger = 7;
  28020. ActionManager._OnIntersectionEnterTrigger = 8;
  28021. ActionManager._OnIntersectionExitTrigger = 9;
  28022. ActionManager._OnKeyDownTrigger = 10;
  28023. ActionManager._OnKeyUpTrigger = 11;
  28024. ActionManager._OnPickUpTrigger = 12;
  28025. return ActionManager;
  28026. })();
  28027. BABYLON.ActionManager = ActionManager;
  28028. })(BABYLON || (BABYLON = {}));
  28029. var BABYLON;
  28030. (function (BABYLON) {
  28031. var InterpolateValueAction = (function (_super) {
  28032. __extends(InterpolateValueAction, _super);
  28033. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  28034. if (duration === void 0) { duration = 1000; }
  28035. _super.call(this, triggerOptions, condition);
  28036. this.propertyPath = propertyPath;
  28037. this.value = value;
  28038. this.duration = duration;
  28039. this.stopOtherAnimations = stopOtherAnimations;
  28040. this._target = target;
  28041. }
  28042. InterpolateValueAction.prototype._prepare = function () {
  28043. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28044. this._property = this._getProperty(this.propertyPath);
  28045. };
  28046. InterpolateValueAction.prototype.execute = function () {
  28047. var scene = this._actionManager.getScene();
  28048. var keys = [
  28049. {
  28050. frame: 0,
  28051. value: this._target[this._property]
  28052. }, {
  28053. frame: 100,
  28054. value: this.value
  28055. }
  28056. ];
  28057. var dataType;
  28058. if (typeof this.value === "number") {
  28059. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  28060. }
  28061. else if (this.value instanceof BABYLON.Color3) {
  28062. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  28063. }
  28064. else if (this.value instanceof BABYLON.Vector3) {
  28065. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  28066. }
  28067. else if (this.value instanceof BABYLON.Matrix) {
  28068. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  28069. }
  28070. else if (this.value instanceof BABYLON.Quaternion) {
  28071. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  28072. }
  28073. else {
  28074. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  28075. return;
  28076. }
  28077. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  28078. animation.setKeys(keys);
  28079. if (this.stopOtherAnimations) {
  28080. scene.stopAnimation(this._target);
  28081. }
  28082. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  28083. };
  28084. return InterpolateValueAction;
  28085. })(BABYLON.Action);
  28086. BABYLON.InterpolateValueAction = InterpolateValueAction;
  28087. })(BABYLON || (BABYLON = {}));
  28088. var BABYLON;
  28089. (function (BABYLON) {
  28090. var SwitchBooleanAction = (function (_super) {
  28091. __extends(SwitchBooleanAction, _super);
  28092. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  28093. _super.call(this, triggerOptions, condition);
  28094. this.propertyPath = propertyPath;
  28095. this._target = target;
  28096. }
  28097. SwitchBooleanAction.prototype._prepare = function () {
  28098. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28099. this._property = this._getProperty(this.propertyPath);
  28100. };
  28101. SwitchBooleanAction.prototype.execute = function () {
  28102. this._target[this._property] = !this._target[this._property];
  28103. };
  28104. return SwitchBooleanAction;
  28105. })(BABYLON.Action);
  28106. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  28107. var SetStateAction = (function (_super) {
  28108. __extends(SetStateAction, _super);
  28109. function SetStateAction(triggerOptions, target, value, condition) {
  28110. _super.call(this, triggerOptions, condition);
  28111. this.value = value;
  28112. this._target = target;
  28113. }
  28114. SetStateAction.prototype.execute = function () {
  28115. this._target.state = this.value;
  28116. };
  28117. return SetStateAction;
  28118. })(BABYLON.Action);
  28119. BABYLON.SetStateAction = SetStateAction;
  28120. var SetValueAction = (function (_super) {
  28121. __extends(SetValueAction, _super);
  28122. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  28123. _super.call(this, triggerOptions, condition);
  28124. this.propertyPath = propertyPath;
  28125. this.value = value;
  28126. this._target = target;
  28127. }
  28128. SetValueAction.prototype._prepare = function () {
  28129. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28130. this._property = this._getProperty(this.propertyPath);
  28131. };
  28132. SetValueAction.prototype.execute = function () {
  28133. this._target[this._property] = this.value;
  28134. };
  28135. return SetValueAction;
  28136. })(BABYLON.Action);
  28137. BABYLON.SetValueAction = SetValueAction;
  28138. var IncrementValueAction = (function (_super) {
  28139. __extends(IncrementValueAction, _super);
  28140. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  28141. _super.call(this, triggerOptions, condition);
  28142. this.propertyPath = propertyPath;
  28143. this.value = value;
  28144. this._target = target;
  28145. }
  28146. IncrementValueAction.prototype._prepare = function () {
  28147. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  28148. this._property = this._getProperty(this.propertyPath);
  28149. if (typeof this._target[this._property] !== "number") {
  28150. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  28151. }
  28152. };
  28153. IncrementValueAction.prototype.execute = function () {
  28154. this._target[this._property] += this.value;
  28155. };
  28156. return IncrementValueAction;
  28157. })(BABYLON.Action);
  28158. BABYLON.IncrementValueAction = IncrementValueAction;
  28159. var PlayAnimationAction = (function (_super) {
  28160. __extends(PlayAnimationAction, _super);
  28161. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  28162. _super.call(this, triggerOptions, condition);
  28163. this.from = from;
  28164. this.to = to;
  28165. this.loop = loop;
  28166. this._target = target;
  28167. }
  28168. PlayAnimationAction.prototype._prepare = function () {
  28169. };
  28170. PlayAnimationAction.prototype.execute = function () {
  28171. var scene = this._actionManager.getScene();
  28172. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  28173. };
  28174. return PlayAnimationAction;
  28175. })(BABYLON.Action);
  28176. BABYLON.PlayAnimationAction = PlayAnimationAction;
  28177. var StopAnimationAction = (function (_super) {
  28178. __extends(StopAnimationAction, _super);
  28179. function StopAnimationAction(triggerOptions, target, condition) {
  28180. _super.call(this, triggerOptions, condition);
  28181. this._target = target;
  28182. }
  28183. StopAnimationAction.prototype._prepare = function () {
  28184. };
  28185. StopAnimationAction.prototype.execute = function () {
  28186. var scene = this._actionManager.getScene();
  28187. scene.stopAnimation(this._target);
  28188. };
  28189. return StopAnimationAction;
  28190. })(BABYLON.Action);
  28191. BABYLON.StopAnimationAction = StopAnimationAction;
  28192. var DoNothingAction = (function (_super) {
  28193. __extends(DoNothingAction, _super);
  28194. function DoNothingAction(triggerOptions, condition) {
  28195. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  28196. _super.call(this, triggerOptions, condition);
  28197. }
  28198. DoNothingAction.prototype.execute = function () {
  28199. };
  28200. return DoNothingAction;
  28201. })(BABYLON.Action);
  28202. BABYLON.DoNothingAction = DoNothingAction;
  28203. var CombineAction = (function (_super) {
  28204. __extends(CombineAction, _super);
  28205. function CombineAction(triggerOptions, children, condition) {
  28206. _super.call(this, triggerOptions, condition);
  28207. this.children = children;
  28208. }
  28209. CombineAction.prototype._prepare = function () {
  28210. for (var index = 0; index < this.children.length; index++) {
  28211. this.children[index]._actionManager = this._actionManager;
  28212. this.children[index]._prepare();
  28213. }
  28214. };
  28215. CombineAction.prototype.execute = function (evt) {
  28216. for (var index = 0; index < this.children.length; index++) {
  28217. this.children[index].execute(evt);
  28218. }
  28219. };
  28220. return CombineAction;
  28221. })(BABYLON.Action);
  28222. BABYLON.CombineAction = CombineAction;
  28223. var ExecuteCodeAction = (function (_super) {
  28224. __extends(ExecuteCodeAction, _super);
  28225. function ExecuteCodeAction(triggerOptions, func, condition) {
  28226. _super.call(this, triggerOptions, condition);
  28227. this.func = func;
  28228. }
  28229. ExecuteCodeAction.prototype.execute = function (evt) {
  28230. this.func(evt);
  28231. };
  28232. return ExecuteCodeAction;
  28233. })(BABYLON.Action);
  28234. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  28235. var SetParentAction = (function (_super) {
  28236. __extends(SetParentAction, _super);
  28237. function SetParentAction(triggerOptions, target, parent, condition) {
  28238. _super.call(this, triggerOptions, condition);
  28239. this._target = target;
  28240. this._parent = parent;
  28241. }
  28242. SetParentAction.prototype._prepare = function () {
  28243. };
  28244. SetParentAction.prototype.execute = function () {
  28245. if (this._target.parent === this._parent) {
  28246. return;
  28247. }
  28248. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  28249. invertParentWorldMatrix.invert();
  28250. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  28251. this._target.parent = this._parent;
  28252. };
  28253. return SetParentAction;
  28254. })(BABYLON.Action);
  28255. BABYLON.SetParentAction = SetParentAction;
  28256. var PlaySoundAction = (function (_super) {
  28257. __extends(PlaySoundAction, _super);
  28258. function PlaySoundAction(triggerOptions, sound, condition) {
  28259. _super.call(this, triggerOptions, condition);
  28260. this._sound = sound;
  28261. }
  28262. PlaySoundAction.prototype._prepare = function () {
  28263. };
  28264. PlaySoundAction.prototype.execute = function () {
  28265. if (this._sound !== undefined)
  28266. this._sound.play();
  28267. };
  28268. return PlaySoundAction;
  28269. })(BABYLON.Action);
  28270. BABYLON.PlaySoundAction = PlaySoundAction;
  28271. var StopSoundAction = (function (_super) {
  28272. __extends(StopSoundAction, _super);
  28273. function StopSoundAction(triggerOptions, sound, condition) {
  28274. _super.call(this, triggerOptions, condition);
  28275. this._sound = sound;
  28276. }
  28277. StopSoundAction.prototype._prepare = function () {
  28278. };
  28279. StopSoundAction.prototype.execute = function () {
  28280. if (this._sound !== undefined)
  28281. this._sound.stop();
  28282. };
  28283. return StopSoundAction;
  28284. })(BABYLON.Action);
  28285. BABYLON.StopSoundAction = StopSoundAction;
  28286. })(BABYLON || (BABYLON = {}));
  28287. var BABYLON;
  28288. (function (BABYLON) {
  28289. var Geometry = (function () {
  28290. function Geometry(id, scene, vertexData, updatable, mesh) {
  28291. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28292. this._totalVertices = 0;
  28293. this._indices = [];
  28294. this._isDisposed = false;
  28295. this.id = id;
  28296. this._engine = scene.getEngine();
  28297. this._meshes = [];
  28298. this._scene = scene;
  28299. // vertexData
  28300. if (vertexData) {
  28301. this.setAllVerticesData(vertexData, updatable);
  28302. }
  28303. else {
  28304. this._totalVertices = 0;
  28305. this._indices = [];
  28306. }
  28307. // applyToMesh
  28308. if (mesh) {
  28309. this.applyToMesh(mesh);
  28310. mesh.computeWorldMatrix(true);
  28311. }
  28312. }
  28313. Geometry.prototype.getScene = function () {
  28314. return this._scene;
  28315. };
  28316. Geometry.prototype.getEngine = function () {
  28317. return this._engine;
  28318. };
  28319. Geometry.prototype.isReady = function () {
  28320. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28321. };
  28322. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28323. vertexData.applyToGeometry(this, updatable);
  28324. this.notifyUpdate();
  28325. };
  28326. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28327. this._vertexBuffers = this._vertexBuffers || {};
  28328. if (this._vertexBuffers[kind]) {
  28329. this._vertexBuffers[kind].dispose();
  28330. }
  28331. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28332. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28333. stride = this._vertexBuffers[kind].getStrideSize();
  28334. this._totalVertices = data.length / stride;
  28335. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28336. var meshes = this._meshes;
  28337. var numOfMeshes = meshes.length;
  28338. for (var index = 0; index < numOfMeshes; index++) {
  28339. var mesh = meshes[index];
  28340. mesh._resetPointsArrayCache();
  28341. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28342. mesh._createGlobalSubMesh();
  28343. mesh.computeWorldMatrix(true);
  28344. }
  28345. }
  28346. this.notifyUpdate(kind);
  28347. };
  28348. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28349. var vertexBuffer = this.getVertexBuffer(kind);
  28350. if (!vertexBuffer) {
  28351. return;
  28352. }
  28353. vertexBuffer.updateDirectly(data, offset);
  28354. this.notifyUpdate(kind);
  28355. };
  28356. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28357. var vertexBuffer = this.getVertexBuffer(kind);
  28358. if (!vertexBuffer) {
  28359. return;
  28360. }
  28361. vertexBuffer.update(data);
  28362. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28363. var extend;
  28364. var stride = vertexBuffer.getStrideSize();
  28365. this._totalVertices = data.length / stride;
  28366. if (updateExtends) {
  28367. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  28368. }
  28369. var meshes = this._meshes;
  28370. var numOfMeshes = meshes.length;
  28371. for (var index = 0; index < numOfMeshes; index++) {
  28372. var mesh = meshes[index];
  28373. mesh._resetPointsArrayCache();
  28374. if (updateExtends) {
  28375. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28376. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28377. var subMesh = mesh.subMeshes[subIndex];
  28378. subMesh.refreshBoundingInfo();
  28379. }
  28380. }
  28381. }
  28382. }
  28383. this.notifyUpdate(kind);
  28384. };
  28385. Geometry.prototype.getTotalVertices = function () {
  28386. if (!this.isReady()) {
  28387. return 0;
  28388. }
  28389. return this._totalVertices;
  28390. };
  28391. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  28392. var vertexBuffer = this.getVertexBuffer(kind);
  28393. if (!vertexBuffer) {
  28394. return null;
  28395. }
  28396. var orig = vertexBuffer.getData();
  28397. if (!copyWhenShared || this._meshes.length === 1) {
  28398. return orig;
  28399. }
  28400. else {
  28401. var len = orig.length;
  28402. var copy = [];
  28403. for (var i = 0; i < len; i++) {
  28404. copy.push(orig[i]);
  28405. }
  28406. return copy;
  28407. }
  28408. };
  28409. Geometry.prototype.getVertexBuffer = function (kind) {
  28410. if (!this.isReady()) {
  28411. return null;
  28412. }
  28413. return this._vertexBuffers[kind];
  28414. };
  28415. Geometry.prototype.getVertexBuffers = function () {
  28416. if (!this.isReady()) {
  28417. return null;
  28418. }
  28419. return this._vertexBuffers;
  28420. };
  28421. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28422. if (!this._vertexBuffers) {
  28423. if (this._delayInfo) {
  28424. return this._delayInfo.indexOf(kind) !== -1;
  28425. }
  28426. return false;
  28427. }
  28428. return this._vertexBuffers[kind] !== undefined;
  28429. };
  28430. Geometry.prototype.getVerticesDataKinds = function () {
  28431. var result = [];
  28432. if (!this._vertexBuffers && this._delayInfo) {
  28433. for (var kind in this._delayInfo) {
  28434. result.push(kind);
  28435. }
  28436. }
  28437. else {
  28438. for (kind in this._vertexBuffers) {
  28439. result.push(kind);
  28440. }
  28441. }
  28442. return result;
  28443. };
  28444. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28445. if (this._indexBuffer) {
  28446. this._engine._releaseBuffer(this._indexBuffer);
  28447. }
  28448. this._indices = indices;
  28449. if (this._meshes.length !== 0 && this._indices) {
  28450. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28451. }
  28452. if (totalVertices !== undefined) {
  28453. this._totalVertices = totalVertices;
  28454. }
  28455. var meshes = this._meshes;
  28456. var numOfMeshes = meshes.length;
  28457. for (var index = 0; index < numOfMeshes; index++) {
  28458. meshes[index]._createGlobalSubMesh();
  28459. }
  28460. this.notifyUpdate();
  28461. };
  28462. Geometry.prototype.getTotalIndices = function () {
  28463. if (!this.isReady()) {
  28464. return 0;
  28465. }
  28466. return this._indices.length;
  28467. };
  28468. Geometry.prototype.getIndices = function (copyWhenShared) {
  28469. if (!this.isReady()) {
  28470. return null;
  28471. }
  28472. var orig = this._indices;
  28473. if (!copyWhenShared || this._meshes.length === 1) {
  28474. return orig;
  28475. }
  28476. else {
  28477. var len = orig.length;
  28478. var copy = [];
  28479. for (var i = 0; i < len; i++) {
  28480. copy.push(orig[i]);
  28481. }
  28482. return copy;
  28483. }
  28484. };
  28485. Geometry.prototype.getIndexBuffer = function () {
  28486. if (!this.isReady()) {
  28487. return null;
  28488. }
  28489. return this._indexBuffer;
  28490. };
  28491. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28492. var meshes = this._meshes;
  28493. var index = meshes.indexOf(mesh);
  28494. if (index === -1) {
  28495. return;
  28496. }
  28497. for (var kind in this._vertexBuffers) {
  28498. this._vertexBuffers[kind].dispose();
  28499. }
  28500. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  28501. this._indexBuffer = null;
  28502. }
  28503. meshes.splice(index, 1);
  28504. mesh._geometry = null;
  28505. if (meshes.length === 0 && shouldDispose) {
  28506. this.dispose();
  28507. }
  28508. };
  28509. Geometry.prototype.applyToMesh = function (mesh) {
  28510. if (mesh._geometry === this) {
  28511. return;
  28512. }
  28513. var previousGeometry = mesh._geometry;
  28514. if (previousGeometry) {
  28515. previousGeometry.releaseForMesh(mesh);
  28516. }
  28517. var meshes = this._meshes;
  28518. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28519. mesh._geometry = this;
  28520. this._scene.pushGeometry(this);
  28521. meshes.push(mesh);
  28522. if (this.isReady()) {
  28523. this._applyToMesh(mesh);
  28524. }
  28525. else {
  28526. mesh._boundingInfo = this._boundingInfo;
  28527. }
  28528. };
  28529. Geometry.prototype._applyToMesh = function (mesh) {
  28530. var numOfMeshes = this._meshes.length;
  28531. // vertexBuffers
  28532. for (var kind in this._vertexBuffers) {
  28533. if (numOfMeshes === 1) {
  28534. this._vertexBuffers[kind].create();
  28535. }
  28536. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  28537. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28538. mesh._resetPointsArrayCache();
  28539. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  28540. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28541. mesh._createGlobalSubMesh();
  28542. //bounding info was just created again, world matrix should be applied again.
  28543. mesh._updateBoundingInfo();
  28544. }
  28545. }
  28546. // indexBuffer
  28547. if (numOfMeshes === 1 && this._indices) {
  28548. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28549. }
  28550. if (this._indexBuffer) {
  28551. this._indexBuffer.references = numOfMeshes;
  28552. }
  28553. };
  28554. Geometry.prototype.notifyUpdate = function (kind) {
  28555. if (this.onGeometryUpdated) {
  28556. this.onGeometryUpdated(this, kind);
  28557. }
  28558. };
  28559. Geometry.prototype.load = function (scene, onLoaded) {
  28560. var _this = this;
  28561. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28562. return;
  28563. }
  28564. if (this.isReady()) {
  28565. if (onLoaded) {
  28566. onLoaded();
  28567. }
  28568. return;
  28569. }
  28570. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28571. scene._addPendingData(this);
  28572. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28573. _this._delayLoadingFunction(JSON.parse(data), _this);
  28574. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28575. _this._delayInfo = [];
  28576. scene._removePendingData(_this);
  28577. var meshes = _this._meshes;
  28578. var numOfMeshes = meshes.length;
  28579. for (var index = 0; index < numOfMeshes; index++) {
  28580. _this._applyToMesh(meshes[index]);
  28581. }
  28582. if (onLoaded) {
  28583. onLoaded();
  28584. }
  28585. }, function () { }, scene.database);
  28586. };
  28587. Geometry.prototype.isDisposed = function () {
  28588. return this._isDisposed;
  28589. };
  28590. Geometry.prototype.dispose = function () {
  28591. var meshes = this._meshes;
  28592. var numOfMeshes = meshes.length;
  28593. var index;
  28594. for (index = 0; index < numOfMeshes; index++) {
  28595. this.releaseForMesh(meshes[index]);
  28596. }
  28597. this._meshes = [];
  28598. for (var kind in this._vertexBuffers) {
  28599. this._vertexBuffers[kind].dispose();
  28600. }
  28601. this._vertexBuffers = [];
  28602. this._totalVertices = 0;
  28603. if (this._indexBuffer) {
  28604. this._engine._releaseBuffer(this._indexBuffer);
  28605. }
  28606. this._indexBuffer = null;
  28607. this._indices = [];
  28608. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28609. this.delayLoadingFile = null;
  28610. this._delayLoadingFunction = null;
  28611. this._delayInfo = [];
  28612. this._boundingInfo = null; // todo: .dispose()
  28613. this._scene.removeGeometry(this);
  28614. this._isDisposed = true;
  28615. };
  28616. Geometry.prototype.copy = function (id) {
  28617. var vertexData = new BABYLON.VertexData();
  28618. vertexData.indices = [];
  28619. var indices = this.getIndices();
  28620. for (var index = 0; index < indices.length; index++) {
  28621. vertexData.indices.push(indices[index]);
  28622. }
  28623. var updatable = false;
  28624. var stopChecking = false;
  28625. for (var kind in this._vertexBuffers) {
  28626. // using slice() to make a copy of the array and not just reference it
  28627. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  28628. if (!stopChecking) {
  28629. updatable = this.getVertexBuffer(kind).isUpdatable();
  28630. stopChecking = !updatable;
  28631. }
  28632. }
  28633. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28634. geometry.delayLoadState = this.delayLoadState;
  28635. geometry.delayLoadingFile = this.delayLoadingFile;
  28636. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28637. for (kind in this._delayInfo) {
  28638. geometry._delayInfo = geometry._delayInfo || [];
  28639. geometry._delayInfo.push(kind);
  28640. }
  28641. // Bounding info
  28642. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  28643. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28644. return geometry;
  28645. };
  28646. // Statics
  28647. Geometry.ExtractFromMesh = function (mesh, id) {
  28648. var geometry = mesh._geometry;
  28649. if (!geometry) {
  28650. return null;
  28651. }
  28652. return geometry.copy(id);
  28653. };
  28654. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  28655. // be aware Math.random() could cause collisions
  28656. Geometry.RandomId = function () {
  28657. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  28658. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  28659. return v.toString(16);
  28660. });
  28661. };
  28662. return Geometry;
  28663. })();
  28664. BABYLON.Geometry = Geometry;
  28665. /////// Primitives //////////////////////////////////////////////
  28666. var Geometry;
  28667. (function (Geometry) {
  28668. var Primitives;
  28669. (function (Primitives) {
  28670. /// Abstract class
  28671. var _Primitive = (function (_super) {
  28672. __extends(_Primitive, _super);
  28673. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  28674. this._beingRegenerated = true;
  28675. this._canBeRegenerated = canBeRegenerated;
  28676. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  28677. this._beingRegenerated = false;
  28678. }
  28679. _Primitive.prototype.canBeRegenerated = function () {
  28680. return this._canBeRegenerated;
  28681. };
  28682. _Primitive.prototype.regenerate = function () {
  28683. if (!this._canBeRegenerated) {
  28684. return;
  28685. }
  28686. this._beingRegenerated = true;
  28687. this.setAllVerticesData(this._regenerateVertexData(), false);
  28688. this._beingRegenerated = false;
  28689. };
  28690. _Primitive.prototype.asNewGeometry = function (id) {
  28691. return _super.prototype.copy.call(this, id);
  28692. };
  28693. // overrides
  28694. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  28695. if (!this._beingRegenerated) {
  28696. return;
  28697. }
  28698. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  28699. };
  28700. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  28701. if (!this._beingRegenerated) {
  28702. return;
  28703. }
  28704. _super.prototype.setVerticesData.call(this, kind, data, false);
  28705. };
  28706. // to override
  28707. // protected
  28708. _Primitive.prototype._regenerateVertexData = function () {
  28709. throw new Error("Abstract method");
  28710. };
  28711. _Primitive.prototype.copy = function (id) {
  28712. throw new Error("Must be overriden in sub-classes.");
  28713. };
  28714. return _Primitive;
  28715. })(Geometry);
  28716. Primitives._Primitive = _Primitive;
  28717. var Ribbon = (function (_super) {
  28718. __extends(Ribbon, _super);
  28719. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  28720. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28721. this.pathArray = pathArray;
  28722. this.closeArray = closeArray;
  28723. this.closePath = closePath;
  28724. this.offset = offset;
  28725. this.side = side;
  28726. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28727. }
  28728. Ribbon.prototype._regenerateVertexData = function () {
  28729. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  28730. };
  28731. Ribbon.prototype.copy = function (id) {
  28732. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  28733. };
  28734. return Ribbon;
  28735. })(_Primitive);
  28736. Primitives.Ribbon = Ribbon;
  28737. var Box = (function (_super) {
  28738. __extends(Box, _super);
  28739. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  28740. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28741. this.size = size;
  28742. this.side = side;
  28743. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28744. }
  28745. Box.prototype._regenerateVertexData = function () {
  28746. return BABYLON.VertexData.CreateBox(this.size, this.side);
  28747. };
  28748. Box.prototype.copy = function (id) {
  28749. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28750. };
  28751. return Box;
  28752. })(_Primitive);
  28753. Primitives.Box = Box;
  28754. var Sphere = (function (_super) {
  28755. __extends(Sphere, _super);
  28756. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  28757. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28758. this.segments = segments;
  28759. this.diameter = diameter;
  28760. this.side = side;
  28761. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28762. }
  28763. Sphere.prototype._regenerateVertexData = function () {
  28764. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  28765. };
  28766. Sphere.prototype.copy = function (id) {
  28767. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  28768. };
  28769. return Sphere;
  28770. })(_Primitive);
  28771. Primitives.Sphere = Sphere;
  28772. var Cylinder = (function (_super) {
  28773. __extends(Cylinder, _super);
  28774. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  28775. if (subdivisions === void 0) { subdivisions = 1; }
  28776. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28777. this.height = height;
  28778. this.diameterTop = diameterTop;
  28779. this.diameterBottom = diameterBottom;
  28780. this.tessellation = tessellation;
  28781. this.subdivisions = subdivisions;
  28782. this.side = side;
  28783. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28784. }
  28785. Cylinder.prototype._regenerateVertexData = function () {
  28786. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  28787. };
  28788. Cylinder.prototype.copy = function (id) {
  28789. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  28790. };
  28791. return Cylinder;
  28792. })(_Primitive);
  28793. Primitives.Cylinder = Cylinder;
  28794. var Torus = (function (_super) {
  28795. __extends(Torus, _super);
  28796. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  28797. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28798. this.diameter = diameter;
  28799. this.thickness = thickness;
  28800. this.tessellation = tessellation;
  28801. this.side = side;
  28802. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28803. }
  28804. Torus.prototype._regenerateVertexData = function () {
  28805. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  28806. };
  28807. Torus.prototype.copy = function (id) {
  28808. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  28809. };
  28810. return Torus;
  28811. })(_Primitive);
  28812. Primitives.Torus = Torus;
  28813. var Ground = (function (_super) {
  28814. __extends(Ground, _super);
  28815. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  28816. this.width = width;
  28817. this.height = height;
  28818. this.subdivisions = subdivisions;
  28819. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28820. }
  28821. Ground.prototype._regenerateVertexData = function () {
  28822. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  28823. };
  28824. Ground.prototype.copy = function (id) {
  28825. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  28826. };
  28827. return Ground;
  28828. })(_Primitive);
  28829. Primitives.Ground = Ground;
  28830. var TiledGround = (function (_super) {
  28831. __extends(TiledGround, _super);
  28832. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  28833. this.xmin = xmin;
  28834. this.zmin = zmin;
  28835. this.xmax = xmax;
  28836. this.zmax = zmax;
  28837. this.subdivisions = subdivisions;
  28838. this.precision = precision;
  28839. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28840. }
  28841. TiledGround.prototype._regenerateVertexData = function () {
  28842. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  28843. };
  28844. TiledGround.prototype.copy = function (id) {
  28845. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  28846. };
  28847. return TiledGround;
  28848. })(_Primitive);
  28849. Primitives.TiledGround = TiledGround;
  28850. var Plane = (function (_super) {
  28851. __extends(Plane, _super);
  28852. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  28853. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28854. this.size = size;
  28855. this.side = side;
  28856. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28857. }
  28858. Plane.prototype._regenerateVertexData = function () {
  28859. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  28860. };
  28861. Plane.prototype.copy = function (id) {
  28862. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  28863. };
  28864. return Plane;
  28865. })(_Primitive);
  28866. Primitives.Plane = Plane;
  28867. var TorusKnot = (function (_super) {
  28868. __extends(TorusKnot, _super);
  28869. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  28870. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  28871. this.radius = radius;
  28872. this.tube = tube;
  28873. this.radialSegments = radialSegments;
  28874. this.tubularSegments = tubularSegments;
  28875. this.p = p;
  28876. this.q = q;
  28877. this.side = side;
  28878. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  28879. }
  28880. TorusKnot.prototype._regenerateVertexData = function () {
  28881. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  28882. };
  28883. TorusKnot.prototype.copy = function (id) {
  28884. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  28885. };
  28886. return TorusKnot;
  28887. })(_Primitive);
  28888. Primitives.TorusKnot = TorusKnot;
  28889. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  28890. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  28891. })(BABYLON || (BABYLON = {}));
  28892. var BABYLON;
  28893. (function (BABYLON) {
  28894. var GroundMesh = (function (_super) {
  28895. __extends(GroundMesh, _super);
  28896. function GroundMesh(name, scene) {
  28897. _super.call(this, name, scene);
  28898. this.generateOctree = false;
  28899. this._worldInverse = new BABYLON.Matrix();
  28900. }
  28901. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  28902. get: function () {
  28903. return this._subdivisions;
  28904. },
  28905. enumerable: true,
  28906. configurable: true
  28907. });
  28908. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  28909. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  28910. this._subdivisions = chunksCount;
  28911. this.subdivide(this._subdivisions);
  28912. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  28913. };
  28914. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  28915. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  28916. this.getWorldMatrix().invertToRef(this._worldInverse);
  28917. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  28918. var pickInfo = this.intersects(ray);
  28919. if (pickInfo.hit) {
  28920. return pickInfo.pickedPoint.y;
  28921. }
  28922. return 0;
  28923. };
  28924. return GroundMesh;
  28925. })(BABYLON.Mesh);
  28926. BABYLON.GroundMesh = GroundMesh;
  28927. })(BABYLON || (BABYLON = {}));
  28928. var BABYLON;
  28929. (function (BABYLON) {
  28930. var LinesMesh = (function (_super) {
  28931. __extends(LinesMesh, _super);
  28932. function LinesMesh(name, scene, updatable) {
  28933. if (updatable === void 0) { updatable = false; }
  28934. _super.call(this, name, scene);
  28935. this.color = new BABYLON.Color3(1, 1, 1);
  28936. this.alpha = 1;
  28937. this._indices = new Array();
  28938. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  28939. attributes: ["position"],
  28940. uniforms: ["worldViewProjection", "color"],
  28941. needAlphaBlending: true
  28942. });
  28943. }
  28944. Object.defineProperty(LinesMesh.prototype, "material", {
  28945. get: function () {
  28946. return this._colorShader;
  28947. },
  28948. enumerable: true,
  28949. configurable: true
  28950. });
  28951. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  28952. get: function () {
  28953. return false;
  28954. },
  28955. enumerable: true,
  28956. configurable: true
  28957. });
  28958. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  28959. get: function () {
  28960. return false;
  28961. },
  28962. enumerable: true,
  28963. configurable: true
  28964. });
  28965. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  28966. var engine = this.getScene().getEngine();
  28967. var indexToBind = this._geometry.getIndexBuffer();
  28968. // VBOs
  28969. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  28970. // Color
  28971. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  28972. };
  28973. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  28974. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28975. return;
  28976. }
  28977. var engine = this.getScene().getEngine();
  28978. // Draw order
  28979. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  28980. };
  28981. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  28982. return null;
  28983. };
  28984. LinesMesh.prototype.dispose = function (doNotRecurse) {
  28985. this._colorShader.dispose();
  28986. _super.prototype.dispose.call(this, doNotRecurse);
  28987. };
  28988. return LinesMesh;
  28989. })(BABYLON.Mesh);
  28990. BABYLON.LinesMesh = LinesMesh;
  28991. })(BABYLON || (BABYLON = {}));
  28992. var BABYLON;
  28993. (function (BABYLON) {
  28994. var OutlineRenderer = (function () {
  28995. function OutlineRenderer(scene) {
  28996. this._scene = scene;
  28997. }
  28998. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  28999. var _this = this;
  29000. if (useOverlay === void 0) { useOverlay = false; }
  29001. var scene = this._scene;
  29002. var engine = this._scene.getEngine();
  29003. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  29004. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  29005. return;
  29006. }
  29007. var mesh = subMesh.getRenderingMesh();
  29008. var material = subMesh.getMaterial();
  29009. engine.enableEffect(this._effect);
  29010. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  29011. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  29012. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29013. // Bones
  29014. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29015. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29016. }
  29017. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  29018. // Alpha test
  29019. if (material && material.needAlphaTesting()) {
  29020. var alphaTexture = material.getAlphaTestTexture();
  29021. this._effect.setTexture("diffuseSampler", alphaTexture);
  29022. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29023. }
  29024. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  29025. };
  29026. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  29027. var defines = [];
  29028. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  29029. var mesh = subMesh.getMesh();
  29030. var material = subMesh.getMaterial();
  29031. // Alpha test
  29032. if (material && material.needAlphaTesting()) {
  29033. defines.push("#define ALPHATEST");
  29034. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29035. attribs.push(BABYLON.VertexBuffer.UVKind);
  29036. defines.push("#define UV1");
  29037. }
  29038. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29039. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29040. defines.push("#define UV2");
  29041. }
  29042. }
  29043. // Bones
  29044. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29045. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29046. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29047. defines.push("#define BONES");
  29048. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29049. }
  29050. // Instances
  29051. if (useInstances) {
  29052. defines.push("#define INSTANCES");
  29053. attribs.push("world0");
  29054. attribs.push("world1");
  29055. attribs.push("world2");
  29056. attribs.push("world3");
  29057. }
  29058. // Get correct effect
  29059. var join = defines.join("\n");
  29060. if (this._cachedDefines !== join) {
  29061. this._cachedDefines = join;
  29062. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  29063. }
  29064. return this._effect.isReady();
  29065. };
  29066. return OutlineRenderer;
  29067. })();
  29068. BABYLON.OutlineRenderer = OutlineRenderer;
  29069. })(BABYLON || (BABYLON = {}));
  29070. var BABYLON;
  29071. (function (BABYLON) {
  29072. var MeshAssetTask = (function () {
  29073. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  29074. this.name = name;
  29075. this.meshesNames = meshesNames;
  29076. this.rootUrl = rootUrl;
  29077. this.sceneFilename = sceneFilename;
  29078. this.isCompleted = false;
  29079. }
  29080. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29081. var _this = this;
  29082. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  29083. _this.loadedMeshes = meshes;
  29084. _this.loadedParticleSystems = particleSystems;
  29085. _this.loadedSkeletons = skeletons;
  29086. _this.isCompleted = true;
  29087. if (_this.onSuccess) {
  29088. _this.onSuccess(_this);
  29089. }
  29090. onSuccess();
  29091. }, null, function () {
  29092. if (_this.onError) {
  29093. _this.onError(_this);
  29094. }
  29095. onError();
  29096. });
  29097. };
  29098. return MeshAssetTask;
  29099. })();
  29100. BABYLON.MeshAssetTask = MeshAssetTask;
  29101. var TextFileAssetTask = (function () {
  29102. function TextFileAssetTask(name, url) {
  29103. this.name = name;
  29104. this.url = url;
  29105. this.isCompleted = false;
  29106. }
  29107. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29108. var _this = this;
  29109. BABYLON.Tools.LoadFile(this.url, function (data) {
  29110. _this.text = data;
  29111. _this.isCompleted = true;
  29112. if (_this.onSuccess) {
  29113. _this.onSuccess(_this);
  29114. }
  29115. onSuccess();
  29116. }, null, scene.database, false, function () {
  29117. if (_this.onError) {
  29118. _this.onError(_this);
  29119. }
  29120. onError();
  29121. });
  29122. };
  29123. return TextFileAssetTask;
  29124. })();
  29125. BABYLON.TextFileAssetTask = TextFileAssetTask;
  29126. var BinaryFileAssetTask = (function () {
  29127. function BinaryFileAssetTask(name, url) {
  29128. this.name = name;
  29129. this.url = url;
  29130. this.isCompleted = false;
  29131. }
  29132. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29133. var _this = this;
  29134. BABYLON.Tools.LoadFile(this.url, function (data) {
  29135. _this.data = data;
  29136. _this.isCompleted = true;
  29137. if (_this.onSuccess) {
  29138. _this.onSuccess(_this);
  29139. }
  29140. onSuccess();
  29141. }, null, scene.database, true, function () {
  29142. if (_this.onError) {
  29143. _this.onError(_this);
  29144. }
  29145. onError();
  29146. });
  29147. };
  29148. return BinaryFileAssetTask;
  29149. })();
  29150. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  29151. var ImageAssetTask = (function () {
  29152. function ImageAssetTask(name, url) {
  29153. this.name = name;
  29154. this.url = url;
  29155. this.isCompleted = false;
  29156. }
  29157. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29158. var _this = this;
  29159. var img = new Image();
  29160. img.onload = function () {
  29161. _this.image = img;
  29162. _this.isCompleted = true;
  29163. if (_this.onSuccess) {
  29164. _this.onSuccess(_this);
  29165. }
  29166. onSuccess();
  29167. };
  29168. img.onerror = function () {
  29169. if (_this.onError) {
  29170. _this.onError(_this);
  29171. }
  29172. onError();
  29173. };
  29174. img.src = this.url;
  29175. };
  29176. return ImageAssetTask;
  29177. })();
  29178. BABYLON.ImageAssetTask = ImageAssetTask;
  29179. var TextureAssetTask = (function () {
  29180. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  29181. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29182. this.name = name;
  29183. this.url = url;
  29184. this.noMipmap = noMipmap;
  29185. this.invertY = invertY;
  29186. this.samplingMode = samplingMode;
  29187. this.isCompleted = false;
  29188. }
  29189. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  29190. var _this = this;
  29191. var onload = function () {
  29192. _this.isCompleted = true;
  29193. if (_this.onSuccess) {
  29194. _this.onSuccess(_this);
  29195. }
  29196. onSuccess();
  29197. };
  29198. var onerror = function () {
  29199. if (_this.onError) {
  29200. _this.onError(_this);
  29201. }
  29202. onError();
  29203. };
  29204. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  29205. };
  29206. return TextureAssetTask;
  29207. })();
  29208. BABYLON.TextureAssetTask = TextureAssetTask;
  29209. var AssetsManager = (function () {
  29210. function AssetsManager(scene) {
  29211. this._tasks = new Array();
  29212. this._waitingTasksCount = 0;
  29213. this.useDefaultLoadingScreen = true;
  29214. this._scene = scene;
  29215. }
  29216. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  29217. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  29218. this._tasks.push(task);
  29219. return task;
  29220. };
  29221. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  29222. var task = new TextFileAssetTask(taskName, url);
  29223. this._tasks.push(task);
  29224. return task;
  29225. };
  29226. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  29227. var task = new BinaryFileAssetTask(taskName, url);
  29228. this._tasks.push(task);
  29229. return task;
  29230. };
  29231. AssetsManager.prototype.addImageTask = function (taskName, url) {
  29232. var task = new ImageAssetTask(taskName, url);
  29233. this._tasks.push(task);
  29234. return task;
  29235. };
  29236. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  29237. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29238. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  29239. this._tasks.push(task);
  29240. return task;
  29241. };
  29242. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  29243. this._waitingTasksCount--;
  29244. if (this._waitingTasksCount === 0) {
  29245. if (this.onFinish) {
  29246. this.onFinish(this._tasks);
  29247. }
  29248. this._scene.getEngine().hideLoadingUI();
  29249. }
  29250. };
  29251. AssetsManager.prototype._runTask = function (task) {
  29252. var _this = this;
  29253. task.run(this._scene, function () {
  29254. if (_this.onTaskSuccess) {
  29255. _this.onTaskSuccess(task);
  29256. }
  29257. _this._decreaseWaitingTasksCount();
  29258. }, function () {
  29259. if (_this.onTaskError) {
  29260. _this.onTaskError(task);
  29261. }
  29262. _this._decreaseWaitingTasksCount();
  29263. });
  29264. };
  29265. AssetsManager.prototype.reset = function () {
  29266. this._tasks = new Array();
  29267. return this;
  29268. };
  29269. AssetsManager.prototype.load = function () {
  29270. this._waitingTasksCount = this._tasks.length;
  29271. if (this._waitingTasksCount === 0) {
  29272. if (this.onFinish) {
  29273. this.onFinish(this._tasks);
  29274. }
  29275. return this;
  29276. }
  29277. if (this.useDefaultLoadingScreen) {
  29278. this._scene.getEngine().displayLoadingUI();
  29279. }
  29280. for (var index = 0; index < this._tasks.length; index++) {
  29281. var task = this._tasks[index];
  29282. this._runTask(task);
  29283. }
  29284. return this;
  29285. };
  29286. return AssetsManager;
  29287. })();
  29288. BABYLON.AssetsManager = AssetsManager;
  29289. })(BABYLON || (BABYLON = {}));
  29290. var BABYLON;
  29291. (function (BABYLON) {
  29292. var VRDeviceOrientationFreeCamera = (function (_super) {
  29293. __extends(VRDeviceOrientationFreeCamera, _super);
  29294. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  29295. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29296. _super.call(this, name, position, scene);
  29297. this._alpha = 0;
  29298. this._beta = 0;
  29299. this._gamma = 0;
  29300. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29301. metrics.compensateDistorsion = compensateDistorsion;
  29302. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29303. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  29304. }
  29305. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  29306. this._alpha = +evt.alpha | 0;
  29307. this._beta = +evt.beta | 0;
  29308. this._gamma = +evt.gamma | 0;
  29309. if (this._gamma < 0) {
  29310. this._gamma = 90 + this._gamma;
  29311. }
  29312. else {
  29313. // Incline it in the correct angle.
  29314. this._gamma = 270 - this._gamma;
  29315. }
  29316. this.rotation.x = this._gamma / 180.0 * Math.PI;
  29317. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  29318. this.rotation.z = this._beta / 180.0 * Math.PI;
  29319. };
  29320. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29321. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29322. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  29323. };
  29324. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  29325. _super.prototype.detachControl.call(this, element);
  29326. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  29327. };
  29328. return VRDeviceOrientationFreeCamera;
  29329. })(BABYLON.FreeCamera);
  29330. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  29331. })(BABYLON || (BABYLON = {}));
  29332. var BABYLON;
  29333. (function (BABYLON) {
  29334. var WebVRFreeCamera = (function (_super) {
  29335. __extends(WebVRFreeCamera, _super);
  29336. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  29337. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  29338. _super.call(this, name, position, scene);
  29339. this._hmdDevice = null;
  29340. this._sensorDevice = null;
  29341. this._cacheState = null;
  29342. this._cacheQuaternion = new BABYLON.Quaternion();
  29343. this._cacheRotation = BABYLON.Vector3.Zero();
  29344. this._vrEnabled = false;
  29345. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  29346. metrics.compensateDistorsion = compensateDistorsion;
  29347. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  29348. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  29349. }
  29350. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  29351. var size = devices.length;
  29352. var i = 0;
  29353. // Reset devices.
  29354. this._sensorDevice = null;
  29355. this._hmdDevice = null;
  29356. // Search for a HmdDevice.
  29357. while (i < size && this._hmdDevice === null) {
  29358. if (devices[i] instanceof HMDVRDevice) {
  29359. this._hmdDevice = devices[i];
  29360. }
  29361. i++;
  29362. }
  29363. i = 0;
  29364. while (i < size && this._sensorDevice === null) {
  29365. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  29366. this._sensorDevice = devices[i];
  29367. }
  29368. i++;
  29369. }
  29370. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  29371. };
  29372. WebVRFreeCamera.prototype._checkInputs = function () {
  29373. if (this._vrEnabled) {
  29374. this._cacheState = this._sensorDevice.getState();
  29375. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  29376. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  29377. this.rotation.x = -this._cacheRotation.z;
  29378. this.rotation.y = -this._cacheRotation.y;
  29379. this.rotation.z = this._cacheRotation.x;
  29380. }
  29381. _super.prototype._checkInputs.call(this);
  29382. };
  29383. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  29384. _super.prototype.attachControl.call(this, element, noPreventDefault);
  29385. if (navigator.getVRDevices) {
  29386. navigator.getVRDevices().then(this._getWebVRDevices);
  29387. }
  29388. else if (navigator.mozGetVRDevices) {
  29389. navigator.mozGetVRDevices(this._getWebVRDevices);
  29390. }
  29391. };
  29392. WebVRFreeCamera.prototype.detachControl = function (element) {
  29393. _super.prototype.detachControl.call(this, element);
  29394. this._vrEnabled = false;
  29395. };
  29396. return WebVRFreeCamera;
  29397. })(BABYLON.FreeCamera);
  29398. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  29399. })(BABYLON || (BABYLON = {}));
  29400. var BABYLON;
  29401. (function (BABYLON) {
  29402. // Standard optimizations
  29403. var SceneOptimization = (function () {
  29404. function SceneOptimization(priority) {
  29405. if (priority === void 0) { priority = 0; }
  29406. this.priority = priority;
  29407. this.apply = function (scene) {
  29408. return true; // Return true if everything that can be done was applied
  29409. };
  29410. }
  29411. return SceneOptimization;
  29412. })();
  29413. BABYLON.SceneOptimization = SceneOptimization;
  29414. var TextureOptimization = (function (_super) {
  29415. __extends(TextureOptimization, _super);
  29416. function TextureOptimization(priority, maximumSize) {
  29417. var _this = this;
  29418. if (priority === void 0) { priority = 0; }
  29419. if (maximumSize === void 0) { maximumSize = 1024; }
  29420. _super.call(this, priority);
  29421. this.priority = priority;
  29422. this.maximumSize = maximumSize;
  29423. this.apply = function (scene) {
  29424. var allDone = true;
  29425. for (var index = 0; index < scene.textures.length; index++) {
  29426. var texture = scene.textures[index];
  29427. if (!texture.canRescale) {
  29428. continue;
  29429. }
  29430. var currentSize = texture.getSize();
  29431. var maxDimension = Math.max(currentSize.width, currentSize.height);
  29432. if (maxDimension > _this.maximumSize) {
  29433. texture.scale(0.5);
  29434. allDone = false;
  29435. }
  29436. }
  29437. return allDone;
  29438. };
  29439. }
  29440. return TextureOptimization;
  29441. })(SceneOptimization);
  29442. BABYLON.TextureOptimization = TextureOptimization;
  29443. var HardwareScalingOptimization = (function (_super) {
  29444. __extends(HardwareScalingOptimization, _super);
  29445. function HardwareScalingOptimization(priority, maximumScale) {
  29446. var _this = this;
  29447. if (priority === void 0) { priority = 0; }
  29448. if (maximumScale === void 0) { maximumScale = 2; }
  29449. _super.call(this, priority);
  29450. this.priority = priority;
  29451. this.maximumScale = maximumScale;
  29452. this._currentScale = 1;
  29453. this.apply = function (scene) {
  29454. _this._currentScale++;
  29455. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  29456. return _this._currentScale >= _this.maximumScale;
  29457. };
  29458. }
  29459. return HardwareScalingOptimization;
  29460. })(SceneOptimization);
  29461. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  29462. var ShadowsOptimization = (function (_super) {
  29463. __extends(ShadowsOptimization, _super);
  29464. function ShadowsOptimization() {
  29465. _super.apply(this, arguments);
  29466. this.apply = function (scene) {
  29467. scene.shadowsEnabled = false;
  29468. return true;
  29469. };
  29470. }
  29471. return ShadowsOptimization;
  29472. })(SceneOptimization);
  29473. BABYLON.ShadowsOptimization = ShadowsOptimization;
  29474. var PostProcessesOptimization = (function (_super) {
  29475. __extends(PostProcessesOptimization, _super);
  29476. function PostProcessesOptimization() {
  29477. _super.apply(this, arguments);
  29478. this.apply = function (scene) {
  29479. scene.postProcessesEnabled = false;
  29480. return true;
  29481. };
  29482. }
  29483. return PostProcessesOptimization;
  29484. })(SceneOptimization);
  29485. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  29486. var LensFlaresOptimization = (function (_super) {
  29487. __extends(LensFlaresOptimization, _super);
  29488. function LensFlaresOptimization() {
  29489. _super.apply(this, arguments);
  29490. this.apply = function (scene) {
  29491. scene.lensFlaresEnabled = false;
  29492. return true;
  29493. };
  29494. }
  29495. return LensFlaresOptimization;
  29496. })(SceneOptimization);
  29497. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  29498. var ParticlesOptimization = (function (_super) {
  29499. __extends(ParticlesOptimization, _super);
  29500. function ParticlesOptimization() {
  29501. _super.apply(this, arguments);
  29502. this.apply = function (scene) {
  29503. scene.particlesEnabled = false;
  29504. return true;
  29505. };
  29506. }
  29507. return ParticlesOptimization;
  29508. })(SceneOptimization);
  29509. BABYLON.ParticlesOptimization = ParticlesOptimization;
  29510. var RenderTargetsOptimization = (function (_super) {
  29511. __extends(RenderTargetsOptimization, _super);
  29512. function RenderTargetsOptimization() {
  29513. _super.apply(this, arguments);
  29514. this.apply = function (scene) {
  29515. scene.renderTargetsEnabled = false;
  29516. return true;
  29517. };
  29518. }
  29519. return RenderTargetsOptimization;
  29520. })(SceneOptimization);
  29521. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  29522. var MergeMeshesOptimization = (function (_super) {
  29523. __extends(MergeMeshesOptimization, _super);
  29524. function MergeMeshesOptimization() {
  29525. var _this = this;
  29526. _super.apply(this, arguments);
  29527. this._canBeMerged = function (abstractMesh) {
  29528. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  29529. return false;
  29530. }
  29531. var mesh = abstractMesh;
  29532. if (!mesh.isVisible || !mesh.isEnabled()) {
  29533. return false;
  29534. }
  29535. if (mesh.instances.length > 0) {
  29536. return false;
  29537. }
  29538. if (mesh.skeleton || mesh.hasLODLevels) {
  29539. return false;
  29540. }
  29541. return true;
  29542. };
  29543. this.apply = function (scene, updateSelectionTree) {
  29544. var globalPool = scene.meshes.slice(0);
  29545. var globalLength = globalPool.length;
  29546. for (var index = 0; index < globalLength; index++) {
  29547. var currentPool = new Array();
  29548. var current = globalPool[index];
  29549. // Checks
  29550. if (!_this._canBeMerged(current)) {
  29551. continue;
  29552. }
  29553. currentPool.push(current);
  29554. // Find compatible meshes
  29555. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  29556. var otherMesh = globalPool[subIndex];
  29557. if (!_this._canBeMerged(otherMesh)) {
  29558. continue;
  29559. }
  29560. if (otherMesh.material !== current.material) {
  29561. continue;
  29562. }
  29563. if (otherMesh.checkCollisions !== current.checkCollisions) {
  29564. continue;
  29565. }
  29566. currentPool.push(otherMesh);
  29567. globalLength--;
  29568. globalPool.splice(subIndex, 1);
  29569. subIndex--;
  29570. }
  29571. if (currentPool.length < 2) {
  29572. continue;
  29573. }
  29574. // Merge meshes
  29575. BABYLON.Mesh.MergeMeshes(currentPool);
  29576. }
  29577. if (updateSelectionTree != undefined) {
  29578. if (updateSelectionTree) {
  29579. scene.createOrUpdateSelectionOctree();
  29580. }
  29581. }
  29582. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  29583. scene.createOrUpdateSelectionOctree();
  29584. }
  29585. return true;
  29586. };
  29587. }
  29588. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  29589. get: function () {
  29590. return MergeMeshesOptimization._UpdateSelectionTree;
  29591. },
  29592. set: function (value) {
  29593. MergeMeshesOptimization._UpdateSelectionTree = value;
  29594. },
  29595. enumerable: true,
  29596. configurable: true
  29597. });
  29598. MergeMeshesOptimization._UpdateSelectionTree = false;
  29599. return MergeMeshesOptimization;
  29600. })(SceneOptimization);
  29601. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  29602. // Options
  29603. var SceneOptimizerOptions = (function () {
  29604. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  29605. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  29606. if (trackerDuration === void 0) { trackerDuration = 2000; }
  29607. this.targetFrameRate = targetFrameRate;
  29608. this.trackerDuration = trackerDuration;
  29609. this.optimizations = new Array();
  29610. }
  29611. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  29612. var result = new SceneOptimizerOptions(targetFrameRate);
  29613. var priority = 0;
  29614. result.optimizations.push(new MergeMeshesOptimization(priority));
  29615. result.optimizations.push(new ShadowsOptimization(priority));
  29616. result.optimizations.push(new LensFlaresOptimization(priority));
  29617. // Next priority
  29618. priority++;
  29619. result.optimizations.push(new PostProcessesOptimization(priority));
  29620. result.optimizations.push(new ParticlesOptimization(priority));
  29621. // Next priority
  29622. priority++;
  29623. result.optimizations.push(new TextureOptimization(priority, 1024));
  29624. return result;
  29625. };
  29626. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  29627. var result = new SceneOptimizerOptions(targetFrameRate);
  29628. var priority = 0;
  29629. result.optimizations.push(new MergeMeshesOptimization(priority));
  29630. result.optimizations.push(new ShadowsOptimization(priority));
  29631. result.optimizations.push(new LensFlaresOptimization(priority));
  29632. // Next priority
  29633. priority++;
  29634. result.optimizations.push(new PostProcessesOptimization(priority));
  29635. result.optimizations.push(new ParticlesOptimization(priority));
  29636. // Next priority
  29637. priority++;
  29638. result.optimizations.push(new TextureOptimization(priority, 512));
  29639. // Next priority
  29640. priority++;
  29641. result.optimizations.push(new RenderTargetsOptimization(priority));
  29642. // Next priority
  29643. priority++;
  29644. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  29645. return result;
  29646. };
  29647. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  29648. var result = new SceneOptimizerOptions(targetFrameRate);
  29649. var priority = 0;
  29650. result.optimizations.push(new MergeMeshesOptimization(priority));
  29651. result.optimizations.push(new ShadowsOptimization(priority));
  29652. result.optimizations.push(new LensFlaresOptimization(priority));
  29653. // Next priority
  29654. priority++;
  29655. result.optimizations.push(new PostProcessesOptimization(priority));
  29656. result.optimizations.push(new ParticlesOptimization(priority));
  29657. // Next priority
  29658. priority++;
  29659. result.optimizations.push(new TextureOptimization(priority, 256));
  29660. // Next priority
  29661. priority++;
  29662. result.optimizations.push(new RenderTargetsOptimization(priority));
  29663. // Next priority
  29664. priority++;
  29665. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  29666. return result;
  29667. };
  29668. return SceneOptimizerOptions;
  29669. })();
  29670. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  29671. // Scene optimizer tool
  29672. var SceneOptimizer = (function () {
  29673. function SceneOptimizer() {
  29674. }
  29675. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  29676. // TODO: add an epsilon
  29677. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  29678. if (onSuccess) {
  29679. onSuccess();
  29680. }
  29681. return;
  29682. }
  29683. // Apply current level of optimizations
  29684. var allDone = true;
  29685. var noOptimizationApplied = true;
  29686. for (var index = 0; index < options.optimizations.length; index++) {
  29687. var optimization = options.optimizations[index];
  29688. if (optimization.priority === currentPriorityLevel) {
  29689. noOptimizationApplied = false;
  29690. allDone = allDone && optimization.apply(scene);
  29691. }
  29692. }
  29693. // If no optimization was applied, this is a failure :(
  29694. if (noOptimizationApplied) {
  29695. if (onFailure) {
  29696. onFailure();
  29697. }
  29698. return;
  29699. }
  29700. // If all optimizations were done, move to next level
  29701. if (allDone) {
  29702. currentPriorityLevel++;
  29703. }
  29704. // Let's the system running for a specific amount of time before checking FPS
  29705. scene.executeWhenReady(function () {
  29706. setTimeout(function () {
  29707. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  29708. }, options.trackerDuration);
  29709. });
  29710. };
  29711. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  29712. if (!options) {
  29713. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  29714. }
  29715. // Let's the system running for a specific amount of time before checking FPS
  29716. scene.executeWhenReady(function () {
  29717. setTimeout(function () {
  29718. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  29719. }, options.trackerDuration);
  29720. });
  29721. };
  29722. return SceneOptimizer;
  29723. })();
  29724. BABYLON.SceneOptimizer = SceneOptimizer;
  29725. })(BABYLON || (BABYLON = {}));
  29726. var BABYLON;
  29727. (function (BABYLON) {
  29728. var Internals;
  29729. (function (Internals) {
  29730. var MeshLODLevel = (function () {
  29731. function MeshLODLevel(distance, mesh) {
  29732. this.distance = distance;
  29733. this.mesh = mesh;
  29734. }
  29735. return MeshLODLevel;
  29736. })();
  29737. Internals.MeshLODLevel = MeshLODLevel;
  29738. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29739. })(BABYLON || (BABYLON = {}));
  29740. var BABYLON;
  29741. (function (BABYLON) {
  29742. var AudioEngine = (function () {
  29743. function AudioEngine() {
  29744. this._audioContext = null;
  29745. this._audioContextInitialized = false;
  29746. this.canUseWebAudio = false;
  29747. this.WarnedWebAudioUnsupported = false;
  29748. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  29749. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  29750. this.canUseWebAudio = true;
  29751. }
  29752. }
  29753. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  29754. get: function () {
  29755. if (!this._audioContextInitialized) {
  29756. this._initializeAudioContext();
  29757. }
  29758. return this._audioContext;
  29759. },
  29760. enumerable: true,
  29761. configurable: true
  29762. });
  29763. AudioEngine.prototype._initializeAudioContext = function () {
  29764. try {
  29765. if (this.canUseWebAudio) {
  29766. this._audioContext = new AudioContext();
  29767. // create a global volume gain node
  29768. this.masterGain = this._audioContext.createGain();
  29769. this.masterGain.gain.value = 1;
  29770. this.masterGain.connect(this._audioContext.destination);
  29771. this._audioContextInitialized = true;
  29772. }
  29773. }
  29774. catch (e) {
  29775. this.canUseWebAudio = false;
  29776. BABYLON.Tools.Error("Web Audio: " + e.message);
  29777. }
  29778. };
  29779. AudioEngine.prototype.dispose = function () {
  29780. if (this.canUseWebAudio && this._audioContextInitialized) {
  29781. if (this._connectedAnalyser) {
  29782. this._connectedAnalyser.stopDebugCanvas();
  29783. this._connectedAnalyser.dispose();
  29784. this.masterGain.disconnect();
  29785. this.masterGain.connect(this._audioContext.destination);
  29786. this._connectedAnalyser = null;
  29787. }
  29788. this.masterGain.gain.value = 1;
  29789. }
  29790. this.WarnedWebAudioUnsupported = false;
  29791. };
  29792. AudioEngine.prototype.getGlobalVolume = function () {
  29793. if (this.canUseWebAudio && this._audioContextInitialized) {
  29794. return this.masterGain.gain.value;
  29795. }
  29796. else {
  29797. return -1;
  29798. }
  29799. };
  29800. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  29801. if (this.canUseWebAudio && this._audioContextInitialized) {
  29802. this.masterGain.gain.value = newVolume;
  29803. }
  29804. };
  29805. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  29806. if (this._connectedAnalyser) {
  29807. this._connectedAnalyser.stopDebugCanvas();
  29808. }
  29809. if (this.canUseWebAudio && this._audioContextInitialized) {
  29810. this._connectedAnalyser = analyser;
  29811. this.masterGain.disconnect();
  29812. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  29813. }
  29814. };
  29815. return AudioEngine;
  29816. })();
  29817. BABYLON.AudioEngine = AudioEngine;
  29818. })(BABYLON || (BABYLON = {}));
  29819. var BABYLON;
  29820. (function (BABYLON) {
  29821. var Sound = (function () {
  29822. /**
  29823. * Create a sound and attach it to a scene
  29824. * @param name Name of your sound
  29825. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  29826. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  29827. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  29828. */
  29829. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  29830. var _this = this;
  29831. this.autoplay = false;
  29832. this.loop = false;
  29833. this.useCustomAttenuation = false;
  29834. this.spatialSound = false;
  29835. this.refDistance = 1;
  29836. this.rolloffFactor = 1;
  29837. this.maxDistance = 100;
  29838. this.distanceModel = "linear";
  29839. this._panningModel = "equalpower";
  29840. this._playbackRate = 1;
  29841. this._startTime = 0;
  29842. this._startOffset = 0;
  29843. this._position = BABYLON.Vector3.Zero();
  29844. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  29845. this._volume = 1;
  29846. this._isLoaded = false;
  29847. this._isReadyToPlay = false;
  29848. this.isPlaying = false;
  29849. this.isPaused = false;
  29850. this._isDirectional = false;
  29851. // Used if you'd like to create a directional sound.
  29852. // If not set, the sound will be omnidirectional
  29853. this._coneInnerAngle = 360;
  29854. this._coneOuterAngle = 360;
  29855. this._coneOuterGain = 0;
  29856. this.name = name;
  29857. this._scene = scene;
  29858. this._readyToPlayCallback = readyToPlayCallback;
  29859. // Default custom attenuation function is a linear attenuation
  29860. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  29861. if (currentDistance < maxDistance) {
  29862. return currentVolume * (1 - currentDistance / maxDistance);
  29863. }
  29864. else {
  29865. return 0;
  29866. }
  29867. };
  29868. if (options) {
  29869. this.autoplay = options.autoplay || false;
  29870. this.loop = options.loop || false;
  29871. // if volume === 0, we need another way to check this option
  29872. if (options.volume !== undefined) {
  29873. this._volume = options.volume;
  29874. }
  29875. this.spatialSound = options.spatialSound || false;
  29876. this.maxDistance = options.maxDistance || 100;
  29877. this.useCustomAttenuation = options.useCustomAttenuation || false;
  29878. this.rolloffFactor = options.rolloffFactor || 1;
  29879. this.refDistance = options.refDistance || 1;
  29880. this.distanceModel = options.distanceModel || "linear";
  29881. this._playbackRate = options.playbackRate || 1;
  29882. }
  29883. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29884. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  29885. this._soundGain.gain.value = this._volume;
  29886. this._inputAudioNode = this._soundGain;
  29887. this._ouputAudioNode = this._soundGain;
  29888. if (this.spatialSound) {
  29889. this._createSpatialParameters();
  29890. }
  29891. this._scene.mainSoundTrack.AddSound(this);
  29892. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  29893. if (urlOrArrayBuffer) {
  29894. // If it's an URL
  29895. if (typeof (urlOrArrayBuffer) === "string") {
  29896. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  29897. }
  29898. else {
  29899. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  29900. this._soundLoaded(urlOrArrayBuffer);
  29901. }
  29902. else {
  29903. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  29904. }
  29905. }
  29906. }
  29907. }
  29908. else {
  29909. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  29910. this._scene.mainSoundTrack.AddSound(this);
  29911. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  29912. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  29913. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  29914. }
  29915. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  29916. if (this._readyToPlayCallback) {
  29917. window.setTimeout(function () {
  29918. _this._readyToPlayCallback();
  29919. }, 1000);
  29920. }
  29921. }
  29922. }
  29923. Sound.prototype.dispose = function () {
  29924. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  29925. if (this.isPlaying) {
  29926. this.stop();
  29927. }
  29928. this._isReadyToPlay = false;
  29929. if (this.soundTrackId === -1) {
  29930. this._scene.mainSoundTrack.RemoveSound(this);
  29931. }
  29932. else {
  29933. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  29934. }
  29935. if (this._soundGain) {
  29936. this._soundGain.disconnect();
  29937. this._soundGain = null;
  29938. }
  29939. if (this._soundPanner) {
  29940. this._soundPanner.disconnect();
  29941. this._soundPanner = null;
  29942. }
  29943. if (this._soundSource) {
  29944. this._soundSource.disconnect();
  29945. this._soundSource = null;
  29946. }
  29947. this._audioBuffer = null;
  29948. if (this._connectedMesh) {
  29949. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  29950. this._connectedMesh = null;
  29951. }
  29952. }
  29953. };
  29954. Sound.prototype._soundLoaded = function (audioData) {
  29955. var _this = this;
  29956. this._isLoaded = true;
  29957. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  29958. _this._audioBuffer = buffer;
  29959. _this._isReadyToPlay = true;
  29960. if (_this.autoplay) {
  29961. _this.play();
  29962. }
  29963. if (_this._readyToPlayCallback) {
  29964. _this._readyToPlayCallback();
  29965. }
  29966. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  29967. };
  29968. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  29969. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29970. this._audioBuffer = audioBuffer;
  29971. this._isReadyToPlay = true;
  29972. }
  29973. };
  29974. Sound.prototype.updateOptions = function (options) {
  29975. if (options) {
  29976. this.loop = options.loop || this.loop;
  29977. this.maxDistance = options.maxDistance || this.maxDistance;
  29978. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  29979. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  29980. this.refDistance = options.refDistance || this.refDistance;
  29981. this.distanceModel = options.distanceModel || this.distanceModel;
  29982. this._playbackRate = options.playbackRate || this._playbackRate;
  29983. this._updateSpatialParameters();
  29984. if (this.isPlaying) {
  29985. this._soundSource.playbackRate.value = this._playbackRate;
  29986. }
  29987. }
  29988. };
  29989. Sound.prototype._createSpatialParameters = function () {
  29990. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29991. if (this._scene.headphone) {
  29992. this._panningModel = "HRTF";
  29993. }
  29994. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  29995. this._updateSpatialParameters();
  29996. this._soundPanner.connect(this._ouputAudioNode);
  29997. this._inputAudioNode = this._soundPanner;
  29998. }
  29999. };
  30000. Sound.prototype._updateSpatialParameters = function () {
  30001. if (this.spatialSound) {
  30002. if (this.useCustomAttenuation) {
  30003. // Tricks to disable in a way embedded Web Audio attenuation
  30004. this._soundPanner.distanceModel = "linear";
  30005. this._soundPanner.maxDistance = Number.MAX_VALUE;
  30006. this._soundPanner.refDistance = 1;
  30007. this._soundPanner.rolloffFactor = 1;
  30008. this._soundPanner.panningModel = this._panningModel;
  30009. }
  30010. else {
  30011. this._soundPanner.distanceModel = this.distanceModel;
  30012. this._soundPanner.maxDistance = this.maxDistance;
  30013. this._soundPanner.refDistance = this.refDistance;
  30014. this._soundPanner.rolloffFactor = this.rolloffFactor;
  30015. this._soundPanner.panningModel = this._panningModel;
  30016. }
  30017. }
  30018. };
  30019. Sound.prototype.switchPanningModelToHRTF = function () {
  30020. this._panningModel = "HRTF";
  30021. this._switchPanningModel();
  30022. };
  30023. Sound.prototype.switchPanningModelToEqualPower = function () {
  30024. this._panningModel = "equalpower";
  30025. this._switchPanningModel();
  30026. };
  30027. Sound.prototype._switchPanningModel = function () {
  30028. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30029. this._soundPanner.panningModel = this._panningModel;
  30030. }
  30031. };
  30032. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  30033. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30034. this._ouputAudioNode.disconnect();
  30035. this._ouputAudioNode.connect(soundTrackAudioNode);
  30036. }
  30037. };
  30038. /**
  30039. * Transform this sound into a directional source
  30040. * @param coneInnerAngle Size of the inner cone in degree
  30041. * @param coneOuterAngle Size of the outer cone in degree
  30042. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  30043. */
  30044. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  30045. if (coneOuterAngle < coneInnerAngle) {
  30046. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  30047. return;
  30048. }
  30049. this._coneInnerAngle = coneInnerAngle;
  30050. this._coneOuterAngle = coneOuterAngle;
  30051. this._coneOuterGain = coneOuterGain;
  30052. this._isDirectional = true;
  30053. if (this.isPlaying && this.loop) {
  30054. this.stop();
  30055. this.play();
  30056. }
  30057. };
  30058. Sound.prototype.setPosition = function (newPosition) {
  30059. this._position = newPosition;
  30060. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  30061. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30062. }
  30063. };
  30064. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  30065. this._localDirection = newLocalDirection;
  30066. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  30067. this._updateDirection();
  30068. }
  30069. };
  30070. Sound.prototype._updateDirection = function () {
  30071. var mat = this._connectedMesh.getWorldMatrix();
  30072. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  30073. direction.normalize();
  30074. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  30075. };
  30076. Sound.prototype.updateDistanceFromListener = function () {
  30077. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  30078. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  30079. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  30080. }
  30081. };
  30082. Sound.prototype.setAttenuationFunction = function (callback) {
  30083. this._customAttenuationFunction = callback;
  30084. };
  30085. /**
  30086. * Play the sound
  30087. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  30088. */
  30089. Sound.prototype.play = function (time) {
  30090. var _this = this;
  30091. if (this._isReadyToPlay && this._scene.audioEnabled) {
  30092. try {
  30093. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30094. if (!this._soundSource) {
  30095. if (this.spatialSound) {
  30096. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  30097. if (this._isDirectional) {
  30098. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  30099. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  30100. this._soundPanner.coneOuterGain = this._coneOuterGain;
  30101. if (this._connectedMesh) {
  30102. this._updateDirection();
  30103. }
  30104. else {
  30105. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  30106. }
  30107. }
  30108. }
  30109. }
  30110. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  30111. this._soundSource.buffer = this._audioBuffer;
  30112. this._soundSource.connect(this._inputAudioNode);
  30113. this._soundSource.loop = this.loop;
  30114. this._soundSource.playbackRate.value = this._playbackRate;
  30115. this._startTime = startTime;
  30116. this._soundSource.onended = function () { _this._onended(); };
  30117. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  30118. this.isPlaying = true;
  30119. this.isPaused = false;
  30120. }
  30121. catch (ex) {
  30122. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  30123. }
  30124. }
  30125. };
  30126. Sound.prototype._onended = function () {
  30127. this.isPlaying = false;
  30128. if (this.onended) {
  30129. this.onended();
  30130. }
  30131. };
  30132. /**
  30133. * Stop the sound
  30134. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  30135. */
  30136. Sound.prototype.stop = function (time) {
  30137. if (this.isPlaying) {
  30138. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  30139. this._soundSource.stop(stopTime);
  30140. this.isPlaying = false;
  30141. }
  30142. };
  30143. Sound.prototype.pause = function () {
  30144. if (this.isPlaying) {
  30145. this.stop(0);
  30146. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  30147. this.isPaused = true;
  30148. }
  30149. };
  30150. Sound.prototype.setVolume = function (newVolume, time) {
  30151. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30152. if (time) {
  30153. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  30154. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  30155. }
  30156. else {
  30157. this._soundGain.gain.value = newVolume;
  30158. }
  30159. }
  30160. this._volume = newVolume;
  30161. };
  30162. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  30163. this._playbackRate = newPlaybackRate;
  30164. if (this.isPlaying) {
  30165. this._soundSource.playbackRate.value = this._playbackRate;
  30166. }
  30167. };
  30168. Sound.prototype.getVolume = function () {
  30169. return this._volume;
  30170. };
  30171. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  30172. var _this = this;
  30173. this._connectedMesh = meshToConnectTo;
  30174. if (!this.spatialSound) {
  30175. this.spatialSound = true;
  30176. this._createSpatialParameters();
  30177. if (this.isPlaying && this.loop) {
  30178. this.stop();
  30179. this.play();
  30180. }
  30181. }
  30182. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  30183. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  30184. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  30185. };
  30186. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  30187. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  30188. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  30189. this._updateDirection();
  30190. }
  30191. };
  30192. return Sound;
  30193. })();
  30194. BABYLON.Sound = Sound;
  30195. })(BABYLON || (BABYLON = {}));
  30196. var BABYLON;
  30197. (function (BABYLON) {
  30198. var SoundTrack = (function () {
  30199. function SoundTrack(scene, options) {
  30200. this.id = -1;
  30201. this._isMainTrack = false;
  30202. this._scene = scene;
  30203. this._audioEngine = BABYLON.Engine.audioEngine;
  30204. this.soundCollection = new Array();
  30205. if (this._audioEngine.canUseWebAudio) {
  30206. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  30207. this._outputAudioNode.connect(this._audioEngine.masterGain);
  30208. if (options) {
  30209. if (options.volume) {
  30210. this._outputAudioNode.gain.value = options.volume;
  30211. }
  30212. if (options.mainTrack) {
  30213. this._isMainTrack = options.mainTrack;
  30214. }
  30215. }
  30216. }
  30217. if (!this._isMainTrack) {
  30218. this._scene.soundTracks.push(this);
  30219. this.id = this._scene.soundTracks.length - 1;
  30220. }
  30221. }
  30222. SoundTrack.prototype.dispose = function () {
  30223. if (this._audioEngine.canUseWebAudio) {
  30224. if (this._connectedAnalyser) {
  30225. this._connectedAnalyser.stopDebugCanvas();
  30226. }
  30227. while (this.soundCollection.length) {
  30228. this.soundCollection[0].dispose();
  30229. }
  30230. if (this._outputAudioNode) {
  30231. this._outputAudioNode.disconnect();
  30232. }
  30233. this._outputAudioNode = null;
  30234. }
  30235. };
  30236. SoundTrack.prototype.AddSound = function (sound) {
  30237. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30238. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  30239. }
  30240. if (sound.soundTrackId) {
  30241. if (sound.soundTrackId === -1) {
  30242. this._scene.mainSoundTrack.RemoveSound(sound);
  30243. }
  30244. else {
  30245. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  30246. }
  30247. }
  30248. this.soundCollection.push(sound);
  30249. sound.soundTrackId = this.id;
  30250. };
  30251. SoundTrack.prototype.RemoveSound = function (sound) {
  30252. var index = this.soundCollection.indexOf(sound);
  30253. if (index !== -1) {
  30254. this.soundCollection.splice(index, 1);
  30255. }
  30256. };
  30257. SoundTrack.prototype.setVolume = function (newVolume) {
  30258. if (this._audioEngine.canUseWebAudio) {
  30259. this._outputAudioNode.gain.value = newVolume;
  30260. }
  30261. };
  30262. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  30263. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30264. for (var i = 0; i < this.soundCollection.length; i++) {
  30265. this.soundCollection[i].switchPanningModelToHRTF();
  30266. }
  30267. }
  30268. };
  30269. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  30270. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30271. for (var i = 0; i < this.soundCollection.length; i++) {
  30272. this.soundCollection[i].switchPanningModelToEqualPower();
  30273. }
  30274. }
  30275. };
  30276. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  30277. if (this._connectedAnalyser) {
  30278. this._connectedAnalyser.stopDebugCanvas();
  30279. }
  30280. this._connectedAnalyser = analyser;
  30281. if (this._audioEngine.canUseWebAudio) {
  30282. this._outputAudioNode.disconnect();
  30283. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  30284. }
  30285. };
  30286. return SoundTrack;
  30287. })();
  30288. BABYLON.SoundTrack = SoundTrack;
  30289. })(BABYLON || (BABYLON = {}));
  30290. var BABYLON;
  30291. (function (BABYLON) {
  30292. var DebugLayer = (function () {
  30293. function DebugLayer(scene) {
  30294. var _this = this;
  30295. this._transformationMatrix = BABYLON.Matrix.Identity();
  30296. this._enabled = false;
  30297. this._labelsEnabled = false;
  30298. this._displayStatistics = true;
  30299. this._displayTree = false;
  30300. this._displayLogs = false;
  30301. this._identityMatrix = BABYLON.Matrix.Identity();
  30302. this.axisRatio = 0.02;
  30303. this.accentColor = "orange";
  30304. this._scene = scene;
  30305. this._syncPositions = function () {
  30306. var engine = _this._scene.getEngine();
  30307. var canvasRect = engine.getRenderingCanvasClientRect();
  30308. if (_this._showUI) {
  30309. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  30310. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  30311. _this._statsDiv.style.width = "400px";
  30312. _this._statsDiv.style.height = "auto";
  30313. _this._statsSubsetDiv.style.maxHeight = "240px";
  30314. _this._optionsDiv.style.left = "0px";
  30315. _this._optionsDiv.style.top = "10px";
  30316. _this._optionsDiv.style.width = "200px";
  30317. _this._optionsDiv.style.height = "auto";
  30318. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  30319. _this._logDiv.style.left = "0px";
  30320. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  30321. _this._logDiv.style.width = "600px";
  30322. _this._logDiv.style.height = "160px";
  30323. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  30324. _this._treeDiv.style.top = "10px";
  30325. _this._treeDiv.style.width = "300px";
  30326. _this._treeDiv.style.height = "auto";
  30327. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  30328. }
  30329. _this._globalDiv.style.left = canvasRect.left + "px";
  30330. _this._globalDiv.style.top = canvasRect.top + "px";
  30331. _this._drawingCanvas.style.left = "0px";
  30332. _this._drawingCanvas.style.top = "0px";
  30333. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  30334. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  30335. var devicePixelRatio = window.devicePixelRatio || 1;
  30336. var context = _this._drawingContext;
  30337. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  30338. context.mozBackingStorePixelRatio ||
  30339. context.msBackingStorePixelRatio ||
  30340. context.oBackingStorePixelRatio ||
  30341. context.backingStorePixelRatio || 1;
  30342. _this._ratio = devicePixelRatio / backingStoreRatio;
  30343. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  30344. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  30345. };
  30346. this._onCanvasClick = function (evt) {
  30347. _this._clickPosition = {
  30348. x: evt.clientX * _this._ratio,
  30349. y: evt.clientY * _this._ratio
  30350. };
  30351. };
  30352. this._syncUI = function () {
  30353. if (_this._showUI) {
  30354. if (_this._displayStatistics) {
  30355. _this._displayStats();
  30356. _this._statsDiv.style.display = "";
  30357. }
  30358. else {
  30359. _this._statsDiv.style.display = "none";
  30360. }
  30361. if (_this._displayLogs) {
  30362. _this._logDiv.style.display = "";
  30363. }
  30364. else {
  30365. _this._logDiv.style.display = "none";
  30366. }
  30367. if (_this._displayTree) {
  30368. _this._treeDiv.style.display = "";
  30369. if (_this._needToRefreshMeshesTree) {
  30370. _this._needToRefreshMeshesTree = false;
  30371. _this._refreshMeshesTreeContent();
  30372. }
  30373. }
  30374. else {
  30375. _this._treeDiv.style.display = "none";
  30376. }
  30377. }
  30378. };
  30379. this._syncData = function () {
  30380. if (_this._labelsEnabled || !_this._showUI) {
  30381. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  30382. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  30383. var engine = _this._scene.getEngine();
  30384. var viewport = _this._camera.viewport;
  30385. var globalViewport = viewport.toGlobal(engine);
  30386. // Meshes
  30387. var meshes = _this._camera.getActiveMeshes();
  30388. for (var index = 0; index < meshes.length; index++) {
  30389. var mesh = meshes.data[index];
  30390. var position = mesh.getBoundingInfo().boundingSphere.center;
  30391. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30392. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  30393. _this._renderAxis(projectedPosition, mesh, globalViewport);
  30394. }
  30395. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  30396. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  30397. }
  30398. }
  30399. // Cameras
  30400. var cameras = _this._scene.cameras;
  30401. for (index = 0; index < cameras.length; index++) {
  30402. var camera = cameras[index];
  30403. if (camera === _this._camera) {
  30404. continue;
  30405. }
  30406. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  30407. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  30408. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  30409. _this._camera.detachControl(engine.getRenderingCanvas());
  30410. _this._camera = camera;
  30411. _this._camera.attachControl(engine.getRenderingCanvas());
  30412. }, function () { return "purple"; });
  30413. }
  30414. }
  30415. // Lights
  30416. var lights = _this._scene.lights;
  30417. for (index = 0; index < lights.length; index++) {
  30418. var light = lights[index];
  30419. if (light.position) {
  30420. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  30421. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  30422. _this._renderLabel(light.name, projectedPosition, -20, function () {
  30423. light.setEnabled(!light.isEnabled());
  30424. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  30425. }
  30426. }
  30427. }
  30428. }
  30429. _this._clickPosition = undefined;
  30430. };
  30431. }
  30432. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  30433. while (this._treeSubsetDiv.hasChildNodes()) {
  30434. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  30435. }
  30436. // Add meshes
  30437. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  30438. sortedArray.sort(function (a, b) {
  30439. if (a.name === b.name) {
  30440. return 0;
  30441. }
  30442. return (a.name > b.name) ? 1 : -1;
  30443. });
  30444. for (var index = 0; index < sortedArray.length; index++) {
  30445. var mesh = sortedArray[index];
  30446. if (!mesh.isEnabled()) {
  30447. continue;
  30448. }
  30449. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  30450. m.isVisible = element.checked;
  30451. }, mesh);
  30452. }
  30453. };
  30454. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  30455. this._drawingContext.beginPath();
  30456. this._drawingContext.moveTo(zero.x, zero.y);
  30457. this._drawingContext.lineTo(unit.x, unit.y);
  30458. this._drawingContext.strokeStyle = color;
  30459. this._drawingContext.lineWidth = 4;
  30460. this._drawingContext.stroke();
  30461. this._drawingContext.font = "normal 14px Segoe UI";
  30462. this._drawingContext.fillStyle = color;
  30463. this._drawingContext.fillText(label, unitText.x, unitText.y);
  30464. };
  30465. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  30466. var position = mesh.getBoundingInfo().boundingSphere.center;
  30467. var worldMatrix = mesh.getWorldMatrix();
  30468. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  30469. var unit = (unprojectedVector.subtract(position)).length();
  30470. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30471. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30472. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  30473. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30474. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  30475. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  30476. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  30477. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  30478. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  30479. };
  30480. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  30481. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  30482. this._drawingContext.font = "normal 12px Segoe UI";
  30483. var textMetrics = this._drawingContext.measureText(text);
  30484. var centerX = projectedPosition.x - textMetrics.width / 2;
  30485. var centerY = projectedPosition.y;
  30486. var clientRect = this._drawingCanvas.getBoundingClientRect();
  30487. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  30488. onClick();
  30489. }
  30490. this._drawingContext.beginPath();
  30491. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  30492. this._drawingContext.fillStyle = getFillStyle();
  30493. this._drawingContext.globalAlpha = 0.5;
  30494. this._drawingContext.fill();
  30495. this._drawingContext.globalAlpha = 1.0;
  30496. this._drawingContext.strokeStyle = '#FFFFFF';
  30497. this._drawingContext.lineWidth = 1;
  30498. this._drawingContext.stroke();
  30499. this._drawingContext.fillStyle = "#FFFFFF";
  30500. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  30501. this._drawingContext.beginPath();
  30502. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  30503. this._drawingContext.fill();
  30504. }
  30505. };
  30506. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  30507. if (!this._clickPosition) {
  30508. return false;
  30509. }
  30510. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  30511. return false;
  30512. }
  30513. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  30514. return false;
  30515. }
  30516. return true;
  30517. };
  30518. DebugLayer.prototype.isVisible = function () {
  30519. return this._enabled;
  30520. };
  30521. DebugLayer.prototype.hide = function () {
  30522. if (!this._enabled) {
  30523. return;
  30524. }
  30525. this._enabled = false;
  30526. var engine = this._scene.getEngine();
  30527. this._scene.unregisterBeforeRender(this._syncData);
  30528. this._scene.unregisterAfterRender(this._syncUI);
  30529. document.body.removeChild(this._globalDiv);
  30530. window.removeEventListener("resize", this._syncPositions);
  30531. this._scene.forceShowBoundingBoxes = false;
  30532. this._scene.forceWireframe = false;
  30533. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  30534. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  30535. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  30536. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  30537. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  30538. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  30539. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  30540. this._scene.shadowsEnabled = true;
  30541. this._scene.particlesEnabled = true;
  30542. this._scene.postProcessesEnabled = true;
  30543. this._scene.collisionsEnabled = true;
  30544. this._scene.lightsEnabled = true;
  30545. this._scene.texturesEnabled = true;
  30546. this._scene.lensFlaresEnabled = true;
  30547. this._scene.proceduralTexturesEnabled = true;
  30548. this._scene.renderTargetsEnabled = true;
  30549. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  30550. };
  30551. DebugLayer.prototype.show = function (showUI, camera) {
  30552. if (showUI === void 0) { showUI = true; }
  30553. if (camera === void 0) { camera = null; }
  30554. if (this._enabled) {
  30555. return;
  30556. }
  30557. this._enabled = true;
  30558. if (camera) {
  30559. this._camera = camera;
  30560. }
  30561. else {
  30562. this._camera = this._scene.activeCamera;
  30563. }
  30564. this._showUI = showUI;
  30565. var engine = this._scene.getEngine();
  30566. this._globalDiv = document.createElement("div");
  30567. document.body.appendChild(this._globalDiv);
  30568. this._generateDOMelements();
  30569. window.addEventListener("resize", this._syncPositions);
  30570. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  30571. this._syncPositions();
  30572. this._scene.registerBeforeRender(this._syncData);
  30573. this._scene.registerAfterRender(this._syncUI);
  30574. };
  30575. DebugLayer.prototype._clearLabels = function () {
  30576. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  30577. for (var index = 0; index < this._scene.meshes.length; index++) {
  30578. var mesh = this._scene.meshes[index];
  30579. mesh.renderOverlay = false;
  30580. }
  30581. };
  30582. DebugLayer.prototype._generateheader = function (root, text) {
  30583. var header = document.createElement("div");
  30584. header.innerHTML = text + "&nbsp;";
  30585. header.style.textAlign = "right";
  30586. header.style.width = "100%";
  30587. header.style.color = "white";
  30588. header.style.backgroundColor = "Black";
  30589. header.style.padding = "5px 5px 4px 0px";
  30590. header.style.marginLeft = "-5px";
  30591. header.style.fontWeight = "bold";
  30592. root.appendChild(header);
  30593. };
  30594. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  30595. var label = document.createElement("label");
  30596. label.innerHTML = title;
  30597. label.style.color = color;
  30598. root.appendChild(label);
  30599. root.appendChild(document.createElement("br"));
  30600. };
  30601. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  30602. if (tag === void 0) { tag = null; }
  30603. var label = document.createElement("label");
  30604. var boundingBoxesCheckbox = document.createElement("input");
  30605. boundingBoxesCheckbox.type = "checkbox";
  30606. boundingBoxesCheckbox.checked = initialState;
  30607. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  30608. task(evt.target, tag);
  30609. });
  30610. label.appendChild(boundingBoxesCheckbox);
  30611. var container = document.createElement("span");
  30612. var leftPart = document.createElement("span");
  30613. var rightPart = document.createElement("span");
  30614. rightPart.style.cssFloat = "right";
  30615. leftPart.innerHTML = leftTitle;
  30616. rightPart.innerHTML = rightTitle;
  30617. rightPart.style.fontSize = "12px";
  30618. rightPart.style.maxWidth = "200px";
  30619. container.appendChild(leftPart);
  30620. container.appendChild(rightPart);
  30621. label.appendChild(container);
  30622. root.appendChild(label);
  30623. root.appendChild(document.createElement("br"));
  30624. };
  30625. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  30626. if (tag === void 0) { tag = null; }
  30627. var label = document.createElement("label");
  30628. var checkBox = document.createElement("input");
  30629. checkBox.type = "checkbox";
  30630. checkBox.checked = initialState;
  30631. checkBox.addEventListener("change", function (evt) {
  30632. task(evt.target, tag);
  30633. });
  30634. label.appendChild(checkBox);
  30635. label.appendChild(document.createTextNode(title));
  30636. root.appendChild(label);
  30637. root.appendChild(document.createElement("br"));
  30638. };
  30639. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  30640. if (tag === void 0) { tag = null; }
  30641. var button = document.createElement("button");
  30642. button.innerHTML = title;
  30643. button.style.height = "24px";
  30644. button.style.color = "#444444";
  30645. button.style.border = "1px solid white";
  30646. button.className = "debugLayerButton";
  30647. button.addEventListener("click", function (evt) {
  30648. task(evt.target, tag);
  30649. });
  30650. root.appendChild(button);
  30651. root.appendChild(document.createElement("br"));
  30652. };
  30653. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  30654. if (tag === void 0) { tag = null; }
  30655. var label = document.createElement("label");
  30656. var boundingBoxesRadio = document.createElement("input");
  30657. boundingBoxesRadio.type = "radio";
  30658. boundingBoxesRadio.name = name;
  30659. boundingBoxesRadio.checked = initialState;
  30660. boundingBoxesRadio.addEventListener("change", function (evt) {
  30661. task(evt.target, tag);
  30662. });
  30663. label.appendChild(boundingBoxesRadio);
  30664. label.appendChild(document.createTextNode(title));
  30665. root.appendChild(label);
  30666. root.appendChild(document.createElement("br"));
  30667. };
  30668. DebugLayer.prototype._generateDOMelements = function () {
  30669. var _this = this;
  30670. this._globalDiv.id = "DebugLayer";
  30671. this._globalDiv.style.position = "absolute";
  30672. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  30673. this._globalDiv.style.fontSize = "14px";
  30674. this._globalDiv.style.color = "white";
  30675. // Drawing canvas
  30676. this._drawingCanvas = document.createElement("canvas");
  30677. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  30678. this._drawingCanvas.style.position = "absolute";
  30679. this._drawingCanvas.style.pointerEvents = "none";
  30680. this._drawingContext = this._drawingCanvas.getContext("2d");
  30681. this._globalDiv.appendChild(this._drawingCanvas);
  30682. if (this._showUI) {
  30683. var background = "rgba(128, 128, 128, 0.4)";
  30684. var border = "rgb(180, 180, 180) solid 1px";
  30685. // Stats
  30686. this._statsDiv = document.createElement("div");
  30687. this._statsDiv.id = "DebugLayerStats";
  30688. this._statsDiv.style.border = border;
  30689. this._statsDiv.style.position = "absolute";
  30690. this._statsDiv.style.background = background;
  30691. this._statsDiv.style.padding = "0px 0px 0px 5px";
  30692. this._generateheader(this._statsDiv, "STATISTICS");
  30693. this._statsSubsetDiv = document.createElement("div");
  30694. this._statsSubsetDiv.style.paddingTop = "5px";
  30695. this._statsSubsetDiv.style.paddingBottom = "5px";
  30696. this._statsSubsetDiv.style.overflowY = "auto";
  30697. this._statsDiv.appendChild(this._statsSubsetDiv);
  30698. // Tree
  30699. this._treeDiv = document.createElement("div");
  30700. this._treeDiv.id = "DebugLayerTree";
  30701. this._treeDiv.style.border = border;
  30702. this._treeDiv.style.position = "absolute";
  30703. this._treeDiv.style.background = background;
  30704. this._treeDiv.style.padding = "0px 0px 0px 5px";
  30705. this._treeDiv.style.display = "none";
  30706. this._generateheader(this._treeDiv, "MESHES TREE");
  30707. this._treeSubsetDiv = document.createElement("div");
  30708. this._treeSubsetDiv.style.paddingTop = "5px";
  30709. this._treeSubsetDiv.style.paddingRight = "5px";
  30710. this._treeSubsetDiv.style.overflowY = "auto";
  30711. this._treeSubsetDiv.style.maxHeight = "300px";
  30712. this._treeDiv.appendChild(this._treeSubsetDiv);
  30713. this._needToRefreshMeshesTree = true;
  30714. // Logs
  30715. this._logDiv = document.createElement("div");
  30716. this._logDiv.style.border = border;
  30717. this._logDiv.id = "DebugLayerLogs";
  30718. this._logDiv.style.position = "absolute";
  30719. this._logDiv.style.background = background;
  30720. this._logDiv.style.padding = "0px 0px 0px 5px";
  30721. this._logDiv.style.display = "none";
  30722. this._generateheader(this._logDiv, "LOGS");
  30723. this._logSubsetDiv = document.createElement("div");
  30724. this._logSubsetDiv.style.height = "127px";
  30725. this._logSubsetDiv.style.paddingTop = "5px";
  30726. this._logSubsetDiv.style.overflowY = "auto";
  30727. this._logSubsetDiv.style.fontSize = "12px";
  30728. this._logSubsetDiv.style.fontFamily = "consolas";
  30729. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  30730. this._logDiv.appendChild(this._logSubsetDiv);
  30731. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  30732. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  30733. };
  30734. // Options
  30735. this._optionsDiv = document.createElement("div");
  30736. this._optionsDiv.id = "DebugLayerOptions";
  30737. this._optionsDiv.style.border = border;
  30738. this._optionsDiv.style.position = "absolute";
  30739. this._optionsDiv.style.background = background;
  30740. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  30741. this._optionsDiv.style.overflowY = "auto";
  30742. this._generateheader(this._optionsDiv, "OPTIONS");
  30743. this._optionsSubsetDiv = document.createElement("div");
  30744. this._optionsSubsetDiv.style.paddingTop = "5px";
  30745. this._optionsSubsetDiv.style.paddingBottom = "5px";
  30746. this._optionsSubsetDiv.style.overflowY = "auto";
  30747. this._optionsSubsetDiv.style.maxHeight = "200px";
  30748. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  30749. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  30750. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  30751. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  30752. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  30753. _this._displayTree = element.checked;
  30754. _this._needToRefreshMeshesTree = true;
  30755. });
  30756. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30757. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  30758. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  30759. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  30760. _this._labelsEnabled = element.checked;
  30761. if (!_this._labelsEnabled) {
  30762. _this._clearLabels();
  30763. }
  30764. });
  30765. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  30766. if (element.checked) {
  30767. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  30768. }
  30769. else {
  30770. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  30771. }
  30772. });
  30773. ;
  30774. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30775. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  30776. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  30777. if (element.checked) {
  30778. _this._scene.forceWireframe = false;
  30779. _this._scene.forcePointsCloud = false;
  30780. }
  30781. });
  30782. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  30783. if (element.checked) {
  30784. _this._scene.forceWireframe = true;
  30785. _this._scene.forcePointsCloud = false;
  30786. }
  30787. });
  30788. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  30789. if (element.checked) {
  30790. _this._scene.forceWireframe = false;
  30791. _this._scene.forcePointsCloud = true;
  30792. }
  30793. });
  30794. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30795. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  30796. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  30797. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  30798. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  30799. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  30800. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  30801. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  30802. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  30803. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  30804. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30805. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  30806. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  30807. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  30808. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  30809. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  30810. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  30811. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  30812. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  30813. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  30814. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  30815. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  30816. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  30817. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  30818. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  30819. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  30820. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30821. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  30822. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  30823. if (element.checked) {
  30824. _this._scene.headphone = true;
  30825. }
  30826. });
  30827. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  30828. if (element.checked) {
  30829. _this._scene.headphone = false;
  30830. }
  30831. });
  30832. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  30833. _this._scene.audioEnabled = !element.checked;
  30834. });
  30835. }
  30836. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30837. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  30838. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  30839. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  30840. this._globalDiv.appendChild(this._statsDiv);
  30841. this._globalDiv.appendChild(this._logDiv);
  30842. this._globalDiv.appendChild(this._optionsDiv);
  30843. this._globalDiv.appendChild(this._treeDiv);
  30844. }
  30845. };
  30846. DebugLayer.prototype._displayStats = function () {
  30847. var scene = this._scene;
  30848. var engine = scene.getEngine();
  30849. var glInfo = engine.getGlInfo();
  30850. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  30851. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30852. + "<b>Count</b><br>"
  30853. + "Total meshes: " + scene.meshes.length + "<br>"
  30854. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  30855. + "Total materials: " + scene.materials.length + "<br>"
  30856. + "Total textures: " + scene.textures.length + "<br>"
  30857. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  30858. + "Active indices: " + scene.getActiveIndices() + "<br>"
  30859. + "Active bones: " + scene.getActiveBones() + "<br>"
  30860. + "Active particles: " + scene.getActiveParticles() + "<br>"
  30861. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  30862. + "<b>Duration</b><br>"
  30863. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  30864. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  30865. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  30866. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  30867. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  30868. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  30869. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  30870. + "</div>"
  30871. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  30872. + "<b>Extensions</b><br>"
  30873. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  30874. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  30875. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  30876. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  30877. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  30878. + "<b>Caps.</b><br>"
  30879. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  30880. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  30881. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  30882. + "</div><br>"
  30883. + "<b>Info</b><br>"
  30884. + glInfo.version + "<br>"
  30885. + glInfo.renderer + "<br>";
  30886. if (this.customStatsFunction) {
  30887. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  30888. }
  30889. };
  30890. return DebugLayer;
  30891. })();
  30892. BABYLON.DebugLayer = DebugLayer;
  30893. })(BABYLON || (BABYLON = {}));
  30894. var BABYLON;
  30895. (function (BABYLON) {
  30896. var RawTexture = (function (_super) {
  30897. __extends(RawTexture, _super);
  30898. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  30899. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30900. if (invertY === void 0) { invertY = false; }
  30901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30902. _super.call(this, null, scene, !generateMipMaps, invertY);
  30903. this.format = format;
  30904. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  30905. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30906. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30907. }
  30908. RawTexture.prototype.update = function (data) {
  30909. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  30910. };
  30911. // Statics
  30912. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30913. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30914. if (invertY === void 0) { invertY = false; }
  30915. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30916. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  30917. };
  30918. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30919. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30920. if (invertY === void 0) { invertY = false; }
  30921. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30922. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30923. };
  30924. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30925. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30926. if (invertY === void 0) { invertY = false; }
  30927. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30928. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  30929. };
  30930. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30931. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30932. if (invertY === void 0) { invertY = false; }
  30933. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30934. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  30935. };
  30936. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  30937. if (generateMipMaps === void 0) { generateMipMaps = true; }
  30938. if (invertY === void 0) { invertY = false; }
  30939. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  30940. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  30941. };
  30942. return RawTexture;
  30943. })(BABYLON.Texture);
  30944. BABYLON.RawTexture = RawTexture;
  30945. })(BABYLON || (BABYLON = {}));
  30946. var BABYLON;
  30947. (function (BABYLON) {
  30948. var IndexedVector2 = (function (_super) {
  30949. __extends(IndexedVector2, _super);
  30950. function IndexedVector2(original, index) {
  30951. _super.call(this, original.x, original.y);
  30952. this.index = index;
  30953. }
  30954. return IndexedVector2;
  30955. })(BABYLON.Vector2);
  30956. var PolygonPoints = (function () {
  30957. function PolygonPoints() {
  30958. this.elements = new Array();
  30959. }
  30960. PolygonPoints.prototype.add = function (originalPoints) {
  30961. var _this = this;
  30962. var result = new Array();
  30963. originalPoints.forEach(function (point) {
  30964. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  30965. var newPoint = new IndexedVector2(point, _this.elements.length);
  30966. result.push(newPoint);
  30967. _this.elements.push(newPoint);
  30968. }
  30969. });
  30970. return result;
  30971. };
  30972. PolygonPoints.prototype.computeBounds = function () {
  30973. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30974. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  30975. this.elements.forEach(function (point) {
  30976. // x
  30977. if (point.x < lmin.x) {
  30978. lmin.x = point.x;
  30979. }
  30980. else if (point.x > lmax.x) {
  30981. lmax.x = point.x;
  30982. }
  30983. // y
  30984. if (point.y < lmin.y) {
  30985. lmin.y = point.y;
  30986. }
  30987. else if (point.y > lmax.y) {
  30988. lmax.y = point.y;
  30989. }
  30990. });
  30991. return {
  30992. min: lmin,
  30993. max: lmax,
  30994. width: lmax.x - lmin.x,
  30995. height: lmax.y - lmin.y
  30996. };
  30997. };
  30998. return PolygonPoints;
  30999. })();
  31000. var Polygon = (function () {
  31001. function Polygon() {
  31002. }
  31003. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  31004. return [
  31005. new BABYLON.Vector2(xmin, ymin),
  31006. new BABYLON.Vector2(xmax, ymin),
  31007. new BABYLON.Vector2(xmax, ymax),
  31008. new BABYLON.Vector2(xmin, ymax)
  31009. ];
  31010. };
  31011. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  31012. if (cx === void 0) { cx = 0; }
  31013. if (cy === void 0) { cy = 0; }
  31014. if (numberOfSides === void 0) { numberOfSides = 32; }
  31015. var result = new Array();
  31016. var angle = 0;
  31017. var increment = (Math.PI * 2) / numberOfSides;
  31018. for (var i = 0; i < numberOfSides; i++) {
  31019. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  31020. angle -= increment;
  31021. }
  31022. return result;
  31023. };
  31024. Polygon.Parse = function (input) {
  31025. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  31026. var i, result = [];
  31027. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  31028. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  31029. }
  31030. return result;
  31031. };
  31032. Polygon.StartingAt = function (x, y) {
  31033. return BABYLON.Path2.StartingAt(x, y);
  31034. };
  31035. return Polygon;
  31036. })();
  31037. BABYLON.Polygon = Polygon;
  31038. var PolygonMeshBuilder = (function () {
  31039. function PolygonMeshBuilder(name, contours, scene) {
  31040. this._points = new PolygonPoints();
  31041. this._outlinepoints = new PolygonPoints();
  31042. this._holes = [];
  31043. if (!("poly2tri" in window)) {
  31044. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  31045. }
  31046. this._name = name;
  31047. this._scene = scene;
  31048. var points;
  31049. if (contours instanceof BABYLON.Path2) {
  31050. points = contours.getPoints();
  31051. }
  31052. else {
  31053. points = contours;
  31054. }
  31055. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  31056. this._outlinepoints.add(points);
  31057. }
  31058. PolygonMeshBuilder.prototype.addHole = function (hole) {
  31059. this._swctx.addHole(this._points.add(hole));
  31060. var holepoints = new PolygonPoints();
  31061. holepoints.add(hole);
  31062. this._holes.push(holepoints);
  31063. return this;
  31064. };
  31065. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  31066. var _this = this;
  31067. if (updatable === void 0) { updatable = false; }
  31068. var result = new BABYLON.Mesh(this._name, this._scene);
  31069. var normals = [];
  31070. var positions = [];
  31071. var uvs = [];
  31072. var bounds = this._points.computeBounds();
  31073. this._points.elements.forEach(function (p) {
  31074. normals.push(0, 1.0, 0);
  31075. positions.push(p.x, 0, p.y);
  31076. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  31077. });
  31078. var indices = [];
  31079. this._swctx.triangulate();
  31080. this._swctx.getTriangles().forEach(function (triangle) {
  31081. triangle.getPoints().forEach(function (point) {
  31082. indices.push(point.index);
  31083. });
  31084. });
  31085. if (depth > 0) {
  31086. var positionscount = (positions.length / 3); //get the current pointcount
  31087. this._points.elements.forEach(function (p) {
  31088. normals.push(0, -1.0, 0);
  31089. positions.push(p.x, -depth, p.y);
  31090. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  31091. });
  31092. var p1; //we need to change order of point so the triangles are made in the rigth way.
  31093. var p2;
  31094. var poscounter = 0;
  31095. this._swctx.getTriangles().forEach(function (triangle) {
  31096. triangle.getPoints().forEach(function (point) {
  31097. switch (poscounter) {
  31098. case 0:
  31099. p1 = point;
  31100. break;
  31101. case 1:
  31102. p2 = point;
  31103. break;
  31104. case 2:
  31105. indices.push(point.index + positionscount);
  31106. indices.push(p2.index + positionscount);
  31107. indices.push(p1.index + positionscount);
  31108. poscounter = -1;
  31109. break;
  31110. }
  31111. poscounter++;
  31112. //indices.push((<IndexedVector2>point).index + positionscount);
  31113. });
  31114. });
  31115. //Add the sides
  31116. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  31117. this._holes.forEach(function (hole) {
  31118. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  31119. });
  31120. }
  31121. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  31122. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  31123. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  31124. result.setIndices(indices);
  31125. return result;
  31126. };
  31127. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  31128. var StartIndex = positions.length / 3;
  31129. var ulength = 0;
  31130. for (var i = 0; i < points.elements.length; i++) {
  31131. var p = points.elements[i];
  31132. var p1;
  31133. if ((i + 1) > points.elements.length - 1) {
  31134. p1 = points.elements[0];
  31135. }
  31136. else {
  31137. p1 = points.elements[i + 1];
  31138. }
  31139. positions.push(p.x, 0, p.y);
  31140. positions.push(p.x, -depth, p.y);
  31141. positions.push(p1.x, 0, p1.y);
  31142. positions.push(p1.x, -depth, p1.y);
  31143. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  31144. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  31145. var v3 = v2.subtract(v1);
  31146. var v4 = new BABYLON.Vector3(0, 1, 0);
  31147. var vn = BABYLON.Vector3.Cross(v3, v4);
  31148. vn = vn.normalize();
  31149. uvs.push(ulength / bounds.width, 0);
  31150. uvs.push(ulength / bounds.width, 1);
  31151. ulength += v3.length();
  31152. uvs.push((ulength / bounds.width), 0);
  31153. uvs.push((ulength / bounds.width), 1);
  31154. if (!flip) {
  31155. normals.push(-vn.x, -vn.y, -vn.z);
  31156. normals.push(-vn.x, -vn.y, -vn.z);
  31157. normals.push(-vn.x, -vn.y, -vn.z);
  31158. normals.push(-vn.x, -vn.y, -vn.z);
  31159. indices.push(StartIndex);
  31160. indices.push(StartIndex + 1);
  31161. indices.push(StartIndex + 2);
  31162. indices.push(StartIndex + 1);
  31163. indices.push(StartIndex + 3);
  31164. indices.push(StartIndex + 2);
  31165. }
  31166. else {
  31167. normals.push(vn.x, vn.y, vn.z);
  31168. normals.push(vn.x, vn.y, vn.z);
  31169. normals.push(vn.x, vn.y, vn.z);
  31170. normals.push(vn.x, vn.y, vn.z);
  31171. indices.push(StartIndex);
  31172. indices.push(StartIndex + 2);
  31173. indices.push(StartIndex + 1);
  31174. indices.push(StartIndex + 1);
  31175. indices.push(StartIndex + 2);
  31176. indices.push(StartIndex + 3);
  31177. }
  31178. StartIndex += 4;
  31179. }
  31180. ;
  31181. };
  31182. return PolygonMeshBuilder;
  31183. })();
  31184. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  31185. })(BABYLON || (BABYLON = {}));
  31186. var BABYLON;
  31187. (function (BABYLON) {
  31188. var SimplificationSettings = (function () {
  31189. function SimplificationSettings(quality, distance, optimizeMesh) {
  31190. this.quality = quality;
  31191. this.distance = distance;
  31192. this.optimizeMesh = optimizeMesh;
  31193. }
  31194. return SimplificationSettings;
  31195. })();
  31196. BABYLON.SimplificationSettings = SimplificationSettings;
  31197. var SimplificationQueue = (function () {
  31198. function SimplificationQueue() {
  31199. this.running = false;
  31200. this._simplificationArray = [];
  31201. }
  31202. SimplificationQueue.prototype.addTask = function (task) {
  31203. this._simplificationArray.push(task);
  31204. };
  31205. SimplificationQueue.prototype.executeNext = function () {
  31206. var task = this._simplificationArray.pop();
  31207. if (task) {
  31208. this.running = true;
  31209. this.runSimplification(task);
  31210. }
  31211. else {
  31212. this.running = false;
  31213. }
  31214. };
  31215. SimplificationQueue.prototype.runSimplification = function (task) {
  31216. var _this = this;
  31217. if (task.parallelProcessing) {
  31218. //parallel simplifier
  31219. task.settings.forEach(function (setting) {
  31220. var simplifier = _this.getSimplifier(task);
  31221. simplifier.simplify(setting, function (newMesh) {
  31222. task.mesh.addLODLevel(setting.distance, newMesh);
  31223. newMesh.isVisible = true;
  31224. //check if it is the last
  31225. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  31226. //all done, run the success callback.
  31227. task.successCallback();
  31228. }
  31229. _this.executeNext();
  31230. });
  31231. });
  31232. }
  31233. else {
  31234. //single simplifier.
  31235. var simplifier = this.getSimplifier(task);
  31236. var runDecimation = function (setting, callback) {
  31237. simplifier.simplify(setting, function (newMesh) {
  31238. task.mesh.addLODLevel(setting.distance, newMesh);
  31239. newMesh.isVisible = true;
  31240. //run the next quality level
  31241. callback();
  31242. });
  31243. };
  31244. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  31245. runDecimation(task.settings[loop.index], function () {
  31246. loop.executeNext();
  31247. });
  31248. }, function () {
  31249. //execution ended, run the success callback.
  31250. if (task.successCallback) {
  31251. task.successCallback();
  31252. }
  31253. _this.executeNext();
  31254. });
  31255. }
  31256. };
  31257. SimplificationQueue.prototype.getSimplifier = function (task) {
  31258. switch (task.simplificationType) {
  31259. case SimplificationType.QUADRATIC:
  31260. default:
  31261. return new QuadraticErrorSimplification(task.mesh);
  31262. }
  31263. };
  31264. return SimplificationQueue;
  31265. })();
  31266. BABYLON.SimplificationQueue = SimplificationQueue;
  31267. /**
  31268. * The implemented types of simplification.
  31269. * At the moment only Quadratic Error Decimation is implemented.
  31270. */
  31271. (function (SimplificationType) {
  31272. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  31273. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  31274. var SimplificationType = BABYLON.SimplificationType;
  31275. var DecimationTriangle = (function () {
  31276. function DecimationTriangle(vertices) {
  31277. this.vertices = vertices;
  31278. this.error = new Array(4);
  31279. this.deleted = false;
  31280. this.isDirty = false;
  31281. this.deletePending = false;
  31282. this.borderFactor = 0;
  31283. }
  31284. return DecimationTriangle;
  31285. })();
  31286. BABYLON.DecimationTriangle = DecimationTriangle;
  31287. var DecimationVertex = (function () {
  31288. function DecimationVertex(position, id) {
  31289. this.position = position;
  31290. this.id = id;
  31291. this.isBorder = true;
  31292. this.q = new QuadraticMatrix();
  31293. this.triangleCount = 0;
  31294. this.triangleStart = 0;
  31295. this.originalOffsets = [];
  31296. }
  31297. DecimationVertex.prototype.updatePosition = function (newPosition) {
  31298. this.position.copyFrom(newPosition);
  31299. };
  31300. return DecimationVertex;
  31301. })();
  31302. BABYLON.DecimationVertex = DecimationVertex;
  31303. var QuadraticMatrix = (function () {
  31304. function QuadraticMatrix(data) {
  31305. this.data = new Array(10);
  31306. for (var i = 0; i < 10; ++i) {
  31307. if (data && data[i]) {
  31308. this.data[i] = data[i];
  31309. }
  31310. else {
  31311. this.data[i] = 0;
  31312. }
  31313. }
  31314. }
  31315. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  31316. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  31317. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  31318. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  31319. return det;
  31320. };
  31321. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  31322. for (var i = 0; i < 10; ++i) {
  31323. this.data[i] += matrix.data[i];
  31324. }
  31325. };
  31326. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  31327. for (var i = 0; i < 10; ++i) {
  31328. this.data[i] += data[i];
  31329. }
  31330. };
  31331. QuadraticMatrix.prototype.add = function (matrix) {
  31332. var m = new QuadraticMatrix();
  31333. for (var i = 0; i < 10; ++i) {
  31334. m.data[i] = this.data[i] + matrix.data[i];
  31335. }
  31336. return m;
  31337. };
  31338. QuadraticMatrix.FromData = function (a, b, c, d) {
  31339. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  31340. };
  31341. //returning an array to avoid garbage collection
  31342. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  31343. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  31344. };
  31345. return QuadraticMatrix;
  31346. })();
  31347. BABYLON.QuadraticMatrix = QuadraticMatrix;
  31348. var Reference = (function () {
  31349. function Reference(vertexId, triangleId) {
  31350. this.vertexId = vertexId;
  31351. this.triangleId = triangleId;
  31352. }
  31353. return Reference;
  31354. })();
  31355. BABYLON.Reference = Reference;
  31356. /**
  31357. * An implementation of the Quadratic Error simplification algorithm.
  31358. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  31359. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  31360. * @author RaananW
  31361. */
  31362. var QuadraticErrorSimplification = (function () {
  31363. function QuadraticErrorSimplification(_mesh) {
  31364. this._mesh = _mesh;
  31365. this.initialized = false;
  31366. this.syncIterations = 5000;
  31367. this.aggressiveness = 7;
  31368. this.decimationIterations = 100;
  31369. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  31370. }
  31371. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  31372. var _this = this;
  31373. this.initDecimatedMesh();
  31374. //iterating through the submeshes array, one after the other.
  31375. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  31376. _this.initWithMesh(loop.index, function () {
  31377. _this.runDecimation(settings, loop.index, function () {
  31378. loop.executeNext();
  31379. });
  31380. }, settings.optimizeMesh);
  31381. }, function () {
  31382. setTimeout(function () {
  31383. successCallback(_this._reconstructedMesh);
  31384. }, 0);
  31385. });
  31386. };
  31387. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  31388. var _this = this;
  31389. var gCount = 0;
  31390. triangle.vertices.forEach(function (vertex) {
  31391. var count = 0;
  31392. var vPos = vertex.position;
  31393. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  31394. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  31395. ++count;
  31396. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  31397. ++count;
  31398. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  31399. ++count;
  31400. if (count > 1) {
  31401. ++gCount;
  31402. }
  31403. ;
  31404. });
  31405. if (gCount > 1) {
  31406. console.log(triangle, gCount);
  31407. }
  31408. return gCount > 1;
  31409. };
  31410. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  31411. var _this = this;
  31412. var targetCount = ~~(this.triangles.length * settings.quality);
  31413. var deletedTriangles = 0;
  31414. var triangleCount = this.triangles.length;
  31415. var iterationFunction = function (iteration, callback) {
  31416. setTimeout(function () {
  31417. if (iteration % 5 === 0) {
  31418. _this.updateMesh(iteration === 0);
  31419. }
  31420. for (var i = 0; i < _this.triangles.length; ++i) {
  31421. _this.triangles[i].isDirty = false;
  31422. }
  31423. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  31424. var trianglesIterator = function (i) {
  31425. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  31426. var t = _this.triangles[tIdx];
  31427. if (!t)
  31428. return;
  31429. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  31430. return;
  31431. }
  31432. for (var j = 0; j < 3; ++j) {
  31433. if (t.error[j] < threshold) {
  31434. var deleted0 = [];
  31435. var deleted1 = [];
  31436. var v0 = t.vertices[j];
  31437. var v1 = t.vertices[(j + 1) % 3];
  31438. if (v0.isBorder !== v1.isBorder)
  31439. continue;
  31440. var p = BABYLON.Vector3.Zero();
  31441. var n = BABYLON.Vector3.Zero();
  31442. var uv = BABYLON.Vector2.Zero();
  31443. var color = new BABYLON.Color4(0, 0, 0, 1);
  31444. _this.calculateError(v0, v1, p, n, uv, color);
  31445. var delTr = [];
  31446. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  31447. continue;
  31448. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  31449. continue;
  31450. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  31451. continue;
  31452. var uniqueArray = [];
  31453. delTr.forEach(function (deletedT) {
  31454. if (uniqueArray.indexOf(deletedT) === -1) {
  31455. deletedT.deletePending = true;
  31456. uniqueArray.push(deletedT);
  31457. }
  31458. });
  31459. if (uniqueArray.length % 2 != 0) {
  31460. continue;
  31461. }
  31462. v0.q = v1.q.add(v0.q);
  31463. v0.updatePosition(p);
  31464. var tStart = _this.references.length;
  31465. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  31466. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  31467. var tCount = _this.references.length - tStart;
  31468. if (tCount <= v0.triangleCount) {
  31469. if (tCount) {
  31470. for (var c = 0; c < tCount; c++) {
  31471. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  31472. }
  31473. }
  31474. }
  31475. else {
  31476. v0.triangleStart = tStart;
  31477. }
  31478. v0.triangleCount = tCount;
  31479. break;
  31480. }
  31481. }
  31482. };
  31483. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  31484. }, 0);
  31485. };
  31486. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  31487. if (triangleCount - deletedTriangles <= targetCount)
  31488. loop.breakLoop();
  31489. else {
  31490. iterationFunction(loop.index, function () {
  31491. loop.executeNext();
  31492. });
  31493. }
  31494. }, function () {
  31495. setTimeout(function () {
  31496. //reconstruct this part of the mesh
  31497. _this.reconstructMesh(submeshIndex);
  31498. successCallback();
  31499. }, 0);
  31500. });
  31501. };
  31502. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  31503. var _this = this;
  31504. this.vertices = [];
  31505. this.triangles = [];
  31506. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31507. var indices = this._mesh.getIndices();
  31508. var submesh = this._mesh.subMeshes[submeshIndex];
  31509. var findInVertices = function (positionToSearch) {
  31510. if (optimizeMesh) {
  31511. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  31512. if (_this.vertices[ii].position.equals(positionToSearch)) {
  31513. return _this.vertices[ii];
  31514. }
  31515. }
  31516. }
  31517. return null;
  31518. };
  31519. var vertexReferences = [];
  31520. var vertexInit = function (i) {
  31521. var offset = i + submesh.verticesStart;
  31522. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  31523. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  31524. vertex.originalOffsets.push(offset);
  31525. if (vertex.id == _this.vertices.length) {
  31526. _this.vertices.push(vertex);
  31527. }
  31528. vertexReferences.push(vertex.id);
  31529. };
  31530. //var totalVertices = mesh.getTotalVertices();
  31531. var totalVertices = submesh.verticesCount;
  31532. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  31533. var indicesInit = function (i) {
  31534. var offset = (submesh.indexStart / 3) + i;
  31535. var pos = (offset * 3);
  31536. var i0 = indices[pos + 0];
  31537. var i1 = indices[pos + 1];
  31538. var i2 = indices[pos + 2];
  31539. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  31540. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  31541. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  31542. var triangle = new DecimationTriangle([v0, v1, v2]);
  31543. triangle.originalOffset = pos;
  31544. _this.triangles.push(triangle);
  31545. };
  31546. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  31547. _this.init(callback);
  31548. });
  31549. });
  31550. };
  31551. QuadraticErrorSimplification.prototype.init = function (callback) {
  31552. var _this = this;
  31553. var triangleInit1 = function (i) {
  31554. var t = _this.triangles[i];
  31555. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  31556. for (var j = 0; j < 3; j++) {
  31557. 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))));
  31558. }
  31559. };
  31560. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  31561. var triangleInit2 = function (i) {
  31562. var t = _this.triangles[i];
  31563. for (var j = 0; j < 3; ++j) {
  31564. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  31565. }
  31566. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31567. };
  31568. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  31569. _this.initialized = true;
  31570. callback();
  31571. });
  31572. });
  31573. };
  31574. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  31575. var newTriangles = [];
  31576. var i;
  31577. for (i = 0; i < this.vertices.length; ++i) {
  31578. this.vertices[i].triangleCount = 0;
  31579. }
  31580. var t;
  31581. var j;
  31582. for (i = 0; i < this.triangles.length; ++i) {
  31583. if (!this.triangles[i].deleted) {
  31584. t = this.triangles[i];
  31585. for (j = 0; j < 3; ++j) {
  31586. t.vertices[j].triangleCount = 1;
  31587. }
  31588. newTriangles.push(t);
  31589. }
  31590. }
  31591. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  31592. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  31593. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  31594. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  31595. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31596. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31597. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31598. var vertexCount = 0;
  31599. for (i = 0; i < this.vertices.length; ++i) {
  31600. var vertex = this.vertices[i];
  31601. vertex.id = vertexCount;
  31602. if (vertex.triangleCount) {
  31603. vertex.originalOffsets.forEach(function (originalOffset) {
  31604. newPositionData.push(vertex.position.x);
  31605. newPositionData.push(vertex.position.y);
  31606. newPositionData.push(vertex.position.z);
  31607. newNormalData.push(normalData[originalOffset * 3]);
  31608. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  31609. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  31610. if (uvs && uvs.length) {
  31611. newUVsData.push(uvs[(originalOffset * 2)]);
  31612. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  31613. }
  31614. else if (colorsData && colorsData.length) {
  31615. newColorsData.push(colorsData[(originalOffset * 4)]);
  31616. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  31617. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  31618. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  31619. }
  31620. ++vertexCount;
  31621. });
  31622. }
  31623. }
  31624. var startingIndex = this._reconstructedMesh.getTotalIndices();
  31625. var startingVertex = this._reconstructedMesh.getTotalVertices();
  31626. var submeshesArray = this._reconstructedMesh.subMeshes;
  31627. this._reconstructedMesh.subMeshes = [];
  31628. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  31629. var originalIndices = this._mesh.getIndices();
  31630. for (i = 0; i < newTriangles.length; ++i) {
  31631. var t = newTriangles[i];
  31632. //now get the new referencing point for each vertex
  31633. [0, 1, 2].forEach(function (idx) {
  31634. var id = originalIndices[t.originalOffset + idx];
  31635. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  31636. if (offset < 0)
  31637. offset = 0;
  31638. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  31639. });
  31640. }
  31641. //overwriting the old vertex buffers and indices.
  31642. this._reconstructedMesh.setIndices(newIndicesArray);
  31643. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  31644. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  31645. if (newUVsData.length > 0)
  31646. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  31647. if (newColorsData.length > 0)
  31648. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  31649. //create submesh
  31650. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  31651. if (submeshIndex > 0) {
  31652. this._reconstructedMesh.subMeshes = [];
  31653. submeshesArray.forEach(function (submesh) {
  31654. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  31655. });
  31656. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  31657. }
  31658. };
  31659. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  31660. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  31661. this._reconstructedMesh.material = this._mesh.material;
  31662. this._reconstructedMesh.parent = this._mesh.parent;
  31663. this._reconstructedMesh.isVisible = false;
  31664. };
  31665. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  31666. for (var i = 0; i < vertex1.triangleCount; ++i) {
  31667. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  31668. if (t.deleted)
  31669. continue;
  31670. var s = this.references[vertex1.triangleStart + i].vertexId;
  31671. var v1 = t.vertices[(s + 1) % 3];
  31672. var v2 = t.vertices[(s + 2) % 3];
  31673. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  31674. deletedArray[i] = true;
  31675. delTr.push(t);
  31676. continue;
  31677. }
  31678. var d1 = v1.position.subtract(point);
  31679. d1 = d1.normalize();
  31680. var d2 = v2.position.subtract(point);
  31681. d2 = d2.normalize();
  31682. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  31683. return true;
  31684. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  31685. deletedArray[i] = false;
  31686. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  31687. return true;
  31688. }
  31689. return false;
  31690. };
  31691. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  31692. var newDeleted = deletedTriangles;
  31693. for (var i = 0; i < vertex.triangleCount; ++i) {
  31694. var ref = this.references[vertex.triangleStart + i];
  31695. var t = this.triangles[ref.triangleId];
  31696. if (t.deleted)
  31697. continue;
  31698. if (deletedArray[i] && t.deletePending) {
  31699. t.deleted = true;
  31700. newDeleted++;
  31701. continue;
  31702. }
  31703. t.vertices[ref.vertexId] = origVertex;
  31704. t.isDirty = true;
  31705. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  31706. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  31707. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  31708. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  31709. this.references.push(ref);
  31710. }
  31711. return newDeleted;
  31712. };
  31713. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  31714. for (var i = 0; i < this.vertices.length; ++i) {
  31715. var vCount = [];
  31716. var vId = [];
  31717. var v = this.vertices[i];
  31718. var j;
  31719. for (j = 0; j < v.triangleCount; ++j) {
  31720. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  31721. for (var ii = 0; ii < 3; ii++) {
  31722. var ofs = 0;
  31723. var vv = triangle.vertices[ii];
  31724. while (ofs < vCount.length) {
  31725. if (vId[ofs] === vv.id)
  31726. break;
  31727. ++ofs;
  31728. }
  31729. if (ofs === vCount.length) {
  31730. vCount.push(1);
  31731. vId.push(vv.id);
  31732. }
  31733. else {
  31734. vCount[ofs]++;
  31735. }
  31736. }
  31737. }
  31738. for (j = 0; j < vCount.length; ++j) {
  31739. if (vCount[j] === 1) {
  31740. this.vertices[vId[j]].isBorder = true;
  31741. }
  31742. else {
  31743. this.vertices[vId[j]].isBorder = false;
  31744. }
  31745. }
  31746. }
  31747. };
  31748. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  31749. if (identifyBorders === void 0) { identifyBorders = false; }
  31750. var i;
  31751. if (!identifyBorders) {
  31752. var newTrianglesVector = [];
  31753. for (i = 0; i < this.triangles.length; ++i) {
  31754. if (!this.triangles[i].deleted) {
  31755. newTrianglesVector.push(this.triangles[i]);
  31756. }
  31757. }
  31758. this.triangles = newTrianglesVector;
  31759. }
  31760. for (i = 0; i < this.vertices.length; ++i) {
  31761. this.vertices[i].triangleCount = 0;
  31762. this.vertices[i].triangleStart = 0;
  31763. }
  31764. var t;
  31765. var j;
  31766. var v;
  31767. for (i = 0; i < this.triangles.length; ++i) {
  31768. t = this.triangles[i];
  31769. for (j = 0; j < 3; ++j) {
  31770. v = t.vertices[j];
  31771. v.triangleCount++;
  31772. }
  31773. }
  31774. var tStart = 0;
  31775. for (i = 0; i < this.vertices.length; ++i) {
  31776. this.vertices[i].triangleStart = tStart;
  31777. tStart += this.vertices[i].triangleCount;
  31778. this.vertices[i].triangleCount = 0;
  31779. }
  31780. var newReferences = new Array(this.triangles.length * 3);
  31781. for (i = 0; i < this.triangles.length; ++i) {
  31782. t = this.triangles[i];
  31783. for (j = 0; j < 3; ++j) {
  31784. v = t.vertices[j];
  31785. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  31786. v.triangleCount++;
  31787. }
  31788. }
  31789. this.references = newReferences;
  31790. if (identifyBorders) {
  31791. this.identifyBorder();
  31792. }
  31793. };
  31794. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  31795. var x = point.x;
  31796. var y = point.y;
  31797. var z = point.z;
  31798. 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
  31799. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  31800. };
  31801. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  31802. var q = vertex1.q.add(vertex2.q);
  31803. var border = vertex1.isBorder && vertex2.isBorder;
  31804. var error = 0;
  31805. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  31806. if (qDet !== 0 && !border) {
  31807. if (!pointResult) {
  31808. pointResult = BABYLON.Vector3.Zero();
  31809. }
  31810. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  31811. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  31812. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  31813. error = this.vertexError(q, pointResult);
  31814. }
  31815. else {
  31816. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  31817. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  31818. var error1 = this.vertexError(q, vertex1.position);
  31819. var error2 = this.vertexError(q, vertex2.position);
  31820. var error3 = this.vertexError(q, p3);
  31821. error = Math.min(error1, error2, error3);
  31822. if (error === error1) {
  31823. if (pointResult) {
  31824. pointResult.copyFrom(vertex1.position);
  31825. }
  31826. }
  31827. else if (error === error2) {
  31828. if (pointResult) {
  31829. pointResult.copyFrom(vertex2.position);
  31830. }
  31831. }
  31832. else {
  31833. if (pointResult) {
  31834. pointResult.copyFrom(p3);
  31835. }
  31836. }
  31837. }
  31838. return error;
  31839. };
  31840. return QuadraticErrorSimplification;
  31841. })();
  31842. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  31843. })(BABYLON || (BABYLON = {}));
  31844. var BABYLON;
  31845. (function (BABYLON) {
  31846. var Analyser = (function () {
  31847. function Analyser(scene) {
  31848. this.SMOOTHING = 0.75;
  31849. this.FFT_SIZE = 512;
  31850. this.BARGRAPHAMPLITUDE = 256;
  31851. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  31852. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  31853. this._scene = scene;
  31854. this._audioEngine = BABYLON.Engine.audioEngine;
  31855. if (this._audioEngine.canUseWebAudio) {
  31856. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  31857. this._webAudioAnalyser.minDecibels = -140;
  31858. this._webAudioAnalyser.maxDecibels = 0;
  31859. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31860. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  31861. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  31862. }
  31863. }
  31864. Analyser.prototype.getFrequencyBinCount = function () {
  31865. if (this._audioEngine.canUseWebAudio) {
  31866. return this._webAudioAnalyser.frequencyBinCount;
  31867. }
  31868. else {
  31869. return 0;
  31870. }
  31871. };
  31872. Analyser.prototype.getByteFrequencyData = function () {
  31873. if (this._audioEngine.canUseWebAudio) {
  31874. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31875. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31876. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  31877. }
  31878. return this._byteFreqs;
  31879. };
  31880. Analyser.prototype.getByteTimeDomainData = function () {
  31881. if (this._audioEngine.canUseWebAudio) {
  31882. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31883. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31884. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  31885. }
  31886. return this._byteTime;
  31887. };
  31888. Analyser.prototype.getFloatFrequencyData = function () {
  31889. if (this._audioEngine.canUseWebAudio) {
  31890. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  31891. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  31892. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  31893. }
  31894. return this._floatFreqs;
  31895. };
  31896. Analyser.prototype.drawDebugCanvas = function () {
  31897. var _this = this;
  31898. if (this._audioEngine.canUseWebAudio) {
  31899. if (!this._debugCanvas) {
  31900. this._debugCanvas = document.createElement("canvas");
  31901. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  31902. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  31903. this._debugCanvas.style.position = "absolute";
  31904. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  31905. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  31906. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  31907. document.body.appendChild(this._debugCanvas);
  31908. this._registerFunc = function () {
  31909. _this.drawDebugCanvas();
  31910. };
  31911. this._scene.registerBeforeRender(this._registerFunc);
  31912. }
  31913. if (this._registerFunc) {
  31914. var workingArray = this.getByteFrequencyData();
  31915. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  31916. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  31917. // Draw the frequency domain chart.
  31918. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  31919. var value = workingArray[i];
  31920. var percent = value / this.BARGRAPHAMPLITUDE;
  31921. var height = this.DEBUGCANVASSIZE.height * percent;
  31922. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  31923. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  31924. var hue = i / this.getFrequencyBinCount() * 360;
  31925. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  31926. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  31927. }
  31928. }
  31929. }
  31930. };
  31931. Analyser.prototype.stopDebugCanvas = function () {
  31932. if (this._debugCanvas) {
  31933. this._scene.unregisterBeforeRender(this._registerFunc);
  31934. this._registerFunc = null;
  31935. document.body.removeChild(this._debugCanvas);
  31936. this._debugCanvas = null;
  31937. this._debugCanvasContext = null;
  31938. }
  31939. };
  31940. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  31941. if (this._audioEngine.canUseWebAudio) {
  31942. inputAudioNode.connect(this._webAudioAnalyser);
  31943. this._webAudioAnalyser.connect(outputAudioNode);
  31944. }
  31945. };
  31946. Analyser.prototype.dispose = function () {
  31947. if (this._audioEngine.canUseWebAudio) {
  31948. this._webAudioAnalyser.disconnect();
  31949. }
  31950. };
  31951. return Analyser;
  31952. })();
  31953. BABYLON.Analyser = Analyser;
  31954. })(BABYLON || (BABYLON = {}));
  31955. var BABYLON;
  31956. (function (BABYLON) {
  31957. var DepthRenderer = (function () {
  31958. function DepthRenderer(scene, type) {
  31959. var _this = this;
  31960. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  31961. this._viewMatrix = BABYLON.Matrix.Zero();
  31962. this._projectionMatrix = BABYLON.Matrix.Zero();
  31963. this._transformMatrix = BABYLON.Matrix.Zero();
  31964. this._worldViewProjection = BABYLON.Matrix.Zero();
  31965. this._scene = scene;
  31966. var engine = scene.getEngine();
  31967. // Render target
  31968. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  31969. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31970. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31971. this._depthMap.refreshRate = 1;
  31972. this._depthMap.renderParticles = false;
  31973. this._depthMap.renderList = null;
  31974. // set default depth value to 1.0 (far away)
  31975. this._depthMap.onClear = function (engine) {
  31976. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  31977. };
  31978. // Custom render function
  31979. var renderSubMesh = function (subMesh) {
  31980. var mesh = subMesh.getRenderingMesh();
  31981. var scene = _this._scene;
  31982. var engine = scene.getEngine();
  31983. // Culling
  31984. engine.setState(subMesh.getMaterial().backFaceCulling);
  31985. // Managing instances
  31986. var batch = mesh._getInstancesRenderList(subMesh._id);
  31987. if (batch.mustReturn) {
  31988. return;
  31989. }
  31990. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31991. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31992. engine.enableEffect(_this._effect);
  31993. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  31994. var material = subMesh.getMaterial();
  31995. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  31996. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  31997. // Alpha test
  31998. if (material && material.needAlphaTesting()) {
  31999. var alphaTexture = material.getAlphaTestTexture();
  32000. _this._effect.setTexture("diffuseSampler", alphaTexture);
  32001. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32002. }
  32003. // Bones
  32004. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32005. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32006. }
  32007. // Draw
  32008. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  32009. }
  32010. };
  32011. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  32012. var index;
  32013. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32014. renderSubMesh(opaqueSubMeshes.data[index]);
  32015. }
  32016. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32017. renderSubMesh(alphaTestSubMeshes.data[index]);
  32018. }
  32019. };
  32020. }
  32021. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  32022. var defines = [];
  32023. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32024. var mesh = subMesh.getMesh();
  32025. var scene = mesh.getScene();
  32026. var material = subMesh.getMaterial();
  32027. // Alpha test
  32028. if (material && material.needAlphaTesting()) {
  32029. defines.push("#define ALPHATEST");
  32030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32031. attribs.push(BABYLON.VertexBuffer.UVKind);
  32032. defines.push("#define UV1");
  32033. }
  32034. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32035. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32036. defines.push("#define UV2");
  32037. }
  32038. }
  32039. // Bones
  32040. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32041. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32042. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32043. defines.push("#define BONES");
  32044. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32045. }
  32046. // Instances
  32047. if (useInstances) {
  32048. defines.push("#define INSTANCES");
  32049. attribs.push("world0");
  32050. attribs.push("world1");
  32051. attribs.push("world2");
  32052. attribs.push("world3");
  32053. }
  32054. // Get correct effect
  32055. var join = defines.join("\n");
  32056. if (this._cachedDefines !== join) {
  32057. this._cachedDefines = join;
  32058. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  32059. }
  32060. return this._effect.isReady();
  32061. };
  32062. DepthRenderer.prototype.getDepthMap = function () {
  32063. return this._depthMap;
  32064. };
  32065. // Methods
  32066. DepthRenderer.prototype.dispose = function () {
  32067. this._depthMap.dispose();
  32068. };
  32069. return DepthRenderer;
  32070. })();
  32071. BABYLON.DepthRenderer = DepthRenderer;
  32072. })(BABYLON || (BABYLON = {}));
  32073. var BABYLON;
  32074. (function (BABYLON) {
  32075. var SSAORenderingPipeline = (function (_super) {
  32076. __extends(SSAORenderingPipeline, _super);
  32077. /**
  32078. * @constructor
  32079. * @param {string} name - The rendering pipeline name
  32080. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32081. * @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 }
  32082. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32083. */
  32084. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  32085. var _this = this;
  32086. _super.call(this, scene.getEngine(), name);
  32087. // Members
  32088. /**
  32089. * The PassPostProcess id in the pipeline that contains the original scene color
  32090. * @type {string}
  32091. */
  32092. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  32093. /**
  32094. * The SSAO PostProcess id in the pipeline
  32095. * @type {string}
  32096. */
  32097. this.SSAORenderEffect = "SSAORenderEffect";
  32098. /**
  32099. * The horizontal blur PostProcess id in the pipeline
  32100. * @type {string}
  32101. */
  32102. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  32103. /**
  32104. * The vertical blur PostProcess id in the pipeline
  32105. * @type {string}
  32106. */
  32107. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  32108. /**
  32109. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  32110. * @type {string}
  32111. */
  32112. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  32113. /**
  32114. * The output strength of the SSAO post-process. Default value is 1.0.
  32115. * @type {number}
  32116. */
  32117. this.totalStrength = 1.0;
  32118. /**
  32119. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  32120. * @type {number}
  32121. */
  32122. this.radius = 0.0002;
  32123. /**
  32124. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  32125. * Must not be equal to fallOff and superior to fallOff.
  32126. * Default value is 0.0075
  32127. * @type {number}
  32128. */
  32129. this.area = 0.0075;
  32130. /**
  32131. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  32132. * Must not be equal to area and inferior to area.
  32133. * Default value is 0.0002
  32134. * @type {number}
  32135. */
  32136. this.fallOff = 0.0002;
  32137. this._firstUpdate = true;
  32138. this._scene = scene;
  32139. // Set up assets
  32140. this._createRandomTexture();
  32141. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32142. var ssaoRatio = ratio.ssaoRatio || ratio;
  32143. var combineRatio = ratio.combineRatio || ratio;
  32144. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32145. this._createSSAOPostProcess(ssaoRatio);
  32146. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32147. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32148. this._createSSAOCombinePostProcess(combineRatio);
  32149. // Set up pipeline
  32150. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  32151. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  32152. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  32153. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  32154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  32155. // Finish
  32156. scene.postProcessRenderPipelineManager.addPipeline(this);
  32157. if (cameras)
  32158. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32159. }
  32160. // Public Methods
  32161. /**
  32162. * Returns the horizontal blur PostProcess
  32163. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  32164. */
  32165. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  32166. return this._blurHPostProcess;
  32167. };
  32168. /**
  32169. * Returns the vertical blur PostProcess
  32170. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  32171. */
  32172. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  32173. return this._blurVPostProcess;
  32174. };
  32175. /**
  32176. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  32177. */
  32178. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32179. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32180. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32181. this._originalColorPostProcess = undefined;
  32182. this._ssaoPostProcess = undefined;
  32183. this._blurHPostProcess = undefined;
  32184. this._blurVPostProcess = undefined;
  32185. this._ssaoCombinePostProcess = undefined;
  32186. this._randomTexture.dispose();
  32187. if (disableDepthRender)
  32188. this._scene.disableDepthRenderer();
  32189. };
  32190. // Private Methods
  32191. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  32192. var _this = this;
  32193. var sampleSphere = [
  32194. 0.5381, 0.1856, -0.4319,
  32195. 0.1379, 0.2486, 0.4430,
  32196. 0.3371, 0.5679, -0.0057,
  32197. -0.6999, -0.0451, -0.0019,
  32198. 0.0689, -0.1598, -0.8547,
  32199. 0.0560, 0.0069, -0.1843,
  32200. -0.0146, 0.1402, 0.0762,
  32201. 0.0100, -0.1924, -0.0344,
  32202. -0.3577, -0.5301, -0.4358,
  32203. -0.3169, 0.1063, 0.0158,
  32204. 0.0103, -0.5869, 0.0046,
  32205. -0.0897, -0.4940, 0.3287,
  32206. 0.7119, -0.0154, -0.0918,
  32207. -0.0533, 0.0596, -0.5411,
  32208. 0.0352, -0.0631, 0.5460,
  32209. -0.4776, 0.2847, -0.0271
  32210. ];
  32211. var samplesFactor = 1.0 / 16.0;
  32212. 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);
  32213. this._ssaoPostProcess.onApply = function (effect) {
  32214. if (_this._firstUpdate) {
  32215. effect.setArray3("sampleSphere", sampleSphere);
  32216. effect.setFloat("samplesFactor", samplesFactor);
  32217. effect.setFloat("randTextureTiles", 4.0 / ratio);
  32218. _this._firstUpdate = false;
  32219. }
  32220. effect.setFloat("totalStrength", _this.totalStrength);
  32221. effect.setFloat("radius", _this.radius);
  32222. effect.setFloat("area", _this.area);
  32223. effect.setFloat("fallOff", _this.fallOff);
  32224. effect.setTexture("textureSampler", _this._depthTexture);
  32225. effect.setTexture("randomSampler", _this._randomTexture);
  32226. };
  32227. };
  32228. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  32229. var _this = this;
  32230. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32231. this._ssaoCombinePostProcess.onApply = function (effect) {
  32232. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  32233. };
  32234. };
  32235. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  32236. var size = 512;
  32237. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32238. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32239. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32240. var context = this._randomTexture.getContext();
  32241. var rand = function (min, max) {
  32242. return Math.random() * (max - min) + min;
  32243. };
  32244. for (var x = 0; x < size; x++) {
  32245. for (var y = 0; y < size; y++) {
  32246. var randVector = BABYLON.Vector3.Zero();
  32247. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  32248. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  32249. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  32250. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  32251. context.fillRect(x, y, 1, 1);
  32252. }
  32253. }
  32254. this._randomTexture.update(false);
  32255. };
  32256. return SSAORenderingPipeline;
  32257. })(BABYLON.PostProcessRenderPipeline);
  32258. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  32259. })(BABYLON || (BABYLON = {}));
  32260. var BABYLON;
  32261. (function (BABYLON) {
  32262. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  32263. var VolumetricLightScatteringPostProcess = (function (_super) {
  32264. __extends(VolumetricLightScatteringPostProcess, _super);
  32265. /**
  32266. * @constructor
  32267. * @param {string} name - The post-process name
  32268. * @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)
  32269. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  32270. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  32271. * @param {number} samples - The post-process quality, default 100
  32272. * @param {number} samplingMode - The post-process filtering mode
  32273. * @param {BABYLON.Engine} engine - The babylon engine
  32274. * @param {boolean} reusable - If the post-process is reusable
  32275. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  32276. */
  32277. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  32278. var _this = this;
  32279. if (samples === void 0) { samples = 100; }
  32280. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  32281. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  32282. this._screenCoordinates = BABYLON.Vector2.Zero();
  32283. /**
  32284. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  32285. * @type {boolean}
  32286. */
  32287. this.useCustomMeshPosition = false;
  32288. /**
  32289. * If the post-process should inverse the light scattering direction
  32290. * @type {boolean}
  32291. */
  32292. this.invert = true;
  32293. /**
  32294. * Set to true to use the diffuseColor instead of the diffuseTexture
  32295. * @type {boolean}
  32296. */
  32297. this.useDiffuseColor = false;
  32298. /**
  32299. * Array containing the excluded meshes not rendered in the internal pass
  32300. */
  32301. this.excludedMeshes = new Array();
  32302. /**
  32303. * Controls the overall intensity of the post-process
  32304. * @type {number}
  32305. */
  32306. this.exposure = 0.3;
  32307. /**
  32308. * Dissipates each sample's contribution in range [0, 1]
  32309. * @type {number}
  32310. */
  32311. this.decay = 0.96815;
  32312. /**
  32313. * Controls the overall intensity of each sample
  32314. * @type {number}
  32315. */
  32316. this.weight = 0.58767;
  32317. /**
  32318. * Controls the density of each sample
  32319. * @type {number}
  32320. */
  32321. this.density = 0.926;
  32322. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  32323. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  32324. // Configure mesh
  32325. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  32326. // Configure
  32327. this._createPass(scene, ratio.passRatio || ratio);
  32328. this.onApply = function (effect) {
  32329. _this._updateMeshScreenCoordinates(scene);
  32330. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  32331. effect.setFloat("exposure", _this.exposure);
  32332. effect.setFloat("decay", _this.decay);
  32333. effect.setFloat("weight", _this.weight);
  32334. effect.setFloat("density", _this.density);
  32335. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  32336. };
  32337. }
  32338. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  32339. var mesh = subMesh.getMesh();
  32340. var defines = [];
  32341. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32342. var material = subMesh.getMaterial();
  32343. var needUV = false;
  32344. // Render this.mesh as default
  32345. if (mesh === this.mesh) {
  32346. if (this.useDiffuseColor) {
  32347. defines.push("#define DIFFUSE_COLOR_RENDER");
  32348. }
  32349. else if (material) {
  32350. if (material.diffuseTexture !== undefined) {
  32351. defines.push("#define BASIC_RENDER");
  32352. }
  32353. else {
  32354. defines.push("#define DIFFUSE_COLOR_RENDER");
  32355. }
  32356. }
  32357. defines.push("#define NEED_UV");
  32358. needUV = true;
  32359. }
  32360. // Alpha test
  32361. if (material) {
  32362. if (material.needAlphaTesting()) {
  32363. defines.push("#define ALPHATEST");
  32364. }
  32365. if (material.opacityTexture !== undefined) {
  32366. defines.push("#define OPACITY");
  32367. if (material.opacityTexture.getAlphaFromRGB) {
  32368. defines.push("#define OPACITYRGB");
  32369. }
  32370. if (!needUV) {
  32371. defines.push("#define NEED_UV");
  32372. }
  32373. }
  32374. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32375. attribs.push(BABYLON.VertexBuffer.UVKind);
  32376. defines.push("#define UV1");
  32377. }
  32378. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32379. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32380. defines.push("#define UV2");
  32381. }
  32382. }
  32383. // Bones
  32384. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32385. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32386. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32387. defines.push("#define BONES");
  32388. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  32389. }
  32390. // Instances
  32391. if (useInstances) {
  32392. defines.push("#define INSTANCES");
  32393. attribs.push("world0");
  32394. attribs.push("world1");
  32395. attribs.push("world2");
  32396. attribs.push("world3");
  32397. }
  32398. // Get correct effect
  32399. var join = defines.join("\n");
  32400. if (this._cachedDefines !== join) {
  32401. this._cachedDefines = join;
  32402. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  32403. }
  32404. return this._volumetricLightScatteringPass.isReady();
  32405. };
  32406. /**
  32407. * Sets the new light position for light scattering effect
  32408. * @param {BABYLON.Vector3} The new custom light position
  32409. */
  32410. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  32411. this._customMeshPosition = position;
  32412. };
  32413. /**
  32414. * Returns the light position for light scattering effect
  32415. * @return {BABYLON.Vector3} The custom light position
  32416. */
  32417. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  32418. return this._customMeshPosition;
  32419. };
  32420. /**
  32421. * Disposes the internal assets and detaches the post-process from the camera
  32422. */
  32423. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  32424. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  32425. if (rttIndex !== -1) {
  32426. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  32427. }
  32428. this._volumetricLightScatteringRTT.dispose();
  32429. _super.prototype.dispose.call(this, camera);
  32430. };
  32431. /**
  32432. * Returns the render target texture used by the post-process
  32433. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  32434. */
  32435. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  32436. return this._volumetricLightScatteringRTT;
  32437. };
  32438. // Private methods
  32439. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  32440. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  32441. return true;
  32442. }
  32443. return false;
  32444. };
  32445. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  32446. var _this = this;
  32447. var engine = scene.getEngine();
  32448. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  32449. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32450. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32451. this._volumetricLightScatteringRTT.renderList = null;
  32452. this._volumetricLightScatteringRTT.renderParticles = false;
  32453. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  32454. // Custom render function for submeshes
  32455. var renderSubMesh = function (subMesh) {
  32456. var mesh = subMesh.getRenderingMesh();
  32457. if (_this._meshExcluded(mesh)) {
  32458. return;
  32459. }
  32460. var scene = mesh.getScene();
  32461. var engine = scene.getEngine();
  32462. // Culling
  32463. engine.setState(subMesh.getMaterial().backFaceCulling);
  32464. // Managing instances
  32465. var batch = mesh._getInstancesRenderList(subMesh._id);
  32466. if (batch.mustReturn) {
  32467. return;
  32468. }
  32469. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  32470. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  32471. engine.enableEffect(_this._volumetricLightScatteringPass);
  32472. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  32473. var material = subMesh.getMaterial();
  32474. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  32475. // Alpha test
  32476. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  32477. var alphaTexture = material.getAlphaTestTexture();
  32478. if ((_this.useDiffuseColor || alphaTexture === undefined) && mesh === _this.mesh) {
  32479. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  32480. }
  32481. if (material.needAlphaTesting() || (mesh === _this.mesh && alphaTexture && !_this.useDiffuseColor)) {
  32482. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  32483. if (alphaTexture) {
  32484. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  32485. }
  32486. }
  32487. if (material.opacityTexture !== undefined) {
  32488. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  32489. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  32490. }
  32491. }
  32492. // Bones
  32493. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  32494. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  32495. }
  32496. // Draw
  32497. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  32498. }
  32499. };
  32500. // Render target texture callbacks
  32501. var savedSceneClearColor;
  32502. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  32503. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  32504. savedSceneClearColor = scene.clearColor;
  32505. scene.clearColor = sceneClearColor;
  32506. };
  32507. this._volumetricLightScatteringRTT.onAfterRender = function () {
  32508. scene.clearColor = savedSceneClearColor;
  32509. };
  32510. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  32511. var engine = scene.getEngine();
  32512. var index;
  32513. for (index = 0; index < opaqueSubMeshes.length; index++) {
  32514. renderSubMesh(opaqueSubMeshes.data[index]);
  32515. }
  32516. engine.setAlphaTesting(true);
  32517. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  32518. renderSubMesh(alphaTestSubMeshes.data[index]);
  32519. }
  32520. engine.setAlphaTesting(false);
  32521. if (transparentSubMeshes.length) {
  32522. // Sort sub meshes
  32523. for (index = 0; index < transparentSubMeshes.length; index++) {
  32524. var submesh = transparentSubMeshes.data[index];
  32525. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  32526. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  32527. }
  32528. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  32529. sortedArray.sort(function (a, b) {
  32530. // Alpha index first
  32531. if (a._alphaIndex > b._alphaIndex) {
  32532. return 1;
  32533. }
  32534. if (a._alphaIndex < b._alphaIndex) {
  32535. return -1;
  32536. }
  32537. // Then distance to camera
  32538. if (a._distanceToCamera < b._distanceToCamera) {
  32539. return 1;
  32540. }
  32541. if (a._distanceToCamera > b._distanceToCamera) {
  32542. return -1;
  32543. }
  32544. return 0;
  32545. });
  32546. // Render sub meshes
  32547. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32548. for (index = 0; index < sortedArray.length; index++) {
  32549. renderSubMesh(sortedArray[index]);
  32550. }
  32551. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32552. }
  32553. };
  32554. };
  32555. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  32556. var transform = scene.getTransformMatrix();
  32557. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  32558. this._screenCoordinates.x = pos.x / this._viewPort.width;
  32559. this._screenCoordinates.y = pos.y / this._viewPort.height;
  32560. if (this.invert)
  32561. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  32562. };
  32563. // Static methods
  32564. /**
  32565. * Creates a default mesh for the Volumeric Light Scattering post-process
  32566. * @param {string} The mesh name
  32567. * @param {BABYLON.Scene} The scene where to create the mesh
  32568. * @return {BABYLON.Mesh} the default mesh
  32569. */
  32570. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  32571. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  32572. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  32573. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  32574. return mesh;
  32575. };
  32576. return VolumetricLightScatteringPostProcess;
  32577. })(BABYLON.PostProcess);
  32578. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  32579. })(BABYLON || (BABYLON = {}));
  32580. var BABYLON;
  32581. (function (BABYLON) {
  32582. var LensRenderingPipeline = (function (_super) {
  32583. __extends(LensRenderingPipeline, _super);
  32584. /**
  32585. * @constructor
  32586. *
  32587. * Effect parameters are as follow:
  32588. * {
  32589. * chromatic_aberration: number; // from 0 to x (1 for realism)
  32590. * edge_blur: number; // from 0 to x (1 for realism)
  32591. * distortion: number; // from 0 to x (1 for realism)
  32592. * grain_amount: number; // from 0 to 1
  32593. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  32594. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  32595. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  32596. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  32597. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  32598. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  32599. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  32600. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  32601. * }
  32602. * Note: if an effect parameter is unset, effect is disabled
  32603. *
  32604. * @param {string} name - The rendering pipeline name
  32605. * @param {object} parameters - An object containing all parameters (see above)
  32606. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32607. * @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)
  32608. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32609. */
  32610. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  32611. var _this = this;
  32612. if (ratio === void 0) { ratio = 1.0; }
  32613. _super.call(this, scene.getEngine(), name);
  32614. // Lens effects can be of the following:
  32615. // - chromatic aberration (slight shift of RGB colors)
  32616. // - blur on the edge of the lens
  32617. // - lens distortion
  32618. // - depth-of-field blur & highlights enhancing
  32619. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  32620. // - grain effect (noise or custom texture)
  32621. // Two additional texture samplers are needed:
  32622. // - depth map (for depth-of-field)
  32623. // - grain texture
  32624. /**
  32625. * The chromatic aberration PostProcess id in the pipeline
  32626. * @type {string}
  32627. */
  32628. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  32629. /**
  32630. * The highlights enhancing PostProcess id in the pipeline
  32631. * @type {string}
  32632. */
  32633. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  32634. /**
  32635. * The depth-of-field PostProcess id in the pipeline
  32636. * @type {string}
  32637. */
  32638. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  32639. this._scene = scene;
  32640. // Fetch texture samplers
  32641. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  32642. if (parameters.grain_texture) {
  32643. this._grainTexture = parameters.grain_texture;
  32644. }
  32645. else {
  32646. this._createGrainTexture();
  32647. }
  32648. // save parameters
  32649. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  32650. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  32651. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  32652. this._distortion = parameters.distortion ? parameters.distortion : 0;
  32653. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  32654. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  32655. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  32656. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  32657. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  32658. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  32659. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  32660. // Create effects
  32661. this._createChromaticAberrationPostProcess(ratio);
  32662. this._createHighlightsPostProcess(ratio);
  32663. this._createDepthOfFieldPostProcess(ratio / 4);
  32664. // Set up pipeline
  32665. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  32666. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  32667. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  32668. if (this._highlightsGain == -1) {
  32669. this._disableEffect(this.HighlightsEnhancingEffect, null);
  32670. }
  32671. // Finish
  32672. scene.postProcessRenderPipelineManager.addPipeline(this);
  32673. if (cameras) {
  32674. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32675. }
  32676. }
  32677. // public methods (self explanatory)
  32678. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  32679. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  32680. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  32681. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  32682. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  32683. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  32684. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  32685. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  32686. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  32687. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  32688. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  32689. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  32690. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  32691. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  32692. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  32693. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  32694. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  32695. this._highlightsGain = amount;
  32696. };
  32697. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  32698. if (this._highlightsGain == -1) {
  32699. this._highlightsGain = 1.0;
  32700. }
  32701. this._highlightsThreshold = amount;
  32702. };
  32703. LensRenderingPipeline.prototype.disableHighlights = function () {
  32704. this._highlightsGain = -1;
  32705. };
  32706. /**
  32707. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  32708. */
  32709. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  32710. if (disableDepthRender === void 0) { disableDepthRender = false; }
  32711. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  32712. this._chromaticAberrationPostProcess = undefined;
  32713. this._highlightsPostProcess = undefined;
  32714. this._depthOfFieldPostProcess = undefined;
  32715. this._grainTexture.dispose();
  32716. if (disableDepthRender)
  32717. this._scene.disableDepthRenderer();
  32718. };
  32719. // colors shifting and distortion
  32720. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  32721. var _this = this;
  32722. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32723. this._chromaticAberrationPostProcess.onApply = function (effect) {
  32724. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  32725. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32726. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32727. };
  32728. };
  32729. // highlights enhancing
  32730. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  32731. var _this = this;
  32732. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32733. this._highlightsPostProcess.onApply = function (effect) {
  32734. effect.setFloat('gain', _this._highlightsGain);
  32735. effect.setFloat('threshold', _this._highlightsThreshold);
  32736. effect.setBool('pentagon', _this._dofPentagon);
  32737. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  32738. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32739. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32740. };
  32741. };
  32742. // colors shifting and distortion
  32743. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  32744. var _this = this;
  32745. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  32746. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  32747. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  32748. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  32749. this._depthOfFieldPostProcess.onApply = function (effect) {
  32750. effect.setTexture("depthSampler", _this._depthTexture);
  32751. effect.setTexture("grainSampler", _this._grainTexture);
  32752. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  32753. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  32754. effect.setFloat('grain_amount', _this._grainAmount);
  32755. effect.setBool('blur_noise', _this._blurNoise);
  32756. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  32757. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  32758. effect.setFloat('distortion', _this._distortion);
  32759. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  32760. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  32761. effect.setFloat('aperture', _this._dofAperture);
  32762. effect.setFloat('darken', _this._dofDarken);
  32763. effect.setFloat('edge_blur', _this._edgeBlur);
  32764. effect.setBool('highlights', (_this._highlightsGain != -1));
  32765. effect.setFloat('near', _this._scene.activeCamera.minZ);
  32766. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  32767. };
  32768. };
  32769. // creates a black and white random noise texture, 512x512
  32770. LensRenderingPipeline.prototype._createGrainTexture = function () {
  32771. var size = 512;
  32772. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32773. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  32774. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  32775. var context = this._grainTexture.getContext();
  32776. var rand = function (min, max) {
  32777. return Math.random() * (max - min) + min;
  32778. };
  32779. var value;
  32780. for (var x = 0; x < size; x++) {
  32781. for (var y = 0; y < size; y++) {
  32782. value = Math.floor(rand(0.42, 0.58) * 255);
  32783. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  32784. context.fillRect(x, y, 1, 1);
  32785. }
  32786. }
  32787. this._grainTexture.update(false);
  32788. };
  32789. return LensRenderingPipeline;
  32790. })(BABYLON.PostProcessRenderPipeline);
  32791. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  32792. })(BABYLON || (BABYLON = {}));
  32793. //
  32794. // This post-process allows the modification of rendered colors by using
  32795. // a 'look-up table' (LUT). This effect is also called Color Grading.
  32796. //
  32797. // The object needs to be provided an url to a texture containing the color
  32798. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  32799. // Use an image editing software to tweak the LUT to match your needs.
  32800. //
  32801. // For an example of a color LUT, see here:
  32802. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  32803. // For explanations on color grading, see here:
  32804. // http://udn.epicgames.com/Three/ColorGrading.html
  32805. //
  32806. var BABYLON;
  32807. (function (BABYLON) {
  32808. var ColorCorrectionPostProcess = (function (_super) {
  32809. __extends(ColorCorrectionPostProcess, _super);
  32810. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  32811. var _this = this;
  32812. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  32813. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  32814. this._colorTableTexture.anisotropicFilteringLevel = 1;
  32815. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32816. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32817. this.onApply = function (effect) {
  32818. effect.setTexture("colorTable", _this._colorTableTexture);
  32819. };
  32820. }
  32821. return ColorCorrectionPostProcess;
  32822. })(BABYLON.PostProcess);
  32823. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  32824. })(BABYLON || (BABYLON = {}));
  32825. var BABYLON;
  32826. (function (BABYLON) {
  32827. var AnaglyphFreeCamera = (function (_super) {
  32828. __extends(AnaglyphFreeCamera, _super);
  32829. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  32830. _super.call(this, name, position, scene);
  32831. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32832. }
  32833. return AnaglyphFreeCamera;
  32834. })(BABYLON.FreeCamera);
  32835. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  32836. var AnaglyphArcRotateCamera = (function (_super) {
  32837. __extends(AnaglyphArcRotateCamera, _super);
  32838. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  32839. _super.call(this, name, alpha, beta, radius, target, scene);
  32840. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32841. }
  32842. return AnaglyphArcRotateCamera;
  32843. })(BABYLON.ArcRotateCamera);
  32844. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  32845. var AnaglyphGamepadCamera = (function (_super) {
  32846. __extends(AnaglyphGamepadCamera, _super);
  32847. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  32848. _super.call(this, name, position, scene);
  32849. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  32850. }
  32851. return AnaglyphGamepadCamera;
  32852. })(BABYLON.GamepadCamera);
  32853. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  32854. var StereoscopicFreeCamera = (function (_super) {
  32855. __extends(StereoscopicFreeCamera, _super);
  32856. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  32857. _super.call(this, name, position, scene);
  32858. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32859. }
  32860. return StereoscopicFreeCamera;
  32861. })(BABYLON.FreeCamera);
  32862. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  32863. var StereoscopicArcRotateCamera = (function (_super) {
  32864. __extends(StereoscopicArcRotateCamera, _super);
  32865. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  32866. _super.call(this, name, alpha, beta, radius, target, scene);
  32867. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32868. }
  32869. return StereoscopicArcRotateCamera;
  32870. })(BABYLON.ArcRotateCamera);
  32871. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  32872. var StereoscopicGamepadCamera = (function (_super) {
  32873. __extends(StereoscopicGamepadCamera, _super);
  32874. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  32875. _super.call(this, name, position, scene);
  32876. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  32877. }
  32878. return StereoscopicGamepadCamera;
  32879. })(BABYLON.GamepadCamera);
  32880. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  32881. })(BABYLON || (BABYLON = {}));
  32882. var BABYLON;
  32883. (function (BABYLON) {
  32884. var HDRRenderingPipeline = (function (_super) {
  32885. __extends(HDRRenderingPipeline, _super);
  32886. /**
  32887. * @constructor
  32888. * @param {string} name - The rendering pipeline name
  32889. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  32890. * @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)
  32891. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  32892. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  32893. */
  32894. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  32895. var _this = this;
  32896. if (originalPostProcess === void 0) { originalPostProcess = null; }
  32897. _super.call(this, scene.getEngine(), name);
  32898. /**
  32899. * Public members
  32900. */
  32901. // Gaussian Blur
  32902. /**
  32903. * Gaussian blur coefficient
  32904. * @type {number}
  32905. */
  32906. this.gaussCoeff = 0.3;
  32907. /**
  32908. * Gaussian blur mean
  32909. * @type {number}
  32910. */
  32911. this.gaussMean = 1.0;
  32912. /**
  32913. * Gaussian blur standard deviation
  32914. * @type {number}
  32915. */
  32916. this.gaussStandDev = 0.8;
  32917. // HDR
  32918. /**
  32919. * Exposure, controls the overall intensity of the pipeline
  32920. * @type {number}
  32921. */
  32922. this.exposure = 1.0;
  32923. /**
  32924. * Minimum luminance that the post-process can output. Luminance is >= 0
  32925. * @type {number}
  32926. */
  32927. this.minimumLuminance = 1.0;
  32928. /**
  32929. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  32930. * @type {number}
  32931. */
  32932. this.maximumLuminance = 1e20;
  32933. /**
  32934. * Increase rate for luminance: eye adaptation speed to dark
  32935. * @type {number}
  32936. */
  32937. this.luminanceIncreaserate = 0.5;
  32938. /**
  32939. * Decrease rate for luminance: eye adaptation speed to bright
  32940. * @type {number}
  32941. */
  32942. this.luminanceDecreaseRate = 0.5;
  32943. // Bright pass
  32944. /**
  32945. * Minimum luminance needed to compute HDR
  32946. * @type {number}
  32947. */
  32948. this.brightThreshold = 0.8;
  32949. this._needUpdate = true;
  32950. this._scene = scene;
  32951. // Bright pass
  32952. this._createBrightPassPostProcess(scene, ratio);
  32953. // Down sample X4
  32954. this._createDownSampleX4PostProcess(scene, ratio);
  32955. // Create gaussian blur post-processes
  32956. this._createGaussianBlurPostProcess(scene, ratio);
  32957. // Texture adder
  32958. this._createTextureAdderPostProcess(scene, ratio);
  32959. // Luminance generator
  32960. this._createLuminanceGeneratorPostProcess(scene);
  32961. // HDR
  32962. this._createHDRPostProcess(scene, ratio);
  32963. // Pass postprocess
  32964. if (originalPostProcess === null) {
  32965. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  32966. }
  32967. else {
  32968. this._originalPostProcess = originalPostProcess;
  32969. }
  32970. // Configure pipeline
  32971. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  32972. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  32973. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  32974. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  32975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  32976. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  32977. var addDownSamplerPostProcess = function (id) {
  32978. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  32979. };
  32980. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  32981. addDownSamplerPostProcess(i);
  32982. }
  32983. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  32984. // Finish
  32985. scene.postProcessRenderPipelineManager.addPipeline(this);
  32986. if (cameras !== null) {
  32987. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  32988. }
  32989. this.update();
  32990. }
  32991. /**
  32992. * Tells the pipeline to update its post-processes
  32993. */
  32994. HDRRenderingPipeline.prototype.update = function () {
  32995. this._needUpdate = true;
  32996. };
  32997. /**
  32998. * Returns the current calculated luminance
  32999. */
  33000. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  33001. return this._hdrCurrentLuminance;
  33002. };
  33003. /**
  33004. * Returns the currently drawn luminance
  33005. */
  33006. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  33007. return this._hdrOutputLuminance;
  33008. };
  33009. /**
  33010. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  33011. */
  33012. HDRRenderingPipeline.prototype.dispose = function () {
  33013. this._originalPostProcess = undefined;
  33014. this._brightPassPostProcess = undefined;
  33015. this._downSampleX4PostProcess = undefined;
  33016. this._guassianBlurHPostProcess = undefined;
  33017. this._guassianBlurVPostProcess = undefined;
  33018. this._textureAdderPostProcess = undefined;
  33019. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  33020. this._downSamplePostProcesses[i] = undefined;
  33021. }
  33022. this._hdrPostProcess = undefined;
  33023. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  33024. };
  33025. /**
  33026. * Creates the HDR post-process and computes the luminance adaptation
  33027. */
  33028. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  33029. var _this = this;
  33030. var hdrLastLuminance = 0.0;
  33031. this._hdrOutputLuminance = -1.0;
  33032. this._hdrCurrentLuminance = 1.0;
  33033. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  33034. this._hdrPostProcess.onApply = function (effect) {
  33035. if (_this._hdrOutputLuminance < 0.0) {
  33036. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33037. }
  33038. else {
  33039. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  33040. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  33041. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  33042. }
  33043. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  33044. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  33045. }
  33046. else {
  33047. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  33048. }
  33049. }
  33050. _this._hdrOutputLuminance = BABYLON.Tools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  33051. hdrLastLuminance += scene.getEngine().getDeltaTime();
  33052. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33053. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33054. effect.setFloat("exposure", _this.exposure);
  33055. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  33056. _this._needUpdate = false;
  33057. };
  33058. };
  33059. /**
  33060. * Texture Adder post-process
  33061. */
  33062. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  33063. var _this = this;
  33064. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  33065. this._textureAdderPostProcess.onApply = function (effect) {
  33066. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  33067. };
  33068. };
  33069. /**
  33070. * Down sample X4 post-process
  33071. */
  33072. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  33073. var _this = this;
  33074. var downSampleX4Offsets = new Array(32);
  33075. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  33076. this._downSampleX4PostProcess.onApply = function (effect) {
  33077. if (_this._needUpdate) {
  33078. var id = 0;
  33079. for (var i = -2; i < 2; i++) {
  33080. for (var j = -2; j < 2; j++) {
  33081. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  33082. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  33083. id += 2;
  33084. }
  33085. }
  33086. }
  33087. effect.setArray2("dsOffsets", downSampleX4Offsets);
  33088. };
  33089. };
  33090. /**
  33091. * Bright pass post-process
  33092. */
  33093. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  33094. var _this = this;
  33095. var brightOffsets = new Array(8);
  33096. var brightPassCallback = function (effect) {
  33097. if (_this._needUpdate) {
  33098. var sU = (1.0 / _this._brightPassPostProcess.width);
  33099. var sV = (1.0 / _this._brightPassPostProcess.height);
  33100. brightOffsets[0] = -0.5 * sU;
  33101. brightOffsets[1] = 0.5 * sV;
  33102. brightOffsets[2] = 0.5 * sU;
  33103. brightOffsets[3] = 0.5 * sV;
  33104. brightOffsets[4] = -0.5 * sU;
  33105. brightOffsets[5] = -0.5 * sV;
  33106. brightOffsets[6] = 0.5 * sU;
  33107. brightOffsets[7] = -0.5 * sV;
  33108. }
  33109. effect.setArray2("dsOffsets", brightOffsets);
  33110. effect.setFloat("brightThreshold", _this.brightThreshold);
  33111. };
  33112. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  33113. this._brightPassPostProcess.onApply = brightPassCallback;
  33114. };
  33115. /**
  33116. * Luminance generator. Creates the luminance post-process and down sample post-processes
  33117. */
  33118. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  33119. var _this = this;
  33120. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  33121. var luminanceOffsets = new Array(8);
  33122. var downSampleOffsets = new Array(18);
  33123. var halfDestPixelSize;
  33124. this._downSamplePostProcesses = new Array(lumSteps);
  33125. // Utils for luminance
  33126. var luminanceUpdateSourceOffsets = function (width, height) {
  33127. var sU = (1.0 / width);
  33128. var sV = (1.0 / height);
  33129. luminanceOffsets[0] = -0.5 * sU;
  33130. luminanceOffsets[1] = 0.5 * sV;
  33131. luminanceOffsets[2] = 0.5 * sU;
  33132. luminanceOffsets[3] = 0.5 * sV;
  33133. luminanceOffsets[4] = -0.5 * sU;
  33134. luminanceOffsets[5] = -0.5 * sV;
  33135. luminanceOffsets[6] = 0.5 * sU;
  33136. luminanceOffsets[7] = -0.5 * sV;
  33137. };
  33138. var luminanceUpdateDestOffsets = function (width, height) {
  33139. var id = 0;
  33140. for (var x = -1; x < 2; x++) {
  33141. for (var y = -1; y < 2; y++) {
  33142. downSampleOffsets[id] = (x) / width;
  33143. downSampleOffsets[id + 1] = (y) / height;
  33144. id += 2;
  33145. }
  33146. }
  33147. };
  33148. // Luminance callback
  33149. var luminanceCallback = function (effect) {
  33150. if (_this._needUpdate) {
  33151. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  33152. }
  33153. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  33154. effect.setArray2("lumOffsets", luminanceOffsets);
  33155. };
  33156. // Down sample callbacks
  33157. var downSampleCallback = function (indice) {
  33158. var i = indice;
  33159. return function (effect) {
  33160. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33161. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  33162. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  33163. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  33164. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  33165. effect.setArray2("dsOffsets", downSampleOffsets);
  33166. };
  33167. };
  33168. var downSampleAfterRenderCallback = function (effect) {
  33169. // Unpack result
  33170. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  33171. 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);
  33172. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  33173. };
  33174. // Create luminance post-process
  33175. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  33176. 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);
  33177. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  33178. // Create down sample post-processes
  33179. for (var i = lumSteps - 2; i >= 0; i--) {
  33180. var length = Math.pow(3, i);
  33181. ratio = { width: length, height: length };
  33182. var defines = "#define DOWN_SAMPLE\n";
  33183. if (i === 0) {
  33184. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  33185. }
  33186. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  33187. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  33188. if (i === 0) {
  33189. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  33190. }
  33191. }
  33192. };
  33193. /**
  33194. * Gaussian blur post-processes. Horizontal and Vertical
  33195. */
  33196. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  33197. var _this = this;
  33198. var blurOffsetsW = new Array(9);
  33199. var blurOffsetsH = new Array(9);
  33200. var blurWeights = new Array(9);
  33201. var uniforms = ["blurOffsets", "blurWeights"];
  33202. // Utils for gaussian blur
  33203. var calculateBlurOffsets = function (height) {
  33204. var lastOutputDimensions = {
  33205. width: scene.getEngine().getRenderWidth() * (ratio / 4),
  33206. height: scene.getEngine().getRenderHeight() * (ratio / 4)
  33207. };
  33208. for (var i = 0; i < 9; i++) {
  33209. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  33210. if (height) {
  33211. blurOffsetsH[i] = value;
  33212. }
  33213. else {
  33214. blurOffsetsW[i] = value;
  33215. }
  33216. }
  33217. };
  33218. var calculateWeights = function () {
  33219. var x = 0.0;
  33220. for (var i = 0; i < 9; i++) {
  33221. x = (i - 4.0) / 4.0;
  33222. 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));
  33223. }
  33224. };
  33225. // Callback
  33226. var gaussianBlurCallback = function (height) {
  33227. return function (effect) {
  33228. if (_this._needUpdate) {
  33229. calculateWeights();
  33230. calculateBlurOffsets(height);
  33231. }
  33232. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  33233. effect.setArray("blurWeights", blurWeights);
  33234. };
  33235. };
  33236. // Create horizontal gaussian blur post-processes
  33237. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  33238. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  33239. // Create vertical gaussian blur post-process
  33240. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  33241. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  33242. };
  33243. // Luminance generator
  33244. HDRRenderingPipeline.LUM_STEPS = 6;
  33245. return HDRRenderingPipeline;
  33246. })(BABYLON.PostProcessRenderPipeline);
  33247. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  33248. })(BABYLON || (BABYLON = {}));
  33249. var BABYLON;
  33250. (function (BABYLON) {
  33251. var FaceAdjacencies = (function () {
  33252. function FaceAdjacencies() {
  33253. this.edges = new Array();
  33254. this.edgesConnectedCount = 0;
  33255. }
  33256. return FaceAdjacencies;
  33257. })();
  33258. var EdgesRenderer = (function () {
  33259. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  33260. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  33261. if (epsilon === void 0) { epsilon = 0.95; }
  33262. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  33263. this._linesPositions = new Array();
  33264. this._linesNormals = new Array();
  33265. this._linesIndices = new Array();
  33266. this._buffers = new Array();
  33267. this._checkVerticesInsteadOfIndices = false;
  33268. this._source = source;
  33269. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  33270. this._epsilon = epsilon;
  33271. this._prepareRessources();
  33272. this._generateEdgesLines();
  33273. }
  33274. EdgesRenderer.prototype._prepareRessources = function () {
  33275. if (this._lineShader) {
  33276. return;
  33277. }
  33278. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  33279. attributes: ["position", "normal"],
  33280. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  33281. });
  33282. this._lineShader.disableDepthWrite = true;
  33283. this._lineShader.backFaceCulling = false;
  33284. };
  33285. EdgesRenderer.prototype.dispose = function () {
  33286. this._vb0.dispose();
  33287. this._vb1.dispose();
  33288. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  33289. this._lineShader.dispose();
  33290. };
  33291. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  33292. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  33293. return 0;
  33294. }
  33295. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  33296. return 1;
  33297. }
  33298. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  33299. return 2;
  33300. }
  33301. return -1;
  33302. };
  33303. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  33304. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  33305. return 0;
  33306. }
  33307. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  33308. return 1;
  33309. }
  33310. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  33311. return 2;
  33312. }
  33313. return -1;
  33314. };
  33315. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  33316. var needToCreateLine;
  33317. if (edge === undefined) {
  33318. needToCreateLine = true;
  33319. }
  33320. else {
  33321. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  33322. needToCreateLine = dotProduct < this._epsilon;
  33323. }
  33324. if (needToCreateLine) {
  33325. var offset = this._linesPositions.length / 3;
  33326. var normal = p0.subtract(p1);
  33327. normal.normalize();
  33328. // Positions
  33329. this._linesPositions.push(p0.x);
  33330. this._linesPositions.push(p0.y);
  33331. this._linesPositions.push(p0.z);
  33332. this._linesPositions.push(p0.x);
  33333. this._linesPositions.push(p0.y);
  33334. this._linesPositions.push(p0.z);
  33335. this._linesPositions.push(p1.x);
  33336. this._linesPositions.push(p1.y);
  33337. this._linesPositions.push(p1.z);
  33338. this._linesPositions.push(p1.x);
  33339. this._linesPositions.push(p1.y);
  33340. this._linesPositions.push(p1.z);
  33341. // Normals
  33342. this._linesNormals.push(p1.x);
  33343. this._linesNormals.push(p1.y);
  33344. this._linesNormals.push(p1.z);
  33345. this._linesNormals.push(-1);
  33346. this._linesNormals.push(p1.x);
  33347. this._linesNormals.push(p1.y);
  33348. this._linesNormals.push(p1.z);
  33349. this._linesNormals.push(1);
  33350. this._linesNormals.push(p0.x);
  33351. this._linesNormals.push(p0.y);
  33352. this._linesNormals.push(p0.z);
  33353. this._linesNormals.push(-1);
  33354. this._linesNormals.push(p0.x);
  33355. this._linesNormals.push(p0.y);
  33356. this._linesNormals.push(p0.z);
  33357. this._linesNormals.push(1);
  33358. // Indices
  33359. this._linesIndices.push(offset);
  33360. this._linesIndices.push(offset + 1);
  33361. this._linesIndices.push(offset + 2);
  33362. this._linesIndices.push(offset);
  33363. this._linesIndices.push(offset + 2);
  33364. this._linesIndices.push(offset + 3);
  33365. }
  33366. };
  33367. EdgesRenderer.prototype._generateEdgesLines = function () {
  33368. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33369. var indices = this._source.getIndices();
  33370. // First let's find adjacencies
  33371. var adjacencies = new Array();
  33372. var faceNormals = new Array();
  33373. var index;
  33374. var faceAdjacencies;
  33375. // Prepare faces
  33376. for (index = 0; index < indices.length; index += 3) {
  33377. faceAdjacencies = new FaceAdjacencies();
  33378. var p0Index = indices[index];
  33379. var p1Index = indices[index + 1];
  33380. var p2Index = indices[index + 2];
  33381. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  33382. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  33383. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  33384. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  33385. faceNormal.normalize();
  33386. faceNormals.push(faceNormal);
  33387. adjacencies.push(faceAdjacencies);
  33388. }
  33389. // Scan
  33390. for (index = 0; index < adjacencies.length; index++) {
  33391. faceAdjacencies = adjacencies[index];
  33392. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  33393. var otherFaceAdjacencies = adjacencies[otherIndex];
  33394. if (faceAdjacencies.edgesConnectedCount === 3) {
  33395. break;
  33396. }
  33397. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  33398. continue;
  33399. }
  33400. var otherP0 = indices[otherIndex * 3];
  33401. var otherP1 = indices[otherIndex * 3 + 1];
  33402. var otherP2 = indices[otherIndex * 3 + 2];
  33403. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  33404. var otherEdgeIndex;
  33405. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  33406. continue;
  33407. }
  33408. switch (edgeIndex) {
  33409. case 0:
  33410. if (this._checkVerticesInsteadOfIndices) {
  33411. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33412. }
  33413. else {
  33414. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  33415. }
  33416. break;
  33417. case 1:
  33418. if (this._checkVerticesInsteadOfIndices) {
  33419. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33420. }
  33421. else {
  33422. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  33423. }
  33424. break;
  33425. case 2:
  33426. if (this._checkVerticesInsteadOfIndices) {
  33427. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  33428. }
  33429. else {
  33430. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  33431. }
  33432. break;
  33433. }
  33434. if (otherEdgeIndex === -1) {
  33435. continue;
  33436. }
  33437. faceAdjacencies.edges[edgeIndex] = otherIndex;
  33438. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  33439. faceAdjacencies.edgesConnectedCount++;
  33440. otherFaceAdjacencies.edgesConnectedCount++;
  33441. if (faceAdjacencies.edgesConnectedCount === 3) {
  33442. break;
  33443. }
  33444. }
  33445. }
  33446. }
  33447. // Create lines
  33448. for (index = 0; index < adjacencies.length; index++) {
  33449. // We need a line when a face has no adjacency on a specific edge or if all the adjacencies has an angle greater than epsilon
  33450. var current = adjacencies[index];
  33451. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  33452. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  33453. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  33454. }
  33455. // Merge into a single mesh
  33456. var engine = this._source.getScene().getEngine();
  33457. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  33458. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  33459. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  33460. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  33461. this._ib = engine.createIndexBuffer(this._linesIndices);
  33462. this._indicesCount = this._linesIndices.length;
  33463. };
  33464. EdgesRenderer.prototype.render = function () {
  33465. if (!this._lineShader.isReady()) {
  33466. return;
  33467. }
  33468. var scene = this._source.getScene();
  33469. var engine = scene.getEngine();
  33470. this._lineShader._preBind();
  33471. // VBOs
  33472. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  33473. scene.resetCachedMaterial();
  33474. this._lineShader.setColor4("color", this._source.edgesColor);
  33475. this._lineShader.setFloat("width", this._source.edgesWidth / 50.0);
  33476. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  33477. this._lineShader.bind(this._source.getWorldMatrix());
  33478. // Draw order
  33479. engine.draw(true, 0, this._indicesCount);
  33480. this._lineShader.unbind();
  33481. engine.setDepthWrite(true);
  33482. };
  33483. return EdgesRenderer;
  33484. })();
  33485. BABYLON.EdgesRenderer = EdgesRenderer;
  33486. })(BABYLON || (BABYLON = {}));
  33487. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec4 skyColor;\r\nuniform vec4 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec4 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = c;\r\n\r\n}\r\n\r\n","colorPixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn min(1.0, visibility + darkness);\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias, float darkness)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn min(1.0, 1.0 - ChebychevInequality(moments, depth.z, bias) + darkness);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n#ifdef SPECULARTERM\r\n\tvec3 specular;\r\n#endif\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., glossiness));\r\n\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n#endif\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, glossiness);\r\n\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n#endif\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n#ifdef SPECULARTERM\r\n\tresult.specular = vec3(0.);\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor, float glossiness) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, glossiness);\r\n\r\n\tresult.specular = specComp * specularColor;\r\n#endif\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tfloat glossiness = vSpecularColor.a;\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n\r\n\t#ifdef SPECULAR\r\n\t\tvec4 specularMapColor = texture2D(specularSampler, vSpecularUV);\r\n\t\tspecularColor = specularMapColor.rgb;\r\n\t\t#ifdef GLOSSINESS\r\n\t\t\tglossiness = specularMapColor.a;\r\n\t\t#endif\r\n\t#endif\r\n#else\r\n\tfloat glossiness = 0.;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a, glossiness);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z, shadowsInfo0.x);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z, shadowsInfo0.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a, glossiness);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z, shadowsInfo1.x);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z, shadowsInfo1.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a, glossiness);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z, shadowsInfo2.x);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z, shadowsInfo2.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3, glossiness);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a, glossiness);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z, shadowsInfo3.x);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z, shadowsInfo3.x);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = getBlurLevel(size);\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, coc);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.30 * grain_amount;\r\n\t}\r\n\r\n}\r\n","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","hdrPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nvarying vec2 vUV;\r\n\r\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\r\nuniform float blurOffsets[9];\r\nuniform float blurWeights[9];\r\n\r\nvoid main(void) {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\t#ifdef GAUSSIAN_BLUR_H\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(blurOffsets[i], 0.0)) * blurWeights[i]);\r\n\t\t#else\r\n\t\tcolor += (texture2D(textureSampler, vUV + vec2(0.0, blurOffsets[i])) * blurWeights[i]);\r\n\t\t#endif\r\n\t}\r\n\r\n\tcolor.a = 1.0;\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n\r\n#if defined(TEXTURE_ADDER)\r\nuniform sampler2D otherSampler;\r\n\r\nvoid main() {\r\n\tvec4 sum = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tsum.a = clamp(sum.a, 0.0, 1.0);\r\n\r\n\tgl_FragColor = sum;\r\n}\r\n#endif\r\n\r\n#if defined(LUMINANCE_GENERATOR)\r\nuniform vec2 lumOffsets[4];\r\n\r\nvoid main() {\r\n\tfloat average = 0.0;\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat maximum = -1e20;\r\n\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + lumOffsets[i]);\r\n\r\n\t\tfloat GreyValue = length(color.rgb);\r\n\r\n\t\tmaximum = max(maximum, GreyValue);\r\n\t\taverage += (0.25 * log(1e-5 + GreyValue));\r\n\t}\r\n\r\n\taverage = exp(average);\r\n\r\n\tgl_FragColor = vec4(average, maximum, 0.0, 1.0);\r\n\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE)\r\nuniform vec2 dsOffsets[9];\r\nuniform float halfDestPixelSize;\r\n\r\n#ifdef FINAL_DOWN_SAMPLE\r\nvec4 pack(float value) {\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(value * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 color = vec4(0.0, 0.0, 0.0, 0.0);\r\n\tfloat average = 0.0;\r\n\r\n\tfor (int i = 0; i < 9; i++) {\r\n\t\tcolor = texture2D(textureSampler, vUV + vec2(halfDestPixelSize, halfDestPixelSize) + dsOffsets[i]);\r\n\t\taverage += color.r;\r\n\t}\r\n\r\n\taverage /= 9.0;\r\n\r\n\t#ifndef FINAL_DOWN_SAMPLE\r\n\tgl_FragColor = vec4(average, average, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = pack(average);\r\n\t#endif\r\n}\r\n#endif\r\n\r\n#if defined(BRIGHT_PASS)\r\nuniform vec2 dsOffsets[4];\r\nuniform float brightThreshold;\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + vec2(dsOffsets[0].x, dsOffsets[0].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[1].x, dsOffsets[1].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[2].x, dsOffsets[2].y));\r\n\taverage += texture2D(textureSampler, vUV + vec2(dsOffsets[3].x, dsOffsets[3].y));\r\n\r\n\taverage *= 0.25;\r\n\r\n\tfloat luminance = length(average.rgb);\r\n\r\n\tif (luminance < brightThreshold) {\r\n\t\taverage = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t}\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(DOWN_SAMPLE_X4)\r\nuniform vec2 dsOffsets[16];\r\n\r\nvoid main() {\r\n\tvec4 average = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\taverage = texture2D(textureSampler, vUV + dsOffsets[0]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[1]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[2]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[3]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[4]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[5]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[6]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[7]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[8]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[9]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[10]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[11]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[12]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[13]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[14]);\r\n\taverage += texture2D(textureSampler, vUV + dsOffsets[15]);\r\n\r\n\taverage /= 16.0;\r\n\r\n\tgl_FragColor = average;\r\n}\r\n#endif\r\n\r\n#if defined(HDR)\r\nuniform sampler2D otherSampler;\r\n\r\nuniform float exposure;\r\nuniform float avgLuminance;\r\n\r\nvoid main() {\r\n\tvec4 color = texture2D(textureSampler, vUV) + texture2D(otherSampler, vUV);\r\n\tvec4 adjustedColor = color / avgLuminance * exposure;\r\n\r\n\tcolor = adjustedColor;\r\n\tcolor.a = 1.0;\r\n\r\n\tgl_FragColor = color;\r\n}\r\n#endif\r\n","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\n#ifdef SPECULARTERM\r\nuniform vec4 vSpecularColor;\r\n#endif\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular0;\r\n#endif\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular1;\r\n#endif\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular2;\r\n#endif\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\n#ifdef SPECULARTERM\r\nuniform vec3 vLightSpecular3;\r\n#endif\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\r\n#ifdef SPECULARTERM\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n#else\r\n\t\tresult[1] = vec3(0.);\r\n#endif\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\r\n#ifdef SPECULARTERM\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\tresult[1] = specComp * specularColor;\r\n#else\r\n\tresult[1] = vec3(0.);\r\n#endif\r\n\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n#ifdef SPECULARTERM\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n#endif\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular0 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular1 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular2 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifndef SPECULARTERM\r\n\tvec3 vLightSpecular3 = vec3(0.0);\r\n#endif\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n#ifdef SPECULARTERM\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n#ifdef SPECULARTERM\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n#ifdef SPECULARTERM\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n#else\r\n\tvec3 finalSpecular = vec3(0.0);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#if defined(SPECULAR) && defined(SPECULARTERM)\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","linePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","lineVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 normal;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nuniform float width;\r\nuniform float aspectRatio;\r\n\r\nvoid main(void) {\r\n\tvec4 viewPosition = worldViewProjection * vec4(position, 1.0);\r\n\tvec4 viewPositionNext = worldViewProjection * vec4(normal.xyz, 1.0);\r\n\r\n\tvec2 currentScreen = viewPosition.xy / viewPosition.w;\r\n\tvec2 nextScreen = viewPositionNext.xy / viewPositionNext.w;\r\n\r\n\tcurrentScreen.x *= aspectRatio;\r\n\tnextScreen.x *= aspectRatio;\r\n\r\n\tvec2 dir = normalize(nextScreen - currentScreen);\r\n\tvec2 normalDir = vec2(-dir.y, dir.x);\r\n\r\n\tnormalDir *= width / 2.0;\r\n\tnormalDir.x /= aspectRatio;\r\n\r\n\tvec4 offset = vec4(normalDir * normal.w, 0.0, 0.0);\r\n\tgl_Position = viewPosition + offset;\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  33488. 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={}));";
  33489. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  33490. module.exports = BABYLON;
  33491. };