babylon.engine.ts 321 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480
  1. module BABYLON {
  2. var compileShader = (gl: WebGLRenderingContext, source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader => {
  3. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  4. };
  5. var compileRawShader = (gl: WebGLRenderingContext, source: string, type: string): WebGLShader => {
  6. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7. gl.shaderSource(shader, source);
  8. gl.compileShader(shader);
  9. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10. let log = gl.getShaderInfoLog(shader);
  11. if (log) {
  12. throw new Error(log);
  13. }
  14. }
  15. if (!shader) {
  16. throw new Error("Something went wrong while compile the shader.");
  17. }
  18. return shader;
  19. };
  20. var getSamplingParameters = (samplingMode: number, generateMipMaps: boolean, gl: WebGLRenderingContext): { min: number; mag: number } => {
  21. var magFilter = gl.NEAREST;
  22. var minFilter = gl.NEAREST;
  23. switch (samplingMode) {
  24. case Texture.BILINEAR_SAMPLINGMODE:
  25. magFilter = gl.LINEAR;
  26. if (generateMipMaps) {
  27. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  28. } else {
  29. minFilter = gl.LINEAR;
  30. }
  31. break;
  32. case Texture.TRILINEAR_SAMPLINGMODE:
  33. magFilter = gl.LINEAR;
  34. if (generateMipMaps) {
  35. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  36. } else {
  37. minFilter = gl.LINEAR;
  38. }
  39. break;
  40. case Texture.NEAREST_SAMPLINGMODE:
  41. magFilter = gl.NEAREST;
  42. if (generateMipMaps) {
  43. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  44. } else {
  45. minFilter = gl.NEAREST;
  46. }
  47. break;
  48. case Texture.NEAREST_NEAREST_MIPNEAREST:
  49. magFilter = gl.NEAREST;
  50. if (generateMipMaps) {
  51. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  52. } else {
  53. minFilter = gl.NEAREST;
  54. }
  55. break;
  56. case Texture.NEAREST_LINEAR_MIPNEAREST:
  57. magFilter = gl.NEAREST;
  58. if (generateMipMaps) {
  59. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  60. } else {
  61. minFilter = gl.LINEAR;
  62. }
  63. break;
  64. case Texture.NEAREST_LINEAR_MIPLINEAR:
  65. magFilter = gl.NEAREST;
  66. if (generateMipMaps) {
  67. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  68. } else {
  69. minFilter = gl.LINEAR;
  70. }
  71. break;
  72. case Texture.NEAREST_LINEAR:
  73. magFilter = gl.NEAREST;
  74. minFilter = gl.LINEAR;
  75. break;
  76. case Texture.NEAREST_NEAREST:
  77. magFilter = gl.NEAREST;
  78. minFilter = gl.NEAREST;
  79. break;
  80. case Texture.LINEAR_NEAREST_MIPNEAREST:
  81. magFilter = gl.LINEAR;
  82. if (generateMipMaps) {
  83. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  84. } else {
  85. minFilter = gl.NEAREST;
  86. }
  87. break;
  88. case Texture.LINEAR_NEAREST_MIPLINEAR:
  89. magFilter = gl.LINEAR;
  90. if (generateMipMaps) {
  91. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  92. } else {
  93. minFilter = gl.NEAREST;
  94. }
  95. break;
  96. case Texture.LINEAR_LINEAR:
  97. magFilter = gl.LINEAR;
  98. minFilter = gl.LINEAR;
  99. break;
  100. case Texture.LINEAR_NEAREST:
  101. magFilter = gl.LINEAR;
  102. minFilter = gl.NEAREST;
  103. break;
  104. }
  105. return {
  106. min: minFilter,
  107. mag: magFilter
  108. }
  109. }
  110. var partialLoadImg = (url: string, index: number, loadedImages: HTMLImageElement[], scene: Nullable<Scene>,
  111. onfinish: (images: HTMLImageElement[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null) => {
  112. var img: HTMLImageElement;
  113. var onload = () => {
  114. loadedImages[index] = img;
  115. (<any>loadedImages)._internalCount++;
  116. if (scene) {
  117. scene._removePendingData(img);
  118. }
  119. if ((<any>loadedImages)._internalCount === 6) {
  120. onfinish(loadedImages);
  121. }
  122. };
  123. var onerror = (message?: string, exception?: any) => {
  124. if (scene) {
  125. scene._removePendingData(img);
  126. }
  127. if (onErrorCallBack) {
  128. onErrorCallBack(message, exception);
  129. }
  130. };
  131. img = Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  132. if (scene) {
  133. scene._addPendingData(img);
  134. }
  135. }
  136. var cascadeLoadImgs = (rootUrl: string, scene: Nullable<Scene>,
  137. onfinish: (images: HTMLImageElement[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null) => {
  138. var loadedImages: HTMLImageElement[] = [];
  139. (<any>loadedImages)._internalCount = 0;
  140. for (let index = 0; index < 6; index++) {
  141. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  142. }
  143. };
  144. class BufferPointer {
  145. public active: boolean;
  146. public index: number;
  147. public size: number;
  148. public type: number;
  149. public normalized: boolean;
  150. public stride: number;
  151. public offset: number;
  152. public buffer: WebGLBuffer;
  153. }
  154. /**
  155. * Interface for attribute information associated with buffer instanciation
  156. */
  157. export class InstancingAttributeInfo {
  158. /**
  159. * Index/offset of the attribute in the vertex shader
  160. */
  161. index: number;
  162. /**
  163. * size of the attribute, 1, 2, 3 or 4
  164. */
  165. attributeSize: number;
  166. /**
  167. * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED, gl.FLOAT.
  168. * default is FLOAT
  169. */
  170. attribyteType: number;
  171. /**
  172. * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
  173. */
  174. normalized: boolean;
  175. /**
  176. * Offset of the data in the Vertex Buffer acting as the instancing buffer
  177. */
  178. offset: number;
  179. /**
  180. * Name of the GLSL attribute, for debugging purpose only
  181. */
  182. attributeName: string;
  183. }
  184. /**
  185. * Define options used to create a render target texture
  186. */
  187. export class RenderTargetCreationOptions {
  188. /**
  189. * Specifies is mipmaps must be generated
  190. */
  191. generateMipMaps?: boolean;
  192. /** Specifies whether or not a depth should be allocated in the texture (true by default) */
  193. generateDepthBuffer?: boolean;
  194. /** Specifies whether or not a stencil should be allocated in the texture (false by default)*/
  195. generateStencilBuffer?: boolean;
  196. /** Defines texture type (int by default) */
  197. type?: number;
  198. /** Defines sampling mode (trilinear by default) */
  199. samplingMode?: number;
  200. /** Defines format (RGBA by default) */
  201. format?: number;
  202. }
  203. /**
  204. * Define options used to create a depth texture
  205. */
  206. export class DepthTextureCreationOptions {
  207. /** Specifies whether or not a stencil should be allocated in the texture */
  208. generateStencil?: boolean;
  209. /** Specifies whether or not bilinear filtering is enable on the texture */
  210. bilinearFiltering?: boolean;
  211. /** Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode */
  212. comparisonFunction?: number;
  213. /** Specifies if the created texture is a cube texture */
  214. isCube?: boolean;
  215. }
  216. /**
  217. * Class used to describe the capabilities of the engine relatively to the current browser
  218. */
  219. export class EngineCapabilities {
  220. /** Maximum textures units per fragment shader */
  221. public maxTexturesImageUnits: number;
  222. /** Maximum texture units per vertex shader */
  223. public maxVertexTextureImageUnits: number;
  224. /** Maximum textures units in the entire pipeline */
  225. public maxCombinedTexturesImageUnits: number;
  226. /** Maximum texture size */
  227. public maxTextureSize: number;
  228. /** Maximum cube texture size */
  229. public maxCubemapTextureSize: number;
  230. /** Maximum render texture size */
  231. public maxRenderTextureSize: number;
  232. /** Maximum number of vertex attributes */
  233. public maxVertexAttribs: number;
  234. /** Maximum number of varyings */
  235. public maxVaryingVectors: number;
  236. /** Maximum number of uniforms per vertex shader */
  237. public maxVertexUniformVectors: number;
  238. /** Maximum number of uniforms per fragment shader */
  239. public maxFragmentUniformVectors: number;
  240. /** Defines if standard derivates (dx/dy) are supported */
  241. public standardDerivatives: boolean;
  242. /** Defines if s3tc texture compression is supported */
  243. public s3tc: Nullable<WEBGL_compressed_texture_s3tc>;
  244. /** Defines if pvrtc texture compression is supported */
  245. public pvrtc: any; //WEBGL_compressed_texture_pvrtc;
  246. /** Defines if etc1 texture compression is supported */
  247. public etc1: any; //WEBGL_compressed_texture_etc1;
  248. /** Defines if etc2 texture compression is supported */
  249. public etc2: any; //WEBGL_compressed_texture_etc;
  250. /** Defines if astc texture compression is supported */
  251. public astc: any; //WEBGL_compressed_texture_astc;
  252. /** Defines if float textures are supported */
  253. public textureFloat: boolean;
  254. /** Defines if vertex array objects are supported */
  255. public vertexArrayObject: boolean;
  256. /** Gets the webgl extension for anisotropic filtering (null if not supported) */
  257. public textureAnisotropicFilterExtension: Nullable<EXT_texture_filter_anisotropic>;
  258. /** Gets the maximum level of anisotropy supported */
  259. public maxAnisotropy: number;
  260. /** Defines if instancing is supported */
  261. public instancedArrays: boolean;
  262. /** Defines if 32 bits indices are supported */
  263. public uintIndices: boolean;
  264. /** Defines if high precision shaders are supported */
  265. public highPrecisionShaderSupported: boolean;
  266. /** Defines if depth reading in the fragment shader is supported */
  267. public fragmentDepthSupported: boolean;
  268. /** Defines if float texture linear filtering is supported*/
  269. public textureFloatLinearFiltering: boolean;
  270. /** Defines if rendering to float textures is supported */
  271. public textureFloatRender: boolean;
  272. /** Defines if half float textures are supported*/
  273. public textureHalfFloat: boolean;
  274. /** Defines if half float texture linear filtering is supported*/
  275. public textureHalfFloatLinearFiltering: boolean;
  276. /** Defines if rendering to half float textures is supported */
  277. public textureHalfFloatRender: boolean;
  278. /** Defines if textureLOD shader command is supported */
  279. public textureLOD: boolean;
  280. /** Defines if draw buffers extension is supported */
  281. public drawBuffersExtension: boolean;
  282. /** Defines if depth textures are supported */
  283. public depthTextureExtension: boolean;
  284. /** Defines if float color buffer are supported */
  285. public colorBufferFloat: boolean;
  286. /** Gets disjoint timer query extension (null if not supported) */
  287. public timerQuery: EXT_disjoint_timer_query;
  288. /** Defines if timestamp can be used with timer query */
  289. public canUseTimestampForTimerQuery: boolean;
  290. }
  291. /** Interface defining initialization parameters for Engine class */
  292. export interface EngineOptions extends WebGLContextAttributes {
  293. /**
  294. * Defines if the engine should no exceed a specified device ratio
  295. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  296. */
  297. limitDeviceRatio?: number;
  298. /**
  299. * Defines if webvr should be enabled automatically
  300. * @see http://doc.babylonjs.com/how_to/webvr_camera
  301. */
  302. autoEnableWebVR?: boolean;
  303. /**
  304. * Defines if webgl2 should be turned off even if supported
  305. * @see http://doc.babylonjs.com/features/webgl2
  306. */
  307. disableWebGL2Support?: boolean;
  308. /**
  309. * Defines if webaudio should be initialized as well
  310. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  311. */
  312. audioEngine?: boolean;
  313. /**
  314. * Defines if animations should run using a deterministic lock step
  315. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  316. */
  317. deterministicLockstep?: boolean;
  318. /** Defines the maximum steps to use with deterministic lock step mode */
  319. lockstepMaxSteps?: number;
  320. /**
  321. * Defines that engine should ignore context lost events
  322. * If this event happens when this parameter is true, you will have to reload the page to restore rendering
  323. */
  324. doNotHandleContextLost?: boolean;
  325. }
  326. /**
  327. * Defines the interface used by display changed events
  328. */
  329. export interface IDisplayChangedEventArgs {
  330. /** Gets the vrDisplay object (if any) */
  331. vrDisplay: Nullable<any>;
  332. /** Gets a boolean indicating if webVR is supported */
  333. vrSupported: boolean;
  334. }
  335. /**
  336. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  337. */
  338. export class Engine {
  339. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  340. public static ExceptionList = [
  341. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  342. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  343. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  344. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  345. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  346. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  347. ];
  348. /** Gets the list of created engines */
  349. public static Instances = new Array<Engine>();
  350. /**
  351. * Gets the latest created engine
  352. */
  353. public static get LastCreatedEngine(): Nullable<Engine> {
  354. if (Engine.Instances.length === 0) {
  355. return null;
  356. }
  357. return Engine.Instances[Engine.Instances.length - 1];
  358. }
  359. /**
  360. * Gets the latest created scene
  361. */
  362. public static get LastCreatedScene(): Nullable<Scene> {
  363. var lastCreatedEngine = Engine.LastCreatedEngine;
  364. if (!lastCreatedEngine) {
  365. return null;
  366. }
  367. if (lastCreatedEngine.scenes.length === 0) {
  368. return null;
  369. }
  370. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  371. }
  372. /**
  373. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  374. * @param flag defines which part of the materials must be marked as dirty
  375. * @param predicate defines a predicate used to filter which materials should be affected
  376. */
  377. public static MarkAllMaterialsAsDirty(flag: number, predicate?: (mat: Material) => boolean): void {
  378. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  379. var engine = Engine.Instances[engineIndex];
  380. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  381. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  382. }
  383. }
  384. }
  385. // Const statics
  386. private static _ALPHA_DISABLE = 0;
  387. private static _ALPHA_ADD = 1;
  388. private static _ALPHA_COMBINE = 2;
  389. private static _ALPHA_SUBTRACT = 3;
  390. private static _ALPHA_MULTIPLY = 4;
  391. private static _ALPHA_MAXIMIZED = 5;
  392. private static _ALPHA_ONEONE = 6;
  393. private static _ALPHA_PREMULTIPLIED = 7;
  394. private static _ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  395. private static _ALPHA_INTERPOLATE = 9;
  396. private static _ALPHA_SCREENMODE = 10;
  397. private static _DELAYLOADSTATE_NONE = 0;
  398. private static _DELAYLOADSTATE_LOADED = 1;
  399. private static _DELAYLOADSTATE_LOADING = 2;
  400. private static _DELAYLOADSTATE_NOTLOADED = 4;
  401. private static _TEXTUREFORMAT_ALPHA = 0;
  402. private static _TEXTUREFORMAT_LUMINANCE = 1;
  403. private static _TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  404. private static _TEXTUREFORMAT_RGB = 4;
  405. private static _TEXTUREFORMAT_RGBA = 5;
  406. private static _TEXTUREFORMAT_R32F = 6;
  407. private static _TEXTUREFORMAT_RG32F = 7;
  408. private static _TEXTUREFORMAT_RGB32F = 8;
  409. private static _TEXTUREFORMAT_RGBA32F = 9;
  410. private static _TEXTURETYPE_UNSIGNED_INT = 0;
  411. private static _TEXTURETYPE_FLOAT = 1;
  412. private static _TEXTURETYPE_HALF_FLOAT = 2;
  413. // Depht or Stencil test Constants.
  414. private static _NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  415. private static _ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  416. private static _LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  417. private static _EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  418. private static _LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  419. private static _GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  420. private static _GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  421. private static _NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  422. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  423. public static get NEVER(): number {
  424. return Engine._NEVER;
  425. }
  426. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
  427. public static get ALWAYS(): number {
  428. return Engine._ALWAYS;
  429. }
  430. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  431. public static get LESS(): number {
  432. return Engine._LESS;
  433. }
  434. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  435. public static get EQUAL(): number {
  436. return Engine._EQUAL;
  437. }
  438. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
  439. public static get LEQUAL(): number {
  440. return Engine._LEQUAL;
  441. }
  442. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  443. public static get GREATER(): number {
  444. return Engine._GREATER;
  445. }
  446. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
  447. public static get GEQUAL(): number {
  448. return Engine._GEQUAL;
  449. }
  450. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
  451. public static get NOTEQUAL(): number {
  452. return Engine._NOTEQUAL;
  453. }
  454. // Stencil Actions Constants.
  455. private static _KEEP = 0x1E00;
  456. private static _REPLACE = 0x1E01;
  457. private static _INCR = 0x1E02;
  458. private static _DECR = 0x1E03;
  459. private static _INVERT = 0x150A;
  460. private static _INCR_WRAP = 0x8507;
  461. private static _DECR_WRAP = 0x8508;
  462. /** Passed to stencilOperation to specify that stencil value must be kept */
  463. public static get KEEP(): number {
  464. return Engine._KEEP;
  465. }
  466. /** Passed to stencilOperation to specify that stencil value must be replaced */
  467. public static get REPLACE(): number {
  468. return Engine._REPLACE;
  469. }
  470. /** Passed to stencilOperation to specify that stencil value must be incremented */
  471. public static get INCR(): number {
  472. return Engine._INCR;
  473. }
  474. /** Passed to stencilOperation to specify that stencil value must be decremented */
  475. public static get DECR(): number {
  476. return Engine._DECR;
  477. }
  478. /** Passed to stencilOperation to specify that stencil value must be inverted */
  479. public static get INVERT(): number {
  480. return Engine._INVERT;
  481. }
  482. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  483. public static get INCR_WRAP(): number {
  484. return Engine._INCR_WRAP;
  485. }
  486. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  487. public static get DECR_WRAP(): number {
  488. return Engine._DECR_WRAP;
  489. }
  490. // Alpha
  491. /** Defines that alpha blending is disabled */
  492. public static get ALPHA_DISABLE(): number {
  493. return Engine._ALPHA_DISABLE;
  494. }
  495. /** Defines that alpha blending to SRC + DEST */
  496. public static get ALPHA_ONEONE(): number {
  497. return Engine._ALPHA_ONEONE;
  498. }
  499. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  500. public static get ALPHA_ADD(): number {
  501. return Engine._ALPHA_ADD;
  502. }
  503. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  504. public static get ALPHA_COMBINE(): number {
  505. return Engine._ALPHA_COMBINE;
  506. }
  507. /** Defines that alpha blending to DEST - SRC * DEST */
  508. public static get ALPHA_SUBTRACT(): number {
  509. return Engine._ALPHA_SUBTRACT;
  510. }
  511. /** Defines that alpha blending to SRC * DEST */
  512. public static get ALPHA_MULTIPLY(): number {
  513. return Engine._ALPHA_MULTIPLY;
  514. }
  515. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  516. public static get ALPHA_MAXIMIZED(): number {
  517. return Engine._ALPHA_MAXIMIZED;
  518. }
  519. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  520. public static get ALPHA_PREMULTIPLIED(): number {
  521. return Engine._ALPHA_PREMULTIPLIED;
  522. }
  523. /**
  524. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  525. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  526. */
  527. public static get ALPHA_PREMULTIPLIED_PORTERDUFF(): number {
  528. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  529. }
  530. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  531. public static get ALPHA_INTERPOLATE(): number {
  532. return Engine._ALPHA_INTERPOLATE;
  533. }
  534. /**
  535. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  536. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  537. */
  538. public static get ALPHA_SCREENMODE(): number {
  539. return Engine._ALPHA_SCREENMODE;
  540. }
  541. // Delays
  542. /** Defines that the ressource is not delayed*/
  543. public static get DELAYLOADSTATE_NONE(): number {
  544. return Engine._DELAYLOADSTATE_NONE;
  545. }
  546. /** Defines that the ressource was successfully delay loaded */
  547. public static get DELAYLOADSTATE_LOADED(): number {
  548. return Engine._DELAYLOADSTATE_LOADED;
  549. }
  550. /** Defines that the ressource is currently delay loading */
  551. public static get DELAYLOADSTATE_LOADING(): number {
  552. return Engine._DELAYLOADSTATE_LOADING;
  553. }
  554. /** Defines that the ressource is delayed and has not started loading */
  555. public static get DELAYLOADSTATE_NOTLOADED(): number {
  556. return Engine._DELAYLOADSTATE_NOTLOADED;
  557. }
  558. /** ALPHA */
  559. public static get TEXTUREFORMAT_ALPHA(): number {
  560. return Engine._TEXTUREFORMAT_ALPHA;
  561. }
  562. /** LUMINANCE */
  563. public static get TEXTUREFORMAT_LUMINANCE(): number {
  564. return Engine._TEXTUREFORMAT_LUMINANCE;
  565. }
  566. /**
  567. * R32F
  568. */
  569. public static get TEXTUREFORMAT_R32F(): number {
  570. return Engine._TEXTUREFORMAT_R32F;
  571. }
  572. /**
  573. * RG32F
  574. */
  575. public static get TEXTUREFORMAT_RG32F(): number {
  576. return Engine._TEXTUREFORMAT_RG32F;
  577. }
  578. /**
  579. * RGB32F
  580. */
  581. public static get TEXTUREFORMAT_RGB32F(): number {
  582. return Engine._TEXTUREFORMAT_RGB32F;
  583. }
  584. /**
  585. * RGBA32F
  586. */
  587. public static get TEXTUREFORMAT_RGBA32F(): number {
  588. return Engine._TEXTUREFORMAT_RGBA32F;
  589. }
  590. /** LUMINANCE_ALPHA */
  591. public static get TEXTUREFORMAT_LUMINANCE_ALPHA(): number {
  592. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  593. }
  594. /** RGB */
  595. public static get TEXTUREFORMAT_RGB(): number {
  596. return Engine._TEXTUREFORMAT_RGB;
  597. }
  598. /** RGBA */
  599. public static get TEXTUREFORMAT_RGBA(): number {
  600. return Engine._TEXTUREFORMAT_RGBA;
  601. }
  602. /** UNSIGNED_INT */
  603. public static get TEXTURETYPE_UNSIGNED_INT(): number {
  604. return Engine._TEXTURETYPE_UNSIGNED_INT;
  605. }
  606. /** FLOAT */
  607. public static get TEXTURETYPE_FLOAT(): number {
  608. return Engine._TEXTURETYPE_FLOAT;
  609. }
  610. /** HALF_FLOAT */
  611. public static get TEXTURETYPE_HALF_FLOAT(): number {
  612. return Engine._TEXTURETYPE_HALF_FLOAT;
  613. }
  614. // Texture rescaling mode
  615. private static _SCALEMODE_FLOOR = 1;
  616. private static _SCALEMODE_NEAREST = 2;
  617. private static _SCALEMODE_CEILING = 3;
  618. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  619. public static get SCALEMODE_FLOOR(): number {
  620. return Engine._SCALEMODE_FLOOR;
  621. }
  622. /** Defines that texture rescaling will look for the nearest power of 2 size */
  623. public static get SCALEMODE_NEAREST(): number {
  624. return Engine._SCALEMODE_NEAREST;
  625. }
  626. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  627. public static get SCALEMODE_CEILING(): number {
  628. return Engine._SCALEMODE_CEILING;
  629. }
  630. /**
  631. * Returns the current version of the framework
  632. */
  633. public static get Version(): string {
  634. return "3.3.0-alpha.1";
  635. }
  636. // Updatable statics so stick with vars here
  637. /**
  638. * Gets or sets the epsilon value used by collision engine
  639. */
  640. public static CollisionsEpsilon = 0.001;
  641. /**
  642. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  643. */
  644. public static CodeRepository = "src/";
  645. /**
  646. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  647. */
  648. public static ShadersRepository = "src/Shaders/";
  649. // Public members
  650. /**
  651. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  652. */
  653. public forcePOTTextures = false;
  654. /**
  655. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  656. */
  657. public isFullscreen = false;
  658. /**
  659. * Gets a boolean indicating if the pointer is currently locked
  660. */
  661. public isPointerLock = false;
  662. /**
  663. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  664. */
  665. public cullBackFaces = true;
  666. /**
  667. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  668. */
  669. public renderEvenInBackground = true;
  670. /**
  671. * Gets or sets a boolean indicating that cache can be kept between frames
  672. */
  673. public preventCacheWipeBetweenFrames = false;
  674. /**
  675. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  676. **/
  677. public enableOfflineSupport = false;
  678. /**
  679. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  680. **/
  681. public disableManifestCheck = false;
  682. /**
  683. * Gets the list of created scenes
  684. */
  685. public scenes = new Array<Scene>();
  686. /**
  687. * Gets the list of created postprocesses
  688. */
  689. public postProcesses = new Array<PostProcess>();
  690. // Observables
  691. /**
  692. * Observable event triggered each time the rendering canvas is resized
  693. */
  694. public onResizeObservable = new Observable<Engine>();
  695. /**
  696. * Observable event triggered each time the canvas loses focus
  697. */
  698. public onCanvasBlurObservable = new Observable<Engine>();
  699. /**
  700. * Observable event triggered each time the canvas gains focus
  701. */
  702. public onCanvasFocusObservable = new Observable<Engine>();
  703. /**
  704. * Observable event triggered each time the canvas receives pointerout event
  705. */
  706. public onCanvasPointerOutObservable = new Observable<PointerEvent>();
  707. /**
  708. * Observable event triggered before each texture is initialized
  709. */
  710. public onBeforeTextureInitObservable = new Observable<Texture>();
  711. //WebVR
  712. private _vrDisplay: any = undefined;
  713. private _vrSupported: boolean = false;
  714. private _oldSize: Size;
  715. private _oldHardwareScaleFactor: number;
  716. private _vrExclusivePointerMode = false;
  717. private _webVRInitPromise: Promise<IDisplayChangedEventArgs>;
  718. /**
  719. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  720. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  721. */
  722. public get isInVRExclusivePointerMode(): boolean {
  723. return this._vrExclusivePointerMode;
  724. }
  725. // Uniform buffers list
  726. /**
  727. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  728. */
  729. public disableUniformBuffers = false;
  730. /** @hidden */
  731. public _uniformBuffers = new Array<UniformBuffer>();
  732. /**
  733. * Gets a boolean indicating that the engine supports uniform buffers
  734. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  735. */
  736. public get supportsUniformBuffers(): boolean {
  737. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  738. }
  739. // Observables
  740. /**
  741. * Observable raised when the engine begins a new frame
  742. */
  743. public onBeginFrameObservable = new Observable<Engine>();
  744. /**
  745. * Observable raised when the engine ends the current frame
  746. */
  747. public onEndFrameObservable = new Observable<Engine>();
  748. /**
  749. * Observable raised when the engine is about to compile a shader
  750. */
  751. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  752. /**
  753. * Observable raised when the engine has jsut compiled a shader
  754. */
  755. public onAfterShaderCompilationObservable = new Observable<Engine>();
  756. // Private Members
  757. private _gl: WebGLRenderingContext;
  758. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  759. private _windowIsBackground = false;
  760. private _webGLVersion = 1.0;
  761. /**
  762. * Gets a boolean indicating that only power of 2 textures are supported
  763. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  764. */
  765. public get needPOTTextures(): boolean {
  766. return this._webGLVersion < 2 || this.forcePOTTextures;
  767. }
  768. /** @hidden */
  769. public _badOS = false;
  770. /** @hidden */
  771. public _badDesktopOS = false;
  772. /**
  773. * Gets or sets a value indicating if we want to disable texture binding optmization.
  774. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  775. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  776. */
  777. public disableTextureBindingOptimization = false;
  778. /**
  779. * Gets the audio engine
  780. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  781. * @ignorenaming
  782. */
  783. public static audioEngine: AudioEngine;
  784. // Focus
  785. private _onFocus: () => void;
  786. private _onBlur: () => void;
  787. private _onCanvasPointerOut: (event: PointerEvent) => void;
  788. private _onCanvasBlur: () => void;
  789. private _onCanvasFocus: () => void;
  790. private _onFullscreenChange: () => void;
  791. private _onPointerLockChange: () => void;
  792. private _onVRDisplayPointerRestricted: () => void;
  793. private _onVRDisplayPointerUnrestricted: () => void;
  794. // VRDisplay connection
  795. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  796. private _onVrDisplayDisconnect: Nullable<() => void>;
  797. private _onVrDisplayPresentChange: Nullable<() => void>;
  798. /**
  799. * Observable signaled when VR display mode changes
  800. */
  801. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  802. /**
  803. * Observable signaled when VR request present is complete
  804. */
  805. public onVRRequestPresentComplete = new Observable<boolean>();
  806. /**
  807. * Observable signaled when VR request present starts
  808. */
  809. public onVRRequestPresentStart = new Observable<Engine>();
  810. private _hardwareScalingLevel: number;
  811. /** @hidden */
  812. protected _caps: EngineCapabilities;
  813. private _pointerLockRequested: boolean;
  814. private _isStencilEnable: boolean;
  815. private _colorWrite = true;
  816. private _loadingScreen: ILoadingScreen;
  817. /** @hidden */
  818. public _drawCalls = new PerfCounter();
  819. /** @hidden */
  820. public _textureCollisions = new PerfCounter();
  821. private _glVersion: string;
  822. private _glRenderer: string;
  823. private _glVendor: string;
  824. private _videoTextureSupported: boolean;
  825. private _renderingQueueLaunched = false;
  826. private _activeRenderLoops = new Array<() => void>();
  827. // Deterministic lockstepMaxSteps
  828. private _deterministicLockstep: boolean = false;
  829. private _lockstepMaxSteps: number = 4;
  830. // Lost context
  831. /**
  832. * Observable signaled when a context lost event is raised
  833. */
  834. public onContextLostObservable = new Observable<Engine>();
  835. /**
  836. * Observable signaled when a context restored event is raised
  837. */
  838. public onContextRestoredObservable = new Observable<Engine>();
  839. private _onContextLost: (evt: Event) => void;
  840. private _onContextRestored: (evt: Event) => void;
  841. private _contextWasLost = false;
  842. private _doNotHandleContextLost = false;
  843. // FPS
  844. private _performanceMonitor = new PerformanceMonitor();
  845. private _fps = 60;
  846. private _deltaTime = 0;
  847. /**
  848. * Turn this value on if you want to pause FPS computation when in background
  849. */
  850. public disablePerformanceMonitorInBackground = false;
  851. /**
  852. * Gets the performance monitor attached to this engine
  853. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  854. */
  855. public get performanceMonitor(): PerformanceMonitor {
  856. return this._performanceMonitor;
  857. }
  858. // States
  859. /** @hidden */
  860. protected _depthCullingState = new _DepthCullingState();
  861. /** @hidden */
  862. protected _stencilState = new _StencilState();
  863. /** @hidden */
  864. protected _alphaState = new _AlphaState();
  865. /** @hidden */
  866. protected _alphaMode = Engine.ALPHA_DISABLE;
  867. // Cache
  868. protected _internalTexturesCache = new Array<InternalTexture>();
  869. /** @hidden */
  870. protected _activeChannel = 0;
  871. private _currentTextureChannel = -1;
  872. /** @hidden */
  873. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  874. /** @hidden */
  875. protected _currentEffect: Nullable<Effect>;
  876. /** @hidden */
  877. protected _currentProgram: Nullable<WebGLProgram>;
  878. private _compiledEffects: { [key: string]: Effect } = {}
  879. private _vertexAttribArraysEnabled: boolean[] = [];
  880. /** @hidden */
  881. protected _cachedViewport: Nullable<Viewport>;
  882. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  883. /** @hidden */
  884. protected _cachedVertexBuffers: any;
  885. /** @hidden */
  886. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  887. /** @hidden */
  888. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  889. /** @hidden */
  890. protected _currentRenderTarget: Nullable<InternalTexture>;
  891. private _uintIndicesCurrentlySet = false;
  892. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  893. /** @hidden */
  894. protected _currentFramebuffer: Nullable<WebGLFramebuffer>;
  895. private _currentBufferPointers = new Array<BufferPointer>();
  896. private _currentInstanceLocations = new Array<number>();
  897. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  898. private _textureUnits: Int32Array;
  899. private _firstBoundInternalTextureTracker = new DummyInternalTextureTracker();
  900. private _lastBoundInternalTextureTracker = new DummyInternalTextureTracker();
  901. private _workingCanvas: Nullable<HTMLCanvasElement>;
  902. private _workingContext: Nullable<CanvasRenderingContext2D>;
  903. private _rescalePostProcess: PassPostProcess;
  904. private _dummyFramebuffer: WebGLFramebuffer;
  905. private _externalData: StringDictionary<Object>;
  906. private _bindedRenderFunction: any;
  907. private _vaoRecordInProgress = false;
  908. private _mustWipeVertexAttributes = false;
  909. private _emptyTexture: Nullable<InternalTexture>;
  910. private _emptyCubeTexture: Nullable<InternalTexture>;
  911. private _emptyTexture3D: Nullable<InternalTexture>;
  912. private _frameHandler: number;
  913. private _nextFreeTextureSlots = new Array<number>();
  914. private _maxSimultaneousTextures = 0;
  915. private _activeRequests = new Array<IFileRequest>();
  916. // Hardware supported Compressed Textures
  917. private _texturesSupported = new Array<string>();
  918. private _textureFormatInUse: Nullable<string>;
  919. /**
  920. * Gets the list of texture formats supported
  921. */
  922. public get texturesSupported(): Array<string> {
  923. return this._texturesSupported;
  924. }
  925. /**
  926. * Gets the list of texture formats in use
  927. */
  928. public get textureFormatInUse(): Nullable<string> {
  929. return this._textureFormatInUse;
  930. }
  931. /**
  932. * Gets the current viewport
  933. */
  934. public get currentViewport(): Nullable<Viewport> {
  935. return this._cachedViewport;
  936. }
  937. /**
  938. * Gets the default empty texture
  939. */
  940. public get emptyTexture(): InternalTexture {
  941. if (!this._emptyTexture) {
  942. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  943. }
  944. return this._emptyTexture;
  945. }
  946. /**
  947. * Gets the default empty 3D texture
  948. */
  949. public get emptyTexture3D(): InternalTexture {
  950. if (!this._emptyTexture3D) {
  951. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Texture.NEAREST_SAMPLINGMODE);
  952. }
  953. return this._emptyTexture3D;
  954. }
  955. /**
  956. * Gets the default empty cube texture
  957. */
  958. public get emptyCubeTexture(): InternalTexture {
  959. if (!this._emptyCubeTexture) {
  960. var faceData = new Uint8Array(4);
  961. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  962. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Texture.NEAREST_SAMPLINGMODE);
  963. }
  964. return this._emptyCubeTexture;
  965. }
  966. /**
  967. * Creates a new engine
  968. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  969. * @param antialias defines enable antialiasing (default: false)
  970. * @param options defines further options to be sent to the getContext() function
  971. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  972. */
  973. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  974. // Register promises
  975. PromisePolyfill.Apply();
  976. let canvas: Nullable<HTMLCanvasElement> = null;
  977. Engine.Instances.push(this);
  978. if (!canvasOrContext) {
  979. return;
  980. }
  981. options = options || {};
  982. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  983. canvas = <HTMLCanvasElement>canvasOrContext;
  984. this._renderingCanvas = canvas;
  985. if (antialias != null) {
  986. options.antialias = antialias;
  987. }
  988. if (options.deterministicLockstep === undefined) {
  989. options.deterministicLockstep = false;
  990. }
  991. if (options.lockstepMaxSteps === undefined) {
  992. options.lockstepMaxSteps = 4;
  993. }
  994. if (options.preserveDrawingBuffer === undefined) {
  995. options.preserveDrawingBuffer = false;
  996. }
  997. if (options.audioEngine === undefined) {
  998. options.audioEngine = true;
  999. }
  1000. if (options.stencil === undefined) {
  1001. options.stencil = true;
  1002. }
  1003. this._deterministicLockstep = options.deterministicLockstep;
  1004. this._lockstepMaxSteps = options.lockstepMaxSteps;
  1005. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  1006. // Exceptions
  1007. if (navigator && navigator.userAgent) {
  1008. let ua = navigator.userAgent;
  1009. for (var exception of Engine.ExceptionList) {
  1010. let key = exception.key;
  1011. let targets = exception.targets;
  1012. if (ua.indexOf(key) > -1) {
  1013. if (exception.capture && exception.captureConstraint) {
  1014. let capture = exception.capture;
  1015. let constraint = exception.captureConstraint;
  1016. let regex = new RegExp(capture);
  1017. let matches = regex.exec(ua);
  1018. if (matches && matches.length > 0) {
  1019. let capturedValue = parseInt(matches[matches.length - 1]);
  1020. if (capturedValue >= constraint) {
  1021. continue;
  1022. }
  1023. }
  1024. }
  1025. for (var target of targets) {
  1026. switch (target) {
  1027. case "uniformBuffer":
  1028. this.disableUniformBuffers = true;
  1029. break;
  1030. case "textureBindingOptimization":
  1031. this.disableTextureBindingOptimization = true;
  1032. break;
  1033. }
  1034. }
  1035. }
  1036. }
  1037. }
  1038. // GL
  1039. if (!options.disableWebGL2Support) {
  1040. try {
  1041. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  1042. if (this._gl) {
  1043. this._webGLVersion = 2.0;
  1044. }
  1045. } catch (e) {
  1046. // Do nothing
  1047. }
  1048. }
  1049. if (!this._gl) {
  1050. if (!canvas) {
  1051. throw new Error("The provided canvas is null or undefined.");
  1052. }
  1053. try {
  1054. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  1055. } catch (e) {
  1056. throw new Error("WebGL not supported");
  1057. }
  1058. }
  1059. if (!this._gl) {
  1060. throw new Error("WebGL not supported");
  1061. }
  1062. this._onCanvasFocus = () => {
  1063. this.onCanvasFocusObservable.notifyObservers(this);
  1064. }
  1065. this._onCanvasBlur = () => {
  1066. this.onCanvasBlurObservable.notifyObservers(this);
  1067. }
  1068. canvas.addEventListener("focus", this._onCanvasFocus);
  1069. canvas.addEventListener("blur", this._onCanvasBlur);
  1070. this._onBlur = () => {
  1071. if (this.disablePerformanceMonitorInBackground) {
  1072. this._performanceMonitor.disable();
  1073. }
  1074. this._windowIsBackground = true;
  1075. };
  1076. this._onFocus = () => {
  1077. if (this.disablePerformanceMonitorInBackground) {
  1078. this._performanceMonitor.enable();
  1079. }
  1080. this._windowIsBackground = false;
  1081. };
  1082. this._onCanvasPointerOut = (ev) => {
  1083. this.onCanvasPointerOutObservable.notifyObservers(ev);
  1084. };
  1085. window.addEventListener("blur", this._onBlur);
  1086. window.addEventListener("focus", this._onFocus);
  1087. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  1088. // Context lost
  1089. if (!this._doNotHandleContextLost) {
  1090. this._onContextLost = (evt: Event) => {
  1091. evt.preventDefault();
  1092. this._contextWasLost = true;
  1093. Tools.Warn("WebGL context lost.");
  1094. this.onContextLostObservable.notifyObservers(this);
  1095. };
  1096. this._onContextRestored = (evt: Event) => {
  1097. // Adding a timeout to avoid race condition at browser level
  1098. setTimeout(() => {
  1099. // Rebuild gl context
  1100. this._initGLContext();
  1101. // Rebuild effects
  1102. this._rebuildEffects();
  1103. // Rebuild textures
  1104. this._rebuildInternalTextures();
  1105. // Rebuild buffers
  1106. this._rebuildBuffers();
  1107. // Cache
  1108. this.wipeCaches(true);
  1109. Tools.Warn("WebGL context successfully restored.");
  1110. this.onContextRestoredObservable.notifyObservers(this);
  1111. this._contextWasLost = false;
  1112. }, 0);
  1113. };
  1114. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  1115. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  1116. }
  1117. } else {
  1118. this._gl = <WebGLRenderingContext>canvasOrContext;
  1119. this._renderingCanvas = this._gl.canvas
  1120. if (this._gl.renderbufferStorageMultisample) {
  1121. this._webGLVersion = 2.0;
  1122. }
  1123. options.stencil = this._gl.getContextAttributes().stencil;
  1124. }
  1125. // Viewport
  1126. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  1127. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  1128. this.resize();
  1129. this._isStencilEnable = options.stencil ? true : false;
  1130. this._initGLContext();
  1131. if (canvas) {
  1132. // Fullscreen
  1133. this._onFullscreenChange = () => {
  1134. if (document.fullscreen !== undefined) {
  1135. this.isFullscreen = document.fullscreen;
  1136. } else if (document.mozFullScreen !== undefined) {
  1137. this.isFullscreen = document.mozFullScreen;
  1138. } else if (document.webkitIsFullScreen !== undefined) {
  1139. this.isFullscreen = document.webkitIsFullScreen;
  1140. } else if (document.msIsFullScreen !== undefined) {
  1141. this.isFullscreen = document.msIsFullScreen;
  1142. }
  1143. // Pointer lock
  1144. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  1145. canvas.requestPointerLock = canvas.requestPointerLock ||
  1146. canvas.msRequestPointerLock ||
  1147. canvas.mozRequestPointerLock ||
  1148. canvas.webkitRequestPointerLock;
  1149. if (canvas.requestPointerLock) {
  1150. canvas.requestPointerLock();
  1151. }
  1152. }
  1153. };
  1154. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  1155. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  1156. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  1157. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  1158. // Pointer lock
  1159. this._onPointerLockChange = () => {
  1160. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  1161. document.webkitPointerLockElement === canvas ||
  1162. document.msPointerLockElement === canvas ||
  1163. document.pointerLockElement === canvas
  1164. );
  1165. };
  1166. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  1167. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  1168. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  1169. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  1170. this._onVRDisplayPointerRestricted = () => {
  1171. if (canvas) {
  1172. canvas.requestPointerLock();
  1173. }
  1174. }
  1175. this._onVRDisplayPointerUnrestricted = () => {
  1176. document.exitPointerLock();
  1177. }
  1178. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  1179. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  1180. }
  1181. if (options.audioEngine && AudioEngine && !Engine.audioEngine) {
  1182. Engine.audioEngine = new AudioEngine();
  1183. }
  1184. // Prepare buffer pointers
  1185. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  1186. this._currentBufferPointers[i] = new BufferPointer();
  1187. }
  1188. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  1189. // Load WebVR Devices
  1190. if (options.autoEnableWebVR) {
  1191. this.initWebVR();
  1192. }
  1193. // Detect if we are running on a faulty buggy OS.
  1194. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  1195. // Detect if we are running on a faulty buggy desktop OS.
  1196. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  1197. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  1198. this.enableOfflineSupport = (Database !== undefined);
  1199. }
  1200. private _rebuildInternalTextures(): void {
  1201. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  1202. for (var internalTexture of currentState) {
  1203. internalTexture._rebuild();
  1204. }
  1205. }
  1206. private _rebuildEffects(): void {
  1207. for (var key in this._compiledEffects) {
  1208. let effect = <Effect>this._compiledEffects[key];
  1209. effect._prepareEffect();
  1210. }
  1211. Effect.ResetCache();
  1212. }
  1213. private _rebuildBuffers(): void {
  1214. // Index / Vertex
  1215. for (var scene of this.scenes) {
  1216. scene.resetCachedMaterial();
  1217. scene._rebuildGeometries();
  1218. scene._rebuildTextures();
  1219. }
  1220. // Uniforms
  1221. for (var uniformBuffer of this._uniformBuffers) {
  1222. uniformBuffer._rebuild();
  1223. }
  1224. }
  1225. private _initGLContext(): void {
  1226. // Caps
  1227. this._caps = new EngineCapabilities();
  1228. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  1229. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  1230. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  1231. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  1232. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  1233. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  1234. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  1235. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  1236. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  1237. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  1238. // Infos
  1239. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  1240. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  1241. if (rendererInfo != null) {
  1242. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  1243. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  1244. }
  1245. if (!this._glVendor) {
  1246. this._glVendor = "Unknown vendor";
  1247. }
  1248. if (!this._glRenderer) {
  1249. this._glRenderer = "Unknown renderer";
  1250. }
  1251. // Constants
  1252. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  1253. if (this._gl.RGBA16F !== 0x881A) {
  1254. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  1255. }
  1256. if (this._gl.RGBA32F !== 0x8814) {
  1257. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  1258. }
  1259. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  1260. this._gl.DEPTH24_STENCIL8 = 35056;
  1261. }
  1262. // Extensions
  1263. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  1264. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  1265. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  1266. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  1267. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  1268. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  1269. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  1270. 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');
  1271. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  1272. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  1273. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  1274. this._caps.highPrecisionShaderSupported = true;
  1275. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  1276. if (this._caps.timerQuery) {
  1277. if (this._webGLVersion === 1) {
  1278. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  1279. }
  1280. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  1281. }
  1282. // Checks if some of the format renders first to allow the use of webgl inspector.
  1283. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  1284. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  1285. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  1286. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true: false;
  1287. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true: false;
  1288. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  1289. if (this._webGLVersion > 1) {
  1290. this._gl.HALF_FLOAT_OES = 0x140B;
  1291. }
  1292. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  1293. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true: false;
  1294. // Draw buffers
  1295. if (this._webGLVersion > 1) {
  1296. this._caps.drawBuffersExtension = true;
  1297. } else {
  1298. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1299. if (drawBuffersExtension !== null) {
  1300. this._caps.drawBuffersExtension = true;
  1301. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1302. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1303. for (var i = 0; i < 16; i++) {
  1304. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1305. }
  1306. } else {
  1307. this._caps.drawBuffersExtension = false;
  1308. }
  1309. }
  1310. // Depth Texture
  1311. if (this._webGLVersion > 1) {
  1312. this._caps.depthTextureExtension = true;
  1313. } else {
  1314. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1315. if (depthTextureExtension != null) {
  1316. this._caps.depthTextureExtension = true;
  1317. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  1318. }
  1319. }
  1320. // Vertex array object
  1321. if (this._webGLVersion > 1) {
  1322. this._caps.vertexArrayObject = true;
  1323. } else {
  1324. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1325. if (vertexArrayObjectExtension != null) {
  1326. this._caps.vertexArrayObject = true;
  1327. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1328. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1329. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1330. } else {
  1331. this._caps.vertexArrayObject = false;
  1332. }
  1333. }
  1334. // Instances count
  1335. if (this._webGLVersion > 1) {
  1336. this._caps.instancedArrays = true;
  1337. } else {
  1338. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1339. if (instanceExtension != null) {
  1340. this._caps.instancedArrays = true;
  1341. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1342. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1343. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1344. } else {
  1345. this._caps.instancedArrays = false;
  1346. }
  1347. }
  1348. // Intelligently add supported compressed formats in order to check for.
  1349. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1350. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1351. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1352. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1353. if (this._caps.astc) this.texturesSupported.push('-astc.ktx');
  1354. if (this._caps.s3tc) this.texturesSupported.push('-dxt.ktx');
  1355. if (this._caps.pvrtc) this.texturesSupported.push('-pvrtc.ktx');
  1356. if (this._caps.etc2) this.texturesSupported.push('-etc2.ktx');
  1357. if (this._caps.etc1) this.texturesSupported.push('-etc1.ktx');
  1358. if (this._gl.getShaderPrecisionFormat) {
  1359. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1360. if (highp) {
  1361. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  1362. }
  1363. }
  1364. // Depth buffer
  1365. this.setDepthBuffer(true);
  1366. this.setDepthFunctionToLessOrEqual();
  1367. this.setDepthWrite(true);
  1368. // Texture maps
  1369. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1370. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1371. this._nextFreeTextureSlots.push(slot);
  1372. }
  1373. }
  1374. /**
  1375. * Gets version of the current webGL context
  1376. */
  1377. public get webGLVersion(): number {
  1378. return this._webGLVersion;
  1379. }
  1380. /**
  1381. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1382. */
  1383. public get isStencilEnable(): boolean {
  1384. return this._isStencilEnable;
  1385. }
  1386. private _prepareWorkingCanvas(): void {
  1387. if (this._workingCanvas) {
  1388. return;
  1389. }
  1390. this._workingCanvas = document.createElement("canvas");
  1391. let context = this._workingCanvas.getContext("2d");
  1392. if (context) {
  1393. this._workingContext = context;
  1394. }
  1395. }
  1396. /**
  1397. * Reset the texture cache to empty state
  1398. */
  1399. public resetTextureCache() {
  1400. for (var key in this._boundTexturesCache) {
  1401. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  1402. continue;
  1403. }
  1404. let boundTexture = this._boundTexturesCache[key];
  1405. if (boundTexture) {
  1406. this._removeDesignatedSlot(boundTexture);
  1407. }
  1408. this._boundTexturesCache[key] = null;
  1409. }
  1410. if (!this.disableTextureBindingOptimization) {
  1411. this._nextFreeTextureSlots = [];
  1412. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1413. this._nextFreeTextureSlots.push(slot);
  1414. }
  1415. }
  1416. this._currentTextureChannel = -1;
  1417. }
  1418. /**
  1419. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  1420. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1421. * @returns true if engine is in deterministic lock step mode
  1422. */
  1423. public isDeterministicLockStep(): boolean {
  1424. return this._deterministicLockstep;
  1425. }
  1426. /**
  1427. * Gets the max steps when engine is running in deterministic lock step
  1428. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1429. * @returns the max steps
  1430. */
  1431. public getLockstepMaxSteps(): number {
  1432. return this._lockstepMaxSteps;
  1433. }
  1434. /**
  1435. * Gets an object containing information about the current webGL context
  1436. * @returns an object containing the vender, the renderer and the version of the current webGL context
  1437. */
  1438. public getGlInfo() {
  1439. return {
  1440. vendor: this._glVendor,
  1441. renderer: this._glRenderer,
  1442. version: this._glVersion
  1443. }
  1444. }
  1445. /**
  1446. * Gets current aspect ratio
  1447. * @param camera defines the camera to use to get the aspect ratio
  1448. * @param useScreen defines if screen size must be used (or the current render target if any)
  1449. * @returns a number defining the aspect ratio
  1450. */
  1451. public getAspectRatio(camera: Camera, useScreen = false): number {
  1452. var viewport = camera.viewport;
  1453. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1454. }
  1455. /**
  1456. * Gets current screen aspect ratio
  1457. * @returns a number defining the aspect ratio
  1458. */
  1459. public getScreenAspectRatio(): number {
  1460. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  1461. }
  1462. /**
  1463. * Gets the current render width
  1464. * @param useScreen defines if screen size must be used (or the current render target if any)
  1465. * @returns a number defining the current render width
  1466. */
  1467. public getRenderWidth(useScreen = false): number {
  1468. if (!useScreen && this._currentRenderTarget) {
  1469. return this._currentRenderTarget.width;
  1470. }
  1471. return this._gl.drawingBufferWidth;
  1472. }
  1473. /**
  1474. * Gets the current render height
  1475. * @param useScreen defines if screen size must be used (or the current render target if any)
  1476. * @returns a number defining the current render height
  1477. */
  1478. public getRenderHeight(useScreen = false): number {
  1479. if (!useScreen && this._currentRenderTarget) {
  1480. return this._currentRenderTarget.height;
  1481. }
  1482. return this._gl.drawingBufferHeight;
  1483. }
  1484. /**
  1485. * Gets the HTML canvas attached with the current webGL context
  1486. * @returns a HTML canvas
  1487. */
  1488. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1489. return this._renderingCanvas;
  1490. }
  1491. /**
  1492. * Gets the client rect of the HTML canvas attached with the current webGL context
  1493. * @returns a client rectanglee
  1494. */
  1495. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1496. if (!this._renderingCanvas) {
  1497. return null;
  1498. }
  1499. return this._renderingCanvas.getBoundingClientRect();
  1500. }
  1501. /**
  1502. * Defines the hardware scaling level.
  1503. * By default the hardware scaling level is computed from the window device ratio.
  1504. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  1505. * @param level defines the level to use
  1506. */
  1507. public setHardwareScalingLevel(level: number): void {
  1508. this._hardwareScalingLevel = level;
  1509. this.resize();
  1510. }
  1511. /**
  1512. * Gets the current hardware scaling level.
  1513. * By default the hardware scaling level is computed from the window device ratio.
  1514. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  1515. * @returns a number indicating the current hardware scaling level
  1516. */
  1517. public getHardwareScalingLevel(): number {
  1518. return this._hardwareScalingLevel;
  1519. }
  1520. /**
  1521. * Gets the list of loaded textures
  1522. * @returns an array containing all loaded textures
  1523. */
  1524. public getLoadedTexturesCache(): InternalTexture[] {
  1525. return this._internalTexturesCache;
  1526. }
  1527. /**
  1528. * Gets the object containing all engine capabilities
  1529. * @returns the EngineCapabilities object
  1530. */
  1531. public getCaps(): EngineCapabilities {
  1532. return this._caps;
  1533. }
  1534. /** @hidden */
  1535. public get drawCalls(): number {
  1536. Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  1537. return 0;
  1538. }
  1539. /** @hidden */
  1540. public get drawCallsPerfCounter(): Nullable<PerfCounter> {
  1541. Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  1542. return null;
  1543. }
  1544. /**
  1545. * Gets the current depth function
  1546. * @returns a number defining the depth function
  1547. */
  1548. public getDepthFunction(): Nullable<number> {
  1549. return this._depthCullingState.depthFunc;
  1550. }
  1551. /**
  1552. * Sets the current depth function
  1553. * @param depthFunc defines the function to use
  1554. */
  1555. public setDepthFunction(depthFunc: number) {
  1556. this._depthCullingState.depthFunc = depthFunc;
  1557. }
  1558. /**
  1559. * Sets the current depth function to GREATER
  1560. */
  1561. public setDepthFunctionToGreater(): void {
  1562. this._depthCullingState.depthFunc = this._gl.GREATER;
  1563. }
  1564. /**
  1565. * Sets the current depth function to GEQUAL
  1566. */
  1567. public setDepthFunctionToGreaterOrEqual(): void {
  1568. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  1569. }
  1570. /**
  1571. * Sets the current depth function to LESS
  1572. */
  1573. public setDepthFunctionToLess(): void {
  1574. this._depthCullingState.depthFunc = this._gl.LESS;
  1575. }
  1576. /**
  1577. * Sets the current depth function to LEQUAL
  1578. */
  1579. public setDepthFunctionToLessOrEqual(): void {
  1580. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  1581. }
  1582. /**
  1583. * Gets a boolean indicating if stencil buffer is enabled
  1584. * @returns the current stencil buffer state
  1585. */
  1586. public getStencilBuffer(): boolean {
  1587. return this._stencilState.stencilTest;
  1588. }
  1589. /**
  1590. * Enable or disable the stencil buffer
  1591. * @param enable defines if the stencil buffer must be enabled or disabled
  1592. */
  1593. public setStencilBuffer(enable: boolean): void {
  1594. this._stencilState.stencilTest = enable;
  1595. }
  1596. /**
  1597. * Gets the current stencil mask
  1598. * @returns a number defining the new stencil mask to use
  1599. */
  1600. public getStencilMask(): number {
  1601. return this._stencilState.stencilMask;
  1602. }
  1603. /**
  1604. * Sets the current stencil mask
  1605. * @param mask defines the new stencil mask to use
  1606. */
  1607. public setStencilMask(mask: number): void {
  1608. this._stencilState.stencilMask = mask;
  1609. }
  1610. /**
  1611. * Gets the current stencil function
  1612. * @returns a number defining the stencil function to use
  1613. */
  1614. public getStencilFunction(): number {
  1615. return this._stencilState.stencilFunc;
  1616. }
  1617. /**
  1618. * Gets the current stencil reference value
  1619. * @returns a number defining the stencil reference value to use
  1620. */
  1621. public getStencilFunctionReference(): number {
  1622. return this._stencilState.stencilFuncRef;
  1623. }
  1624. /**
  1625. * Gets the current stencil mask
  1626. * @returns a number defining the stencil mask to use
  1627. */
  1628. public getStencilFunctionMask(): number {
  1629. return this._stencilState.stencilFuncMask;
  1630. }
  1631. /**
  1632. * Sets the current stencil function
  1633. * @param stencilFunc defines the new stencil function to use
  1634. */
  1635. public setStencilFunction(stencilFunc: number) {
  1636. this._stencilState.stencilFunc = stencilFunc;
  1637. }
  1638. /**
  1639. * Sets the current stencil reference
  1640. * @param reference defines the new stencil reference to use
  1641. */
  1642. public setStencilFunctionReference(reference: number) {
  1643. this._stencilState.stencilFuncRef = reference;
  1644. }
  1645. /**
  1646. * Sets the current stencil mask
  1647. * @param mask defines the new stencil mask to use
  1648. */
  1649. public setStencilFunctionMask(mask: number) {
  1650. this._stencilState.stencilFuncMask = mask;
  1651. }
  1652. /**
  1653. * Gets the current stencil operation when stencil fails
  1654. * @returns a number defining stencil operation to use when stencil fails
  1655. */
  1656. public getStencilOperationFail(): number {
  1657. return this._stencilState.stencilOpStencilFail;
  1658. }
  1659. /**
  1660. * Gets the current stencil operation when depth fails
  1661. * @returns a number defining stencil operation to use when depth fails
  1662. */
  1663. public getStencilOperationDepthFail(): number {
  1664. return this._stencilState.stencilOpDepthFail;
  1665. }
  1666. /**
  1667. * Gets the current stencil operation when stencil passes
  1668. * @returns a number defining stencil operation to use when stencil passes
  1669. */
  1670. public getStencilOperationPass(): number {
  1671. return this._stencilState.stencilOpStencilDepthPass;
  1672. }
  1673. /**
  1674. * Sets the stencil operation to use when stencil fails
  1675. * @param operation defines the stencil operation to use when stencil fails
  1676. */
  1677. public setStencilOperationFail(operation: number): void {
  1678. this._stencilState.stencilOpStencilFail = operation;
  1679. }
  1680. /**
  1681. * Sets the stencil operation to use when depth fails
  1682. * @param operation defines the stencil operation to use when depth fails
  1683. */
  1684. public setStencilOperationDepthFail(operation: number): void {
  1685. this._stencilState.stencilOpDepthFail = operation;
  1686. }
  1687. /**
  1688. * Sets the stencil operation to use when stencil passes
  1689. * @param operation defines the stencil operation to use when stencil passes
  1690. */
  1691. public setStencilOperationPass(operation: number): void {
  1692. this._stencilState.stencilOpStencilDepthPass = operation;
  1693. }
  1694. /**
  1695. * Sets a boolean indicating if the dithering state is enabled or disabled
  1696. * @param value defines the dithering state
  1697. */
  1698. public setDitheringState(value: boolean): void {
  1699. if (value) {
  1700. this._gl.enable(this._gl.DITHER);
  1701. } else {
  1702. this._gl.disable(this._gl.DITHER);
  1703. }
  1704. }
  1705. /**
  1706. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  1707. * @param value defines the rasterizer state
  1708. */
  1709. public setRasterizerState(value: boolean): void {
  1710. if (value) {
  1711. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  1712. } else {
  1713. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  1714. }
  1715. }
  1716. /**
  1717. * stop executing a render loop function and remove it from the execution array
  1718. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  1719. */
  1720. public stopRenderLoop(renderFunction?: () => void): void {
  1721. if (!renderFunction) {
  1722. this._activeRenderLoops = [];
  1723. return;
  1724. }
  1725. var index = this._activeRenderLoops.indexOf(renderFunction);
  1726. if (index >= 0) {
  1727. this._activeRenderLoops.splice(index, 1);
  1728. }
  1729. }
  1730. /** @hidden */
  1731. public _renderLoop(): void {
  1732. if (!this._contextWasLost) {
  1733. var shouldRender = true;
  1734. if (!this.renderEvenInBackground && this._windowIsBackground) {
  1735. shouldRender = false;
  1736. }
  1737. if (shouldRender) {
  1738. // Start new frame
  1739. this.beginFrame();
  1740. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  1741. var renderFunction = this._activeRenderLoops[index];
  1742. renderFunction();
  1743. }
  1744. // Present
  1745. this.endFrame();
  1746. }
  1747. }
  1748. if (this._activeRenderLoops.length > 0) {
  1749. // Register new frame
  1750. var requester = null;
  1751. if (this._vrDisplay && this._vrDisplay.isPresenting)
  1752. requester = this._vrDisplay;
  1753. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  1754. } else {
  1755. this._renderingQueueLaunched = false;
  1756. }
  1757. }
  1758. /**
  1759. * Register and execute a render loop. The engine can have more than one render function
  1760. * @param renderFunction defines the function to continuously execute
  1761. */
  1762. public runRenderLoop(renderFunction: () => void): void {
  1763. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  1764. return;
  1765. }
  1766. this._activeRenderLoops.push(renderFunction);
  1767. if (!this._renderingQueueLaunched) {
  1768. this._renderingQueueLaunched = true;
  1769. this._bindedRenderFunction = this._renderLoop.bind(this);
  1770. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1771. }
  1772. }
  1773. /**
  1774. * Toggle full screen mode
  1775. * @param requestPointerLock defines if a pointer lock should be requested from the user
  1776. * @param options defines an option object to be sent to the requestFullscreen function
  1777. */
  1778. public switchFullscreen(requestPointerLock: boolean): void {
  1779. if (this.isFullscreen) {
  1780. Tools.ExitFullscreen();
  1781. } else {
  1782. this._pointerLockRequested = requestPointerLock;
  1783. if (this._renderingCanvas) {
  1784. Tools.RequestFullscreen(this._renderingCanvas);
  1785. }
  1786. }
  1787. }
  1788. /**
  1789. * Clear the current render buffer or the current render target (if any is set up)
  1790. * @param color defines the color to use
  1791. * @param backBuffer defines if the back buffer must be cleared
  1792. * @param depth defines if the depth buffer must be cleared
  1793. * @param stencil defines if the stencil buffer must be cleared
  1794. */
  1795. public clear(color: Nullable<Color4>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  1796. this.applyStates();
  1797. var mode = 0;
  1798. if (backBuffer && color) {
  1799. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1800. mode |= this._gl.COLOR_BUFFER_BIT;
  1801. }
  1802. if (depth) {
  1803. this._gl.clearDepth(1.0);
  1804. mode |= this._gl.DEPTH_BUFFER_BIT;
  1805. }
  1806. if (stencil) {
  1807. this._gl.clearStencil(0);
  1808. mode |= this._gl.STENCIL_BUFFER_BIT;
  1809. }
  1810. this._gl.clear(mode);
  1811. }
  1812. /**
  1813. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  1814. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  1815. * @param y defines the y-coordinate of the corner of the clear rectangle
  1816. * @param width defines the width of the clear rectangle
  1817. * @param height defines the height of the clear rectangle
  1818. * @param clearColor defines the clear color
  1819. */
  1820. public scissorClear(x: number, y: number, width: number, height: number, clearColor: Color4): void {
  1821. let gl = this._gl;
  1822. // Save state
  1823. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  1824. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  1825. // Change state
  1826. gl.enable(gl.SCISSOR_TEST);
  1827. gl.scissor(x, y, width, height);
  1828. // Clear
  1829. this.clear(clearColor, true, true, true);
  1830. // Restore state
  1831. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  1832. if (curScissor === true) {
  1833. gl.enable(gl.SCISSOR_TEST);
  1834. } else {
  1835. gl.disable(gl.SCISSOR_TEST);
  1836. }
  1837. }
  1838. /**
  1839. * Set the WebGL's viewport
  1840. * @param viewport defines the viewport element to be used
  1841. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  1842. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  1843. */
  1844. public setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void {
  1845. var width = requiredWidth || this.getRenderWidth();
  1846. var height = requiredHeight || this.getRenderHeight();
  1847. var x = viewport.x || 0;
  1848. var y = viewport.y || 0;
  1849. this._cachedViewport = viewport;
  1850. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1851. }
  1852. /**
  1853. * Directly set the WebGL Viewport
  1854. * @param x defines the x coordinate of the viewport (in screen space)
  1855. * @param y defines the y coordinate of the viewport (in screen space)
  1856. * @param width defines the width of the viewport (in screen space)
  1857. * @param height defines the height of the viewport (in screen space)
  1858. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
  1859. */
  1860. public setDirectViewport(x: number, y: number, width: number, height: number): Nullable<Viewport> {
  1861. let currentViewport = this._cachedViewport;
  1862. this._cachedViewport = null;
  1863. this._gl.viewport(x, y, width, height);
  1864. return currentViewport;
  1865. }
  1866. /**
  1867. * Begin a new frame
  1868. */
  1869. public beginFrame(): void {
  1870. this.onBeginFrameObservable.notifyObservers(this);
  1871. this._measureFps();
  1872. }
  1873. /**
  1874. * Enf the current frame
  1875. */
  1876. public endFrame(): void {
  1877. // Force a flush in case we are using a bad OS.
  1878. if (this._badOS) {
  1879. this.flushFramebuffer();
  1880. }
  1881. // Submit frame to the vr device, if enabled
  1882. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  1883. // TODO: We should only submit the frame if we read frameData successfully.
  1884. this._vrDisplay.submitFrame();
  1885. }
  1886. this.onEndFrameObservable.notifyObservers(this);
  1887. }
  1888. /**
  1889. * Resize the view according to the canvas' size
  1890. */
  1891. public resize(): void {
  1892. // We're not resizing the size of the canvas while in VR mode & presenting
  1893. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  1894. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1895. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1896. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1897. }
  1898. }
  1899. /**
  1900. * Force a specific size of the canvas
  1901. * @param width defines the new canvas' width
  1902. * @param height defines the new canvas' height
  1903. */
  1904. public setSize(width: number, height: number): void {
  1905. if (!this._renderingCanvas) {
  1906. return;
  1907. }
  1908. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1909. return;
  1910. }
  1911. this._renderingCanvas.width = width;
  1912. this._renderingCanvas.height = height;
  1913. for (var index = 0; index < this.scenes.length; index++) {
  1914. var scene = this.scenes[index];
  1915. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  1916. var cam = scene.cameras[camIndex];
  1917. cam._currentRenderId = 0;
  1918. }
  1919. }
  1920. if (this.onResizeObservable.hasObservers) {
  1921. this.onResizeObservable.notifyObservers(this);
  1922. }
  1923. }
  1924. // WebVR functions
  1925. /**
  1926. * Gets a boolean indicating if a webVR device was detected
  1927. * @returns true if a webVR device was detected
  1928. */
  1929. public isVRDevicePresent(): boolean {
  1930. return !!this._vrDisplay;
  1931. }
  1932. /**
  1933. * Gets the current webVR device
  1934. * @returns the current webVR device (or null)
  1935. */
  1936. public getVRDevice(): any {
  1937. return this._vrDisplay;
  1938. }
  1939. /**
  1940. * Initializes a webVR display and starts listening to display change events
  1941. * The onVRDisplayChangedObservable will be notified upon these changes
  1942. * @returns The onVRDisplayChangedObservable
  1943. */
  1944. public initWebVR(): Observable<IDisplayChangedEventArgs> {
  1945. this.initWebVRAsync();
  1946. return this.onVRDisplayChangedObservable;
  1947. }
  1948. /**
  1949. * Initializes a webVR display and starts listening to display change events
  1950. * The onVRDisplayChangedObservable will be notified upon these changes
  1951. * @returns A promise containing a VRDisplay and if vr is supported
  1952. */
  1953. public initWebVRAsync(): Promise<IDisplayChangedEventArgs> {
  1954. var notifyObservers = () => {
  1955. var eventArgs = {
  1956. vrDisplay: this._vrDisplay,
  1957. vrSupported: this._vrSupported
  1958. };
  1959. this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  1960. this._webVRInitPromise = new Promise((res)=>{res(eventArgs)});
  1961. }
  1962. if (!this._onVrDisplayConnect) {
  1963. this._onVrDisplayConnect = (event) => {
  1964. this._vrDisplay = event.display;
  1965. notifyObservers();
  1966. };
  1967. this._onVrDisplayDisconnect = () => {
  1968. this._vrDisplay.cancelAnimationFrame(this._frameHandler);
  1969. this._vrDisplay = undefined;
  1970. this._frameHandler = Tools.QueueNewFrame(this._bindedRenderFunction);
  1971. notifyObservers();
  1972. };
  1973. this._onVrDisplayPresentChange = () => {
  1974. this._vrExclusivePointerMode = this._vrDisplay && this._vrDisplay.isPresenting;
  1975. }
  1976. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  1977. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  1978. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  1979. }
  1980. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  1981. this._webVRInitPromise.then(notifyObservers);
  1982. return this._webVRInitPromise;
  1983. }
  1984. /**
  1985. * Call this function to switch to webVR mode
  1986. * Will do nothing if webVR is not supported or if there is no webVR device
  1987. * @see http://doc.babylonjs.com/how_to/webvr_camera
  1988. */
  1989. public enableVR() {
  1990. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  1991. var onResolved = () => {
  1992. this.onVRRequestPresentComplete.notifyObservers(true);
  1993. this._onVRFullScreenTriggered();
  1994. };
  1995. var onRejected = () => {
  1996. this.onVRRequestPresentComplete.notifyObservers(false);
  1997. };
  1998. this.onVRRequestPresentStart.notifyObservers(this);
  1999. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  2000. }
  2001. }
  2002. /**
  2003. * Call this function to leave webVR mode
  2004. * Will do nothing if webVR is not supported or if there is no webVR device
  2005. * @see http://doc.babylonjs.com/how_to/webvr_camera
  2006. */
  2007. public disableVR() {
  2008. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  2009. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  2010. }
  2011. }
  2012. private _onVRFullScreenTriggered = () => {
  2013. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  2014. //get the old size before we change
  2015. this._oldSize = new Size(this.getRenderWidth(), this.getRenderHeight());
  2016. this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
  2017. //get the width and height, change the render size
  2018. var leftEye = this._vrDisplay.getEyeParameters('left');
  2019. this.setHardwareScalingLevel(1);
  2020. this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  2021. } else {
  2022. this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
  2023. this.setSize(this._oldSize.width, this._oldSize.height);
  2024. }
  2025. }
  2026. private _getVRDisplaysAsync():Promise<IDisplayChangedEventArgs> {
  2027. return new Promise((res, rej)=>{
  2028. if (navigator.getVRDisplays) {
  2029. navigator.getVRDisplays().then((devices: Array<any>)=>{
  2030. this._vrSupported = true;
  2031. // note that devices may actually be an empty array. This is fine;
  2032. // we expect this._vrDisplay to be undefined in this case.
  2033. this._vrDisplay = devices[0];
  2034. res({
  2035. vrDisplay: this._vrDisplay,
  2036. vrSupported: this._vrSupported
  2037. });
  2038. });
  2039. } else {
  2040. this._vrDisplay = undefined;
  2041. this._vrSupported = false;
  2042. res({
  2043. vrDisplay: this._vrDisplay,
  2044. vrSupported: this._vrSupported
  2045. });
  2046. }
  2047. });
  2048. }
  2049. /**
  2050. * Binds the frame buffer to the specified texture.
  2051. * @param texture The texture to render to or null for the default canvas
  2052. * @param faceIndex The face of the texture to render to in case of cube texture
  2053. * @param requiredWidth The width of the target to render to
  2054. * @param requiredHeight The height of the target to render to
  2055. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  2056. * @param depthStencilTexture The depth stencil texture to use to render
  2057. */
  2058. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture): void {
  2059. if (this._currentRenderTarget) {
  2060. this.unBindFramebuffer(this._currentRenderTarget);
  2061. }
  2062. this._currentRenderTarget = texture;
  2063. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  2064. var gl = this._gl;
  2065. if (texture.isCube) {
  2066. if (faceIndex === undefined) {
  2067. faceIndex = 0;
  2068. }
  2069. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  2070. if (depthStencilTexture) {
  2071. if (depthStencilTexture._generateStencilBuffer) {
  2072. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  2073. }
  2074. else {
  2075. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  2076. }
  2077. }
  2078. }
  2079. if (this._cachedViewport && !forceFullscreenViewport) {
  2080. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  2081. } else {
  2082. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  2083. }
  2084. this.wipeCaches();
  2085. }
  2086. private bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  2087. if (this._currentFramebuffer !== framebuffer) {
  2088. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  2089. this._currentFramebuffer = framebuffer;
  2090. }
  2091. }
  2092. /**
  2093. * Unbind the current render target texture from the webGL context
  2094. * @param texture defines the render target texture to unbind
  2095. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  2096. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  2097. */
  2098. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  2099. this._currentRenderTarget = null;
  2100. // If MSAA, we need to bitblt back to main texture
  2101. var gl = this._gl;
  2102. if (texture._MSAAFramebuffer) {
  2103. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  2104. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  2105. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  2106. 0, 0, texture.width, texture.height,
  2107. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  2108. }
  2109. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2110. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2111. gl.generateMipmap(gl.TEXTURE_2D);
  2112. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2113. }
  2114. if (onBeforeUnbind) {
  2115. if (texture._MSAAFramebuffer) {
  2116. // Bind the correct framebuffer
  2117. this.bindUnboundFramebuffer(texture._framebuffer);
  2118. }
  2119. onBeforeUnbind();
  2120. }
  2121. this.bindUnboundFramebuffer(null);
  2122. }
  2123. /**
  2124. * Unbind a list of render target textures from the webGL context
  2125. * This is used only when drawBuffer extension or webGL2 are active
  2126. * @param textures defines the render target textures to unbind
  2127. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  2128. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  2129. */
  2130. public unBindMultiColorAttachmentFramebuffer(textures: InternalTexture[], disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  2131. this._currentRenderTarget = null;
  2132. // If MSAA, we need to bitblt back to main texture
  2133. var gl = this._gl;
  2134. if (textures[0]._MSAAFramebuffer) {
  2135. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  2136. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  2137. var attachments = textures[0]._attachments;
  2138. if (!attachments) {
  2139. attachments = new Array(textures.length);
  2140. textures[0]._attachments = attachments;
  2141. }
  2142. for (var i = 0; i < textures.length; i++) {
  2143. var texture = textures[i];
  2144. for (var j = 0; j < attachments.length; j++) {
  2145. attachments[j] = gl.NONE;
  2146. }
  2147. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2148. gl.readBuffer(attachments[i]);
  2149. gl.drawBuffers(attachments);
  2150. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  2151. 0, 0, texture.width, texture.height,
  2152. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  2153. }
  2154. for (var i = 0; i < attachments.length; i++) {
  2155. attachments[i] = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  2156. }
  2157. gl.drawBuffers(attachments);
  2158. }
  2159. for (var i = 0; i < textures.length; i++) {
  2160. var texture = textures[i];
  2161. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  2162. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  2163. gl.generateMipmap(gl.TEXTURE_2D);
  2164. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2165. }
  2166. }
  2167. if (onBeforeUnbind) {
  2168. if (textures[0]._MSAAFramebuffer) {
  2169. // Bind the correct framebuffer
  2170. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  2171. }
  2172. onBeforeUnbind();
  2173. }
  2174. this.bindUnboundFramebuffer(null);
  2175. }
  2176. /**
  2177. * Force the mipmap generation for the given render target texture
  2178. * @param texture defines the render target texture to use
  2179. */
  2180. public generateMipMapsForCubemap(texture: InternalTexture) {
  2181. if (texture.generateMipMaps) {
  2182. var gl = this._gl;
  2183. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  2184. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  2185. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  2186. }
  2187. }
  2188. /**
  2189. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  2190. */
  2191. public flushFramebuffer(): void {
  2192. this._gl.flush();
  2193. }
  2194. /**
  2195. * Unbind the current render target and bind the default framebuffer
  2196. */
  2197. public restoreDefaultFramebuffer(): void {
  2198. if (this._currentRenderTarget) {
  2199. this.unBindFramebuffer(this._currentRenderTarget);
  2200. } else {
  2201. this.bindUnboundFramebuffer(null);
  2202. }
  2203. if (this._cachedViewport) {
  2204. this.setViewport(this._cachedViewport);
  2205. }
  2206. this.wipeCaches();
  2207. }
  2208. // UBOs
  2209. /**
  2210. * Create an uniform buffer
  2211. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2212. * @param elements defines the content of the uniform buffer
  2213. * @returns the webGL uniform buffer
  2214. */
  2215. public createUniformBuffer(elements: FloatArray): WebGLBuffer {
  2216. var ubo = this._gl.createBuffer();
  2217. if (!ubo) {
  2218. throw new Error("Unable to create uniform buffer");
  2219. }
  2220. this.bindUniformBuffer(ubo);
  2221. if (elements instanceof Float32Array) {
  2222. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.STATIC_DRAW);
  2223. } else {
  2224. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.STATIC_DRAW);
  2225. }
  2226. this.bindUniformBuffer(null);
  2227. ubo.references = 1;
  2228. return ubo;
  2229. }
  2230. /**
  2231. * Create a dynamic uniform buffer
  2232. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2233. * @param elements defines the content of the uniform buffer
  2234. * @returns the webGL uniform buffer
  2235. */
  2236. public createDynamicUniformBuffer(elements: FloatArray): WebGLBuffer {
  2237. var ubo = this._gl.createBuffer();
  2238. if (!ubo) {
  2239. throw new Error("Unable to create dynamic uniform buffer");
  2240. }
  2241. this.bindUniformBuffer(ubo);
  2242. if (elements instanceof Float32Array) {
  2243. this._gl.bufferData(this._gl.UNIFORM_BUFFER, <Float32Array>elements, this._gl.DYNAMIC_DRAW);
  2244. } else {
  2245. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(<number[]>elements), this._gl.DYNAMIC_DRAW);
  2246. }
  2247. this.bindUniformBuffer(null);
  2248. ubo.references = 1;
  2249. return ubo;
  2250. }
  2251. /**
  2252. * Update an existing uniform buffer
  2253. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  2254. * @param uniformBuffer defines the target uniform buffer
  2255. * @param elements defines the content to update
  2256. * @param offset defines the offset in the uniform buffer where update should start
  2257. * @param count defines the size of the data to update
  2258. */
  2259. public updateUniformBuffer(uniformBuffer: WebGLBuffer, elements: FloatArray, offset?: number, count?: number): void {
  2260. this.bindUniformBuffer(uniformBuffer);
  2261. if (offset === undefined) {
  2262. offset = 0;
  2263. }
  2264. if (count === undefined) {
  2265. if (elements instanceof Float32Array) {
  2266. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, <Float32Array>elements);
  2267. } else {
  2268. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(<number[]>elements));
  2269. }
  2270. } else {
  2271. if (elements instanceof Float32Array) {
  2272. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, <Float32Array>elements.subarray(offset, offset + count));
  2273. } else {
  2274. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(<number[]>elements).subarray(offset, offset + count));
  2275. }
  2276. }
  2277. this.bindUniformBuffer(null);
  2278. }
  2279. // VBOs
  2280. private _resetVertexBufferBinding(): void {
  2281. this.bindArrayBuffer(null);
  2282. this._cachedVertexBuffers = null;
  2283. }
  2284. /**
  2285. * Creates a vertex buffer
  2286. * @param data the data for the vertex buffer
  2287. * @returns the new WebGL static buffer
  2288. */
  2289. public createVertexBuffer(data: DataArray): WebGLBuffer {
  2290. var vbo = this._gl.createBuffer();
  2291. if (!vbo) {
  2292. throw new Error("Unable to create vertex buffer");
  2293. }
  2294. this.bindArrayBuffer(vbo);
  2295. if (data instanceof Array) {
  2296. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  2297. } else {
  2298. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.STATIC_DRAW);
  2299. }
  2300. this._resetVertexBufferBinding();
  2301. vbo.references = 1;
  2302. return vbo;
  2303. }
  2304. /**
  2305. * Creates a dynamic vertex buffer
  2306. * @param data the data for the dynamic vertex buffer
  2307. * @returns the new WebGL dynamic buffer
  2308. */
  2309. public createDynamicVertexBuffer(data: DataArray): WebGLBuffer {
  2310. var vbo = this._gl.createBuffer();
  2311. if (!vbo) {
  2312. throw new Error("Unable to create dynamic vertex buffer");
  2313. }
  2314. this.bindArrayBuffer(vbo);
  2315. if (data instanceof Array) {
  2316. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  2317. } else {
  2318. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.DYNAMIC_DRAW);
  2319. }
  2320. this._resetVertexBufferBinding();
  2321. vbo.references = 1;
  2322. return vbo;
  2323. }
  2324. /**
  2325. * Update a dynamic index buffer
  2326. * @param indexBuffer defines the target index buffer
  2327. * @param indices defines the data to update
  2328. * @param offset defines the offset in the target index buffer where update should start
  2329. */
  2330. public updateDynamicIndexBuffer(indexBuffer: WebGLBuffer, indices: IndicesArray, offset: number = 0): void {
  2331. // Force cache update
  2332. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  2333. this.bindIndexBuffer(indexBuffer);
  2334. var arrayBuffer;
  2335. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  2336. arrayBuffer = indices;
  2337. } else {
  2338. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2339. }
  2340. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  2341. this._resetIndexBufferBinding();
  2342. }
  2343. /**
  2344. * Updates a dynamic vertex buffer.
  2345. * @param vertexBuffer the vertex buffer to update
  2346. * @param data the data used to update the vertex buffer
  2347. * @param byteOffset the byte offset of the data
  2348. * @param byteLength the byte length of the data
  2349. */
  2350. public updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, data: DataArray, byteOffset?: number, byteLength?: number): void {
  2351. this.bindArrayBuffer(vertexBuffer);
  2352. if (byteOffset === undefined) {
  2353. byteOffset = 0;
  2354. }
  2355. if (byteLength === undefined) {
  2356. if (data instanceof Array) {
  2357. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  2358. } else {
  2359. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, <ArrayBuffer>data);
  2360. }
  2361. } else {
  2362. if (data instanceof Array) {
  2363. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  2364. } else {
  2365. if (data instanceof ArrayBuffer) {
  2366. data = new Uint8Array(data, byteOffset, byteLength);
  2367. } else {
  2368. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  2369. }
  2370. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, <ArrayBuffer>data);
  2371. }
  2372. }
  2373. this._resetVertexBufferBinding();
  2374. }
  2375. private _resetIndexBufferBinding(): void {
  2376. this.bindIndexBuffer(null);
  2377. this._cachedIndexBuffer = null;
  2378. }
  2379. /**
  2380. * Creates a new index buffer
  2381. * @param indices defines the content of the index buffer
  2382. * @param updatable defines if the index buffer must be updatable
  2383. * @returns a new webGL buffer
  2384. */
  2385. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): WebGLBuffer {
  2386. var vbo = this._gl.createBuffer();
  2387. if (!vbo) {
  2388. throw new Error("Unable to create index buffer");
  2389. }
  2390. this.bindIndexBuffer(vbo);
  2391. // Check for 32 bits indices
  2392. var arrayBuffer;
  2393. var need32Bits = false;
  2394. if (indices instanceof Uint16Array) {
  2395. arrayBuffer = indices;
  2396. } else {
  2397. //check 32 bit support
  2398. if (this._caps.uintIndices) {
  2399. if (indices instanceof Uint32Array) {
  2400. arrayBuffer = indices;
  2401. need32Bits = true;
  2402. } else {
  2403. //number[] or Int32Array, check if 32 bit is necessary
  2404. for (var index = 0; index < indices.length; index++) {
  2405. if (indices[index] > 65535) {
  2406. need32Bits = true;
  2407. break;
  2408. }
  2409. }
  2410. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  2411. }
  2412. } else {
  2413. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  2414. arrayBuffer = new Uint16Array(indices);
  2415. }
  2416. }
  2417. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  2418. this._resetIndexBufferBinding();
  2419. vbo.references = 1;
  2420. vbo.is32Bits = need32Bits;
  2421. return vbo;
  2422. }
  2423. /**
  2424. * Bind a webGL buffer to the webGL context
  2425. * @param buffer defines the buffer to bind
  2426. */
  2427. public bindArrayBuffer(buffer: Nullable<WebGLBuffer>): void {
  2428. if (!this._vaoRecordInProgress) {
  2429. this._unbindVertexArrayObject();
  2430. }
  2431. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  2432. }
  2433. /**
  2434. * Bind an uniform buffer to the current webGL context
  2435. * @param buffer defines the buffer to bind
  2436. */
  2437. public bindUniformBuffer(buffer: Nullable<WebGLBuffer>): void {
  2438. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  2439. }
  2440. /**
  2441. * Bind a buffer to the current webGL context at a given location
  2442. * @param buffer defines the buffer to bind
  2443. * @param location defines the index where to bind the buffer
  2444. */
  2445. public bindUniformBufferBase(buffer: WebGLBuffer, location: number): void {
  2446. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  2447. }
  2448. /**
  2449. * Bind a specific block at a given index in a specific shader program
  2450. * @param shaderProgram defines the shader program
  2451. * @param blockName defines the block name
  2452. * @param index defines the index where to bind the block
  2453. */
  2454. public bindUniformBlock(shaderProgram: WebGLProgram, blockName: string, index: number): void {
  2455. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  2456. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  2457. };
  2458. private bindIndexBuffer(buffer: Nullable<WebGLBuffer>): void {
  2459. if (!this._vaoRecordInProgress) {
  2460. this._unbindVertexArrayObject();
  2461. }
  2462. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  2463. }
  2464. private bindBuffer(buffer: Nullable<WebGLBuffer>, target: number): void {
  2465. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  2466. this._gl.bindBuffer(target, buffer);
  2467. this._currentBoundBuffer[target] = buffer;
  2468. }
  2469. }
  2470. /**
  2471. * update the bound buffer with the given data
  2472. * @param data defines the data to update
  2473. */
  2474. public updateArrayBuffer(data: Float32Array): void {
  2475. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2476. }
  2477. private _vertexAttribPointer(buffer: WebGLBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  2478. var pointer = this._currentBufferPointers[indx];
  2479. var changed = false;
  2480. if (!pointer.active) {
  2481. changed = true;
  2482. pointer.active = true;
  2483. pointer.index = indx;
  2484. pointer.size = size;
  2485. pointer.type = type;
  2486. pointer.normalized = normalized;
  2487. pointer.stride = stride;
  2488. pointer.offset = offset;
  2489. pointer.buffer = buffer;
  2490. } else {
  2491. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  2492. if (pointer.size !== size) { pointer.size = size; changed = true; }
  2493. if (pointer.type !== type) { pointer.type = type; changed = true; }
  2494. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  2495. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  2496. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  2497. }
  2498. if (changed || this._vaoRecordInProgress) {
  2499. this.bindArrayBuffer(buffer);
  2500. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  2501. }
  2502. }
  2503. private _bindIndexBufferWithCache(indexBuffer: Nullable<WebGLBuffer>): void {
  2504. if (indexBuffer == null) {
  2505. return;
  2506. }
  2507. if (this._cachedIndexBuffer !== indexBuffer) {
  2508. this._cachedIndexBuffer = indexBuffer;
  2509. this.bindIndexBuffer(indexBuffer);
  2510. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  2511. }
  2512. }
  2513. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  2514. var attributes = effect.getAttributesNames();
  2515. if (!this._vaoRecordInProgress) {
  2516. this._unbindVertexArrayObject();
  2517. }
  2518. this.unbindAllAttributes();
  2519. for (var index = 0; index < attributes.length; index++) {
  2520. var order = effect.getAttributeLocation(index);
  2521. if (order >= 0) {
  2522. var vertexBuffer = vertexBuffers[attributes[index]];
  2523. if (!vertexBuffer) {
  2524. continue;
  2525. }
  2526. this._gl.enableVertexAttribArray(order);
  2527. if (!this._vaoRecordInProgress) {
  2528. this._vertexAttribArraysEnabled[order] = true;
  2529. }
  2530. var buffer = vertexBuffer.getBuffer();
  2531. if (buffer) {
  2532. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  2533. if (vertexBuffer.getIsInstanced()) {
  2534. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  2535. if (!this._vaoRecordInProgress) {
  2536. this._currentInstanceLocations.push(order);
  2537. this._currentInstanceBuffers.push(buffer);
  2538. }
  2539. }
  2540. }
  2541. }
  2542. }
  2543. }
  2544. /**
  2545. * Records a vertex array object
  2546. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2547. * @param vertexBuffers defines the list of vertex buffers to store
  2548. * @param indexBuffer defines the index buffer to store
  2549. * @param effect defines the effect to store
  2550. * @returns the new vertex array object
  2551. */
  2552. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): WebGLVertexArrayObject {
  2553. var vao = this._gl.createVertexArray();
  2554. this._vaoRecordInProgress = true;
  2555. this._gl.bindVertexArray(vao);
  2556. this._mustWipeVertexAttributes = true;
  2557. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2558. this.bindIndexBuffer(indexBuffer);
  2559. this._vaoRecordInProgress = false;
  2560. this._gl.bindVertexArray(null);
  2561. return vao;
  2562. }
  2563. /**
  2564. * Bind a specific vertex array object
  2565. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  2566. * @param vertexArrayObject defines the vertex array object to bind
  2567. * @param indexBuffer defines the index buffer to bind
  2568. */
  2569. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<WebGLBuffer>): void {
  2570. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  2571. this._cachedVertexArrayObject = vertexArrayObject;
  2572. this._gl.bindVertexArray(vertexArrayObject);
  2573. this._cachedVertexBuffers = null;
  2574. this._cachedIndexBuffer = null;
  2575. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  2576. this._mustWipeVertexAttributes = true;
  2577. }
  2578. }
  2579. /**
  2580. * Bind webGl buffers directly to the webGL context
  2581. * @param vertexBuffer defines the vertex buffer to bind
  2582. * @param indexBuffer defines the index buffer to bind
  2583. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  2584. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  2585. * @param effect defines the effect associated with the vertex buffer
  2586. */
  2587. public bindBuffersDirectly(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  2588. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  2589. this._cachedVertexBuffers = vertexBuffer;
  2590. this._cachedEffectForVertexBuffers = effect;
  2591. let attributesCount = effect.getAttributesCount();
  2592. this._unbindVertexArrayObject();
  2593. this.unbindAllAttributes();
  2594. var offset = 0;
  2595. for (var index = 0; index < attributesCount; index++) {
  2596. if (index < vertexDeclaration.length) {
  2597. var order = effect.getAttributeLocation(index);
  2598. if (order >= 0) {
  2599. this._gl.enableVertexAttribArray(order);
  2600. this._vertexAttribArraysEnabled[order] = true;
  2601. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  2602. }
  2603. offset += vertexDeclaration[index] * 4;
  2604. }
  2605. }
  2606. }
  2607. this._bindIndexBufferWithCache(indexBuffer);
  2608. }
  2609. private _unbindVertexArrayObject(): void {
  2610. if (!this._cachedVertexArrayObject) {
  2611. return;
  2612. }
  2613. this._cachedVertexArrayObject = null;
  2614. this._gl.bindVertexArray(null);
  2615. }
  2616. /**
  2617. * Bind a list of vertex buffers to the webGL context
  2618. * @param vertexBuffers defines the list of vertex buffers to bind
  2619. * @param indexBuffer defines the index buffer to bind
  2620. * @param effect defines the effect associated with the vertex buffers
  2621. */
  2622. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<WebGLBuffer>, effect: Effect): void {
  2623. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  2624. this._cachedVertexBuffers = vertexBuffers;
  2625. this._cachedEffectForVertexBuffers = effect;
  2626. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  2627. }
  2628. this._bindIndexBufferWithCache(indexBuffer);
  2629. }
  2630. /**
  2631. * Unbind all instance attributes
  2632. */
  2633. public unbindInstanceAttributes() {
  2634. var boundBuffer;
  2635. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  2636. var instancesBuffer = this._currentInstanceBuffers[i];
  2637. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  2638. boundBuffer = instancesBuffer;
  2639. this.bindArrayBuffer(instancesBuffer);
  2640. }
  2641. var offsetLocation = this._currentInstanceLocations[i];
  2642. this._gl.vertexAttribDivisor(offsetLocation, 0);
  2643. }
  2644. this._currentInstanceBuffers.length = 0;
  2645. this._currentInstanceLocations.length = 0;
  2646. }
  2647. /**
  2648. * Release and free the memory of a vertex array object
  2649. * @param vao defines the vertex array object to delete
  2650. */
  2651. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  2652. this._gl.deleteVertexArray(vao);
  2653. }
  2654. /** @hidden */
  2655. public _releaseBuffer(buffer: WebGLBuffer): boolean {
  2656. buffer.references--;
  2657. if (buffer.references === 0) {
  2658. this._gl.deleteBuffer(buffer);
  2659. return true;
  2660. }
  2661. return false;
  2662. }
  2663. /**
  2664. * Creates a webGL buffer to use with instanciation
  2665. * @param capacity defines the size of the buffer
  2666. * @returns the webGL buffer
  2667. */
  2668. public createInstancesBuffer(capacity: number): WebGLBuffer {
  2669. var buffer = this._gl.createBuffer();
  2670. if (!buffer) {
  2671. throw new Error("Unable to create instance buffer");
  2672. }
  2673. buffer.capacity = capacity;
  2674. this.bindArrayBuffer(buffer);
  2675. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  2676. return buffer;
  2677. }
  2678. /**
  2679. * Delete a webGL buffer used with instanciation
  2680. * @param buffer defines the webGL buffer to delete
  2681. */
  2682. public deleteInstancesBuffer(buffer: WebGLBuffer): void {
  2683. this._gl.deleteBuffer(buffer);
  2684. }
  2685. /**
  2686. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  2687. * @param instancesBuffer defines the webGL buffer to update and bind
  2688. * @param data defines the data to store in the buffer
  2689. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  2690. */
  2691. public updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  2692. this.bindArrayBuffer(instancesBuffer);
  2693. if (data) {
  2694. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  2695. }
  2696. if ((<any>offsetLocations[0]).index !== undefined) {
  2697. let stride = 0;
  2698. for (let i = 0; i < offsetLocations.length; i++) {
  2699. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2700. stride += ai.attributeSize * 4;
  2701. }
  2702. for (let i = 0; i < offsetLocations.length; i++) {
  2703. let ai = <InstancingAttributeInfo>offsetLocations[i];
  2704. if (!this._vertexAttribArraysEnabled[ai.index]) {
  2705. this._gl.enableVertexAttribArray(ai.index);
  2706. this._vertexAttribArraysEnabled[ai.index] = true;
  2707. }
  2708. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  2709. this._gl.vertexAttribDivisor(ai.index, 1);
  2710. this._currentInstanceLocations.push(ai.index);
  2711. this._currentInstanceBuffers.push(instancesBuffer);
  2712. }
  2713. } else {
  2714. for (let index = 0; index < 4; index++) {
  2715. let offsetLocation = <number>offsetLocations[index];
  2716. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  2717. this._gl.enableVertexAttribArray(offsetLocation);
  2718. this._vertexAttribArraysEnabled[offsetLocation] = true;
  2719. }
  2720. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  2721. this._gl.vertexAttribDivisor(offsetLocation, 1);
  2722. this._currentInstanceLocations.push(offsetLocation);
  2723. this._currentInstanceBuffers.push(instancesBuffer);
  2724. }
  2725. }
  2726. }
  2727. /**
  2728. * Apply all cached states (depth, culling, stencil and alpha)
  2729. */
  2730. public applyStates() {
  2731. this._depthCullingState.apply(this._gl);
  2732. this._stencilState.apply(this._gl);
  2733. this._alphaState.apply(this._gl);
  2734. }
  2735. /**
  2736. * Send a draw order
  2737. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2738. * @param indexStart defines the starting index
  2739. * @param indexCount defines the number of index to draw
  2740. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2741. */
  2742. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  2743. this.drawElementsType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  2744. }
  2745. /**
  2746. * Draw a list of points
  2747. * @param verticesStart defines the index of first vertex to draw
  2748. * @param verticesCount defines the count of vertices to draw
  2749. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2750. */
  2751. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2752. this.drawArraysType(Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  2753. }
  2754. /**
  2755. * Draw a list of unindexed primitives
  2756. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  2757. * @param verticesStart defines the index of first vertex to draw
  2758. * @param verticesCount defines the count of vertices to draw
  2759. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2760. */
  2761. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2762. this.drawArraysType(useTriangles ? Material.TriangleFillMode : Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  2763. }
  2764. /**
  2765. * Draw a list of indexed primitives
  2766. * @param fillMode defines the primitive to use
  2767. * @param indexStart defines the starting index
  2768. * @param indexCount defines the number of index to draw
  2769. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2770. */
  2771. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  2772. // Apply states
  2773. this.applyStates();
  2774. this._drawCalls.addCount(1, false);
  2775. // Render
  2776. const drawMode = this._drawMode(fillMode);
  2777. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  2778. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  2779. if (instancesCount) {
  2780. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  2781. } else {
  2782. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  2783. }
  2784. }
  2785. /**
  2786. * Draw a list of unindexed primitives
  2787. * @param fillMode defines the primitive to use
  2788. * @param verticesStart defines the index of first vertex to draw
  2789. * @param verticesCount defines the count of vertices to draw
  2790. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  2791. */
  2792. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  2793. // Apply states
  2794. this.applyStates();
  2795. this._drawCalls.addCount(1, false);
  2796. const drawMode = this._drawMode(fillMode);
  2797. if (instancesCount) {
  2798. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  2799. } else {
  2800. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  2801. }
  2802. }
  2803. private _drawMode(fillMode: number): number {
  2804. switch (fillMode) {
  2805. // Triangle views
  2806. case Material.TriangleFillMode:
  2807. return this._gl.TRIANGLES;
  2808. case Material.PointFillMode:
  2809. return this._gl.POINTS;
  2810. case Material.WireFrameFillMode:
  2811. return this._gl.LINES;
  2812. // Draw modes
  2813. case Material.PointListDrawMode:
  2814. return this._gl.POINTS
  2815. case Material.LineListDrawMode:
  2816. return this._gl.LINES;
  2817. case Material.LineLoopDrawMode:
  2818. return this._gl.LINE_LOOP
  2819. case Material.LineStripDrawMode:
  2820. return this._gl.LINE_STRIP
  2821. case Material.TriangleStripDrawMode:
  2822. return this._gl.TRIANGLE_STRIP
  2823. case Material.TriangleFanDrawMode:
  2824. return this._gl.TRIANGLE_FAN;
  2825. default:
  2826. return this._gl.TRIANGLES;
  2827. }
  2828. }
  2829. // Shaders
  2830. /** @hidden */
  2831. public _releaseEffect(effect: Effect): void {
  2832. if (this._compiledEffects[effect._key]) {
  2833. delete this._compiledEffects[effect._key];
  2834. this._deleteProgram(effect.getProgram());
  2835. }
  2836. }
  2837. /** @hidden */
  2838. public _deleteProgram(program: WebGLProgram): void {
  2839. if (program) {
  2840. program.__SPECTOR_rebuildProgram = null;
  2841. if (program.transformFeedback) {
  2842. this.deleteTransformFeedback(program.transformFeedback);
  2843. program.transformFeedback = null;
  2844. }
  2845. this._gl.deleteProgram(program);
  2846. }
  2847. }
  2848. /**
  2849. * Create a new effect (used to store vertex/fragment shaders)
  2850. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  2851. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  2852. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  2853. * @param samplers defines an array of string used to represent textures
  2854. * @param defines defines the string containing the defines to use to compile the shaders
  2855. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  2856. * @param onCompiled defines a function to call when the effect creation is successful
  2857. * @param onError defines a function to call when the effect creation has failed
  2858. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  2859. * @returns the new Effect
  2860. */
  2861. public createEffect(baseName: any, attributesNamesOrOptions: string[] | EffectCreationOptions, uniformsNamesOrEngine: string[] | Engine, samplers?: string[], defines?: string, fallbacks?: EffectFallbacks,
  2862. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void, indexParameters?: any): Effect {
  2863. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  2864. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  2865. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<EffectCreationOptions>attributesNamesOrOptions).defines);
  2866. if (this._compiledEffects[name]) {
  2867. var compiledEffect = <Effect>this._compiledEffects[name];
  2868. if (onCompiled && compiledEffect.isReady()) {
  2869. onCompiled(compiledEffect);
  2870. }
  2871. return compiledEffect;
  2872. }
  2873. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  2874. effect._key = name;
  2875. this._compiledEffects[name] = effect;
  2876. return effect;
  2877. }
  2878. /**
  2879. * Create an effect to use with particle systems
  2880. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  2881. * @param uniformsNames defines a list of attribute names
  2882. * @param samplers defines an array of string used to represent textures
  2883. * @param defines defines the string containing the defines to use to compile the shaders
  2884. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  2885. * @param onCompiled defines a function to call when the effect creation is successful
  2886. * @param onError defines a function to call when the effect creation has failed
  2887. * @returns the new Effect
  2888. */
  2889. public createEffectForParticles(fragmentName: string, uniformsNames: string[] = [], samplers: string[] = [], defines = "", fallbacks?: EffectFallbacks,
  2890. onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect {
  2891. return this.createEffect(
  2892. {
  2893. vertex: "particles",
  2894. fragmentElement: fragmentName
  2895. },
  2896. ["position", "color", "options"],
  2897. ["view", "projection"].concat(uniformsNames),
  2898. ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  2899. }
  2900. /**
  2901. * Directly creates a webGL program
  2902. * @param vertexCode defines the vertex shader code to use
  2903. * @param fragmentCode defines the fragment shader code to use
  2904. * @param context defines the webGL context to use (if not set, the current one will be used)
  2905. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2906. * @returns the new webGL program
  2907. */
  2908. public createRawShaderProgram(vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2909. context = context || this._gl;
  2910. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  2911. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  2912. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2913. }
  2914. /**
  2915. * Creates a webGL program
  2916. * @param vertexCode defines the vertex shader code to use
  2917. * @param fragmentCode defines the fragment shader code to use
  2918. * @param defines defines the string containing the defines to use to compile the shaders
  2919. * @param context defines the webGL context to use (if not set, the current one will be used)
  2920. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  2921. * @returns the new webGL program
  2922. */
  2923. public createShaderProgram(vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2924. context = context || this._gl;
  2925. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  2926. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  2927. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  2928. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  2929. let program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  2930. this.onAfterShaderCompilationObservable.notifyObservers(this);
  2931. return program;
  2932. }
  2933. private _createShaderProgram(vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  2934. var shaderProgram = context.createProgram();
  2935. if (!shaderProgram) {
  2936. throw new Error("Unable to create program");
  2937. }
  2938. context.attachShader(shaderProgram, vertexShader);
  2939. context.attachShader(shaderProgram, fragmentShader);
  2940. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2941. let transformFeedback = this.createTransformFeedback();
  2942. this.bindTransformFeedback(transformFeedback);
  2943. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  2944. shaderProgram.transformFeedback = transformFeedback;
  2945. }
  2946. context.linkProgram(shaderProgram);
  2947. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  2948. this.bindTransformFeedback(null);
  2949. }
  2950. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  2951. if (!linked) {
  2952. context.validateProgram(shaderProgram);
  2953. var error = context.getProgramInfoLog(shaderProgram);
  2954. if (error) {
  2955. throw new Error(error);
  2956. }
  2957. }
  2958. context.deleteShader(vertexShader);
  2959. context.deleteShader(fragmentShader);
  2960. return shaderProgram;
  2961. }
  2962. /**
  2963. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  2964. * @param shaderProgram defines the webGL program to use
  2965. * @param uniformsNames defines the list of uniform names
  2966. * @returns an array of webGL uniform locations
  2967. */
  2968. public getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2969. var results = new Array<Nullable<WebGLUniformLocation>>();
  2970. for (var index = 0; index < uniformsNames.length; index++) {
  2971. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  2972. }
  2973. return results;
  2974. }
  2975. /**
  2976. * Gets the lsit of active attributes for a given webGL program
  2977. * @param shaderProgram defines the webGL program to use
  2978. * @param attributesNames defines the list of attribute names to get
  2979. * @returns an array of indices indicating the offset of each attribute
  2980. */
  2981. public getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[] {
  2982. var results = [];
  2983. for (var index = 0; index < attributesNames.length; index++) {
  2984. try {
  2985. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  2986. } catch (e) {
  2987. results.push(-1);
  2988. }
  2989. }
  2990. return results;
  2991. }
  2992. /**
  2993. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  2994. * @param effect defines the effect to activate
  2995. */
  2996. public enableEffect(effect: Nullable<Effect>): void {
  2997. if (!effect) {
  2998. return;
  2999. }
  3000. // Use program
  3001. this.bindSamplers(effect);
  3002. this._currentEffect = effect;
  3003. if (effect.onBind) {
  3004. effect.onBind(effect);
  3005. }
  3006. effect.onBindObservable.notifyObservers(effect);
  3007. }
  3008. /**
  3009. * Set the value of an uniform to an array of int32
  3010. * @param uniform defines the webGL uniform location where to store the value
  3011. * @param array defines the array of int32 to store
  3012. */
  3013. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3014. if (!uniform)
  3015. return;
  3016. this._gl.uniform1iv(uniform, array);
  3017. }
  3018. /**
  3019. * Set the value of an uniform to an array of int32 (stored as vec2)
  3020. * @param uniform defines the webGL uniform location where to store the value
  3021. * @param array defines the array of int32 to store
  3022. */
  3023. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3024. if (!uniform || array.length % 2 !== 0)
  3025. return;
  3026. this._gl.uniform2iv(uniform, array);
  3027. }
  3028. /**
  3029. * Set the value of an uniform to an array of int32 (stored as vec3)
  3030. * @param uniform defines the webGL uniform location where to store the value
  3031. * @param array defines the array of int32 to store
  3032. */
  3033. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3034. if (!uniform || array.length % 3 !== 0)
  3035. return;
  3036. this._gl.uniform3iv(uniform, array);
  3037. }
  3038. /**
  3039. * Set the value of an uniform to an array of int32 (stored as vec4)
  3040. * @param uniform defines the webGL uniform location where to store the value
  3041. * @param array defines the array of int32 to store
  3042. */
  3043. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  3044. if (!uniform || array.length % 4 !== 0)
  3045. return;
  3046. this._gl.uniform4iv(uniform, array);
  3047. }
  3048. /**
  3049. * Set the value of an uniform to an array of float32
  3050. * @param uniform defines the webGL uniform location where to store the value
  3051. * @param array defines the array of float32 to store
  3052. */
  3053. public setFloatArray(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3054. if (!uniform)
  3055. return;
  3056. this._gl.uniform1fv(uniform, array);
  3057. }
  3058. /**
  3059. * Set the value of an uniform to an array of float32 (stored as vec2)
  3060. * @param uniform defines the webGL uniform location where to store the value
  3061. * @param array defines the array of float32 to store
  3062. */
  3063. public setFloatArray2(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3064. if (!uniform || array.length % 2 !== 0)
  3065. return;
  3066. this._gl.uniform2fv(uniform, array);
  3067. }
  3068. /**
  3069. * Set the value of an uniform to an array of float32 (stored as vec3)
  3070. * @param uniform defines the webGL uniform location where to store the value
  3071. * @param array defines the array of float32 to store
  3072. */
  3073. public setFloatArray3(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3074. if (!uniform || array.length % 3 !== 0)
  3075. return;
  3076. this._gl.uniform3fv(uniform, array);
  3077. }
  3078. /**
  3079. * Set the value of an uniform to an array of float32 (stored as vec4)
  3080. * @param uniform defines the webGL uniform location where to store the value
  3081. * @param array defines the array of float32 to store
  3082. */
  3083. public setFloatArray4(uniform: Nullable<WebGLUniformLocation>, array: Float32Array): void {
  3084. if (!uniform || array.length % 4 !== 0)
  3085. return;
  3086. this._gl.uniform4fv(uniform, array);
  3087. }
  3088. /**
  3089. * Set the value of an uniform to an array of number
  3090. * @param uniform defines the webGL uniform location where to store the value
  3091. * @param array defines the array of number to store
  3092. */
  3093. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3094. if (!uniform)
  3095. return;
  3096. this._gl.uniform1fv(uniform, <any>array);
  3097. }
  3098. /**
  3099. * Set the value of an uniform to an array of number (stored as vec2)
  3100. * @param uniform defines the webGL uniform location where to store the value
  3101. * @param array defines the array of number to store
  3102. */
  3103. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3104. if (!uniform || array.length % 2 !== 0)
  3105. return;
  3106. this._gl.uniform2fv(uniform, <any>array);
  3107. }
  3108. /**
  3109. * Set the value of an uniform to an array of number (stored as vec3)
  3110. * @param uniform defines the webGL uniform location where to store the value
  3111. * @param array defines the array of number to store
  3112. */
  3113. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3114. if (!uniform || array.length % 3 !== 0)
  3115. return;
  3116. this._gl.uniform3fv(uniform, <any>array);
  3117. }
  3118. /**
  3119. * Set the value of an uniform to an array of number (stored as vec4)
  3120. * @param uniform defines the webGL uniform location where to store the value
  3121. * @param array defines the array of number to store
  3122. */
  3123. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[]): void {
  3124. if (!uniform || array.length % 4 !== 0)
  3125. return;
  3126. this._gl.uniform4fv(uniform, <any>array);
  3127. }
  3128. /**
  3129. * Set the value of an uniform to an array of float32 (stored as matrices)
  3130. * @param uniform defines the webGL uniform location where to store the value
  3131. * @param matrices defines the array of float32 to store
  3132. */
  3133. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  3134. if (!uniform)
  3135. return;
  3136. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3137. }
  3138. /**
  3139. * Set the value of an uniform to a matrix
  3140. * @param uniform defines the webGL uniform location where to store the value
  3141. * @param matrix defines the matrix to store
  3142. */
  3143. public setMatrix(uniform: Nullable<WebGLUniformLocation>, matrix: Matrix): void {
  3144. if (!uniform)
  3145. return;
  3146. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3147. }
  3148. /**
  3149. * Set the value of an uniform to a matrix (3x3)
  3150. * @param uniform defines the webGL uniform location where to store the value
  3151. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  3152. */
  3153. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  3154. if (!uniform)
  3155. return;
  3156. this._gl.uniformMatrix3fv(uniform, false, matrix);
  3157. }
  3158. /**
  3159. * Set the value of an uniform to a matrix (2x2)
  3160. * @param uniform defines the webGL uniform location where to store the value
  3161. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  3162. */
  3163. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  3164. if (!uniform)
  3165. return;
  3166. this._gl.uniformMatrix2fv(uniform, false, matrix);
  3167. }
  3168. /**
  3169. * Set the value of an uniform to a number (int)
  3170. * @param uniform defines the webGL uniform location where to store the value
  3171. * @param value defines the int number to store
  3172. */
  3173. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3174. if (!uniform)
  3175. return;
  3176. this._gl.uniform1i(uniform, value);
  3177. }
  3178. /**
  3179. * Set the value of an uniform to a number (float)
  3180. * @param uniform defines the webGL uniform location where to store the value
  3181. * @param value defines the float number to store
  3182. */
  3183. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  3184. if (!uniform)
  3185. return;
  3186. this._gl.uniform1f(uniform, value);
  3187. }
  3188. /**
  3189. * Set the value of an uniform to a vec2
  3190. * @param uniform defines the webGL uniform location where to store the value
  3191. * @param x defines the 1st component of the value
  3192. * @param y defines the 2nd component of the value
  3193. */
  3194. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  3195. if (!uniform)
  3196. return;
  3197. this._gl.uniform2f(uniform, x, y);
  3198. }
  3199. /**
  3200. * Set the value of an uniform to a vec3
  3201. * @param uniform defines the webGL uniform location where to store the value
  3202. * @param x defines the 1st component of the value
  3203. * @param y defines the 2nd component of the value
  3204. * @param z defines the 3rd component of the value
  3205. */
  3206. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  3207. if (!uniform)
  3208. return;
  3209. this._gl.uniform3f(uniform, x, y, z);
  3210. }
  3211. /**
  3212. * Set the value of an uniform to a boolean
  3213. * @param uniform defines the webGL uniform location where to store the value
  3214. * @param bool defines the boolean to store
  3215. */
  3216. public setBool(uniform: Nullable<WebGLUniformLocation>, bool: number): void {
  3217. if (!uniform)
  3218. return;
  3219. this._gl.uniform1i(uniform, bool);
  3220. }
  3221. /**
  3222. * Set the value of an uniform to a vec4
  3223. * @param uniform defines the webGL uniform location where to store the value
  3224. * @param x defines the 1st component of the value
  3225. * @param y defines the 2nd component of the value
  3226. * @param z defines the 3rd component of the value
  3227. * @param w defines the 4th component of the value
  3228. */
  3229. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  3230. if (!uniform)
  3231. return;
  3232. this._gl.uniform4f(uniform, x, y, z, w);
  3233. }
  3234. /**
  3235. * Set the value of an uniform to a Color3
  3236. * @param uniform defines the webGL uniform location where to store the value
  3237. * @param color3 defines the color to store
  3238. */
  3239. public setColor3(uniform: Nullable<WebGLUniformLocation>, color3: Color3): void {
  3240. if (!uniform)
  3241. return;
  3242. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3243. }
  3244. /**
  3245. * Set the value of an uniform to a Color3 and an alpha value
  3246. * @param uniform defines the webGL uniform location where to store the value
  3247. * @param color3 defines the color to store
  3248. * @param alpha defines the alpha component to store
  3249. */
  3250. public setColor4(uniform: Nullable<WebGLUniformLocation>, color3: Color3, alpha: number): void {
  3251. if (!uniform)
  3252. return;
  3253. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3254. }
  3255. /**
  3256. * Sets a Color4 on a uniform variable
  3257. * @param uniform defines the uniform location
  3258. * @param color4 defines the value to be set
  3259. */
  3260. public setDirectColor4(uniform: Nullable<WebGLUniformLocation>, color4: Color4): void {
  3261. if (!uniform)
  3262. return;
  3263. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  3264. }
  3265. // States
  3266. /**
  3267. * Set various states to the webGL context
  3268. * @param culling defines backface culling state
  3269. * @param zOffset defines the value to apply to zOffset (0 by default)
  3270. * @param force defines if states must be applied even if cache is up to date
  3271. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  3272. */
  3273. public setState(culling: boolean, zOffset: number = 0, force?: boolean, reverseSide = false): void {
  3274. // Culling
  3275. if (this._depthCullingState.cull !== culling || force) {
  3276. this._depthCullingState.cull = culling;
  3277. }
  3278. // Cull face
  3279. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3280. if (this._depthCullingState.cullFace !== cullFace || force) {
  3281. this._depthCullingState.cullFace = cullFace;
  3282. }
  3283. // Z offset
  3284. this.setZOffset(zOffset);
  3285. // Front face
  3286. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  3287. if (this._depthCullingState.frontFace !== frontFace || force) {
  3288. this._depthCullingState.frontFace = frontFace;
  3289. }
  3290. }
  3291. /**
  3292. * Set the z offset to apply to current rendering
  3293. * @param value defines the offset to apply
  3294. */
  3295. public setZOffset(value: number): void {
  3296. this._depthCullingState.zOffset = value;
  3297. }
  3298. /**
  3299. * Gets the current value of the zOffset
  3300. * @returns the current zOffset state
  3301. */
  3302. public getZOffset(): number {
  3303. return this._depthCullingState.zOffset;
  3304. }
  3305. /**
  3306. * Enable or disable depth buffering
  3307. * @param enable defines the state to set
  3308. */
  3309. public setDepthBuffer(enable: boolean): void {
  3310. this._depthCullingState.depthTest = enable;
  3311. }
  3312. /**
  3313. * Gets a boolean indicating if depth writing is enabled
  3314. * @returns the current depth writing state
  3315. */
  3316. public getDepthWrite(): boolean {
  3317. return this._depthCullingState.depthMask;
  3318. }
  3319. /**
  3320. * Enable or disable depth writing
  3321. * @param enable defines the state to set
  3322. */
  3323. public setDepthWrite(enable: boolean): void {
  3324. this._depthCullingState.depthMask = enable;
  3325. }
  3326. /**
  3327. * Enable or disable color writing
  3328. * @param enable defines the state to set
  3329. */
  3330. public setColorWrite(enable: boolean): void {
  3331. this._gl.colorMask(enable, enable, enable, enable);
  3332. this._colorWrite = enable;
  3333. }
  3334. /**
  3335. * Gets a boolean indicating if color writing is enabled
  3336. * @returns the current color writing state
  3337. */
  3338. public getColorWrite(): boolean {
  3339. return this._colorWrite;
  3340. }
  3341. /**
  3342. * Sets alpha constants used by some alpha blending modes
  3343. * @param r defines the red component
  3344. * @param g defines the green component
  3345. * @param b defines the blue component
  3346. * @param a defines the alpha component
  3347. */
  3348. public setAlphaConstants(r: number, g: number, b: number, a: number) {
  3349. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  3350. }
  3351. /**
  3352. * Sets the current alpha mode
  3353. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  3354. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  3355. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3356. */
  3357. public setAlphaMode(mode: number, noDepthWriteChange: boolean = false): void {
  3358. if (this._alphaMode === mode) {
  3359. return;
  3360. }
  3361. switch (mode) {
  3362. case Engine.ALPHA_DISABLE:
  3363. this._alphaState.alphaBlend = false;
  3364. break;
  3365. case Engine.ALPHA_PREMULTIPLIED:
  3366. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3367. this._alphaState.alphaBlend = true;
  3368. break;
  3369. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  3370. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3371. this._alphaState.alphaBlend = true;
  3372. break;
  3373. case Engine.ALPHA_COMBINE:
  3374. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3375. this._alphaState.alphaBlend = true;
  3376. break;
  3377. case Engine.ALPHA_ONEONE:
  3378. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3379. this._alphaState.alphaBlend = true;
  3380. break;
  3381. case Engine.ALPHA_ADD:
  3382. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3383. this._alphaState.alphaBlend = true;
  3384. break;
  3385. case Engine.ALPHA_SUBTRACT:
  3386. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3387. this._alphaState.alphaBlend = true;
  3388. break;
  3389. case Engine.ALPHA_MULTIPLY:
  3390. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  3391. this._alphaState.alphaBlend = true;
  3392. break;
  3393. case Engine.ALPHA_MAXIMIZED:
  3394. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  3395. this._alphaState.alphaBlend = true;
  3396. break;
  3397. case Engine.ALPHA_INTERPOLATE:
  3398. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  3399. this._alphaState.alphaBlend = true;
  3400. break;
  3401. case Engine.ALPHA_SCREENMODE:
  3402. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  3403. this._alphaState.alphaBlend = true;
  3404. break;
  3405. }
  3406. if (!noDepthWriteChange) {
  3407. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  3408. }
  3409. this._alphaMode = mode;
  3410. }
  3411. /**
  3412. * Gets the current alpha mode
  3413. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  3414. * @returns the current alpha mode
  3415. */
  3416. public getAlphaMode(): number {
  3417. return this._alphaMode;
  3418. }
  3419. // Textures
  3420. /**
  3421. * Force the entire cache to be cleared
  3422. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  3423. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  3424. */
  3425. public wipeCaches(bruteForce?: boolean): void {
  3426. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  3427. return;
  3428. }
  3429. this._currentEffect = null;
  3430. if (bruteForce) {
  3431. this.resetTextureCache();
  3432. this._currentProgram = null;
  3433. this._stencilState.reset();
  3434. this._depthCullingState.reset();
  3435. this.setDepthFunctionToLessOrEqual();
  3436. this._alphaState.reset();
  3437. }
  3438. this._resetVertexBufferBinding();
  3439. this._cachedIndexBuffer = null;
  3440. this._cachedEffectForVertexBuffers = null;
  3441. this._unbindVertexArrayObject();
  3442. this.bindIndexBuffer(null);
  3443. }
  3444. /**
  3445. * Set the compressed texture format to use, based on the formats you have, and the formats
  3446. * supported by the hardware / browser.
  3447. *
  3448. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  3449. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  3450. * to API arguments needed to compressed textures. This puts the burden on the container
  3451. * generator to house the arcane code for determining these for current & future formats.
  3452. *
  3453. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  3454. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  3455. *
  3456. * Note: The result of this call is not taken into account when a texture is base64.
  3457. *
  3458. * @param formatsAvailable defines the list of those format families you have created
  3459. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  3460. *
  3461. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  3462. * @returns The extension selected.
  3463. */
  3464. public setTextureFormatToUse(formatsAvailable: Array<string>): Nullable<string> {
  3465. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  3466. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  3467. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  3468. return this._textureFormatInUse = this._texturesSupported[i];
  3469. }
  3470. }
  3471. }
  3472. // actively set format to nothing, to allow this to be called more than once
  3473. // and possibly fail the 2nd time
  3474. this._textureFormatInUse = null;
  3475. return null;
  3476. }
  3477. /** @hidden */
  3478. public _createTexture(): WebGLTexture {
  3479. let texture = this._gl.createTexture();
  3480. if (!texture) {
  3481. throw new Error("Unable to create texture");
  3482. }
  3483. return texture;
  3484. }
  3485. /**
  3486. * Usually called from BABYLON.Texture.ts.
  3487. * Passed information to create a WebGLTexture
  3488. * @param urlArg defines a value which contains one of the following:
  3489. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  3490. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  3491. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  3492. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  3493. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  3494. * @param scene needed for loading to the correct scene
  3495. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  3496. * @param onLoad optional callback to be called upon successful completion
  3497. * @param onError optional callback to be called upon failure
  3498. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  3499. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  3500. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  3501. * @returns a InternalTexture for assignment back into BABYLON.Texture
  3502. */
  3503. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE,
  3504. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  3505. buffer: Nullable<string | ArrayBuffer | HTMLImageElement | Blob> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null): InternalTexture {
  3506. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  3507. var fromData = url.substr(0, 5) === "data:";
  3508. var fromBlob = url.substr(0, 5) === "blob:";
  3509. var isBase64 = fromData && url.indexOf("base64") !== -1;
  3510. let texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  3511. // establish the file extension, if possible
  3512. var lastDot = url.lastIndexOf('.');
  3513. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  3514. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  3515. var isTGA = (extension.indexOf(".tga") === 0);
  3516. // determine if a ktx file should be substituted
  3517. var isKTX = false;
  3518. if (this._textureFormatInUse && !isBase64 && !fallback) {
  3519. url = url.substring(0, lastDot) + this._textureFormatInUse;
  3520. isKTX = true;
  3521. }
  3522. if (scene) {
  3523. scene._addPendingData(texture);
  3524. }
  3525. texture.url = url;
  3526. texture.generateMipMaps = !noMipmap;
  3527. texture.samplingMode = samplingMode;
  3528. texture.invertY = invertY;
  3529. if (!this._doNotHandleContextLost) {
  3530. // Keep a link to the buffer only if we plan to handle context lost
  3531. texture._buffer = buffer;
  3532. }
  3533. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  3534. if (onLoad && !fallback) {
  3535. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  3536. }
  3537. if (!fallback) this._internalTexturesCache.push(texture);
  3538. var onerror = (message?: string, exception?: any) => {
  3539. if (scene) {
  3540. scene._removePendingData(texture);
  3541. }
  3542. if (onLoadObserver) {
  3543. texture.onLoadedObservable.remove(onLoadObserver);
  3544. }
  3545. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  3546. if (isKTX) {
  3547. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3548. } else if (Tools.UseFallbackTexture) {
  3549. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3550. }
  3551. if (onError) {
  3552. onError(message || "Unknown error", exception);
  3553. }
  3554. };
  3555. var callback: Nullable<(arrayBuffer: any) => void> = null;
  3556. // processing for non-image formats
  3557. if (isKTX || isTGA || isDDS) {
  3558. if (isKTX) {
  3559. callback = (data) => {
  3560. var ktx = new KhronosTextureContainer(data, 1);
  3561. this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, () => {
  3562. ktx.uploadLevels(this._gl, !noMipmap);
  3563. return false;
  3564. }, samplingMode);
  3565. };
  3566. } else if (isTGA) {
  3567. callback = (arrayBuffer) => {
  3568. var data = new Uint8Array(arrayBuffer);
  3569. var header = TGATools.GetTGAHeader(data);
  3570. this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, () => {
  3571. TGATools.UploadContent(this._gl, data);
  3572. return false;
  3573. }, samplingMode);
  3574. };
  3575. } else if (isDDS) {
  3576. callback = (data) => {
  3577. var info = DDSTools.GetDDSInfo(data);
  3578. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  3579. this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, () => {
  3580. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 1);
  3581. return false;
  3582. }, samplingMode);
  3583. };
  3584. }
  3585. if (!buffer) {
  3586. this._loadFile(url, data => {
  3587. if (callback) {
  3588. callback(data);
  3589. }
  3590. }, undefined, scene ? scene.database : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  3591. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  3592. });
  3593. } else {
  3594. if (callback) {
  3595. callback(buffer);
  3596. }
  3597. }
  3598. // image format processing
  3599. } else {
  3600. var onload = (img: HTMLImageElement) => {
  3601. if (fromBlob && !this._doNotHandleContextLost) {
  3602. // We need to store the image if we need to rebuild the texture
  3603. // in case of a webgl context lost
  3604. texture._buffer = img;
  3605. }
  3606. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  3607. let gl = this._gl;
  3608. var isPot = (img.width === potWidth && img.height === potHeight);
  3609. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  3610. if (isPot) {
  3611. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3612. return false;
  3613. }
  3614. // Using shaders to rescale because canvas.drawImage is lossy
  3615. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3616. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  3617. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3618. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3619. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3620. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3621. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3622. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  3623. this._releaseTexture(source);
  3624. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3625. continuationCallback();
  3626. });
  3627. return true;
  3628. }, samplingMode);
  3629. };
  3630. if (!fromData || isBase64) {
  3631. if (buffer instanceof HTMLImageElement) {
  3632. onload(buffer);
  3633. } else {
  3634. Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  3635. }
  3636. }
  3637. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  3638. Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  3639. }
  3640. else {
  3641. onload(<HTMLImageElement>buffer);
  3642. }
  3643. }
  3644. return texture;
  3645. }
  3646. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  3647. let rtt = this.createRenderTargetTexture({
  3648. width: destination.width,
  3649. height: destination.height,
  3650. }, {
  3651. generateMipMaps: false,
  3652. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  3653. samplingMode: Texture.BILINEAR_SAMPLINGMODE,
  3654. generateDepthBuffer: false,
  3655. generateStencilBuffer: false
  3656. }
  3657. );
  3658. if (!this._rescalePostProcess) {
  3659. this._rescalePostProcess = new PassPostProcess("rescale", 1, null, Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  3660. }
  3661. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  3662. this._rescalePostProcess.onApply = function (effect) {
  3663. effect._bindTexture("textureSampler", source);
  3664. }
  3665. let hostingScene = scene;
  3666. if (!hostingScene) {
  3667. hostingScene = this.scenes[this.scenes.length - 1];
  3668. }
  3669. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  3670. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  3671. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  3672. this.unBindFramebuffer(rtt);
  3673. this._releaseTexture(rtt);
  3674. if (onComplete) {
  3675. onComplete();
  3676. }
  3677. });
  3678. }
  3679. /**
  3680. * Update a raw texture
  3681. * @param texture defines the texture to update
  3682. * @param data defines the data to store in the texture
  3683. * @param format defines the format of the data
  3684. * @param invertY defines if data must be stored with Y axis inverted
  3685. * @param compression defines the compression used (null by default)
  3686. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3687. */
  3688. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void { if (!texture) {
  3689. return;
  3690. }
  3691. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  3692. var internalFormat = this._getInternalFormat(format);
  3693. var textureType = this._getWebGLTextureType(type);
  3694. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3695. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3696. if (!this._doNotHandleContextLost) {
  3697. texture._bufferView = data;
  3698. texture.format = format;
  3699. texture.type = type;
  3700. texture.invertY = invertY;
  3701. texture._compression = compression;
  3702. }
  3703. if (texture.width % 4 !== 0) {
  3704. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3705. }
  3706. if (compression && data) {
  3707. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, <DataView>data);
  3708. } else {
  3709. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  3710. }
  3711. if (texture.generateMipMaps) {
  3712. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3713. }
  3714. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3715. // this.resetTextureCache();
  3716. texture.isReady = true;
  3717. }
  3718. /**
  3719. * Creates a raw texture
  3720. * @param data defines the data to store in the texture
  3721. * @param width defines the width of the texture
  3722. * @param height defines the height of the texture
  3723. * @param format defines the format of the data
  3724. * @param generateMipMaps defines if the engine should generate the mip levels
  3725. * @param invertY defines if data must be stored with Y axis inverted
  3726. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3727. * @param compression defines the compression used (null by default)
  3728. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3729. * @returns the raw texture inside an InternalTexture
  3730. */
  3731. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, type: number = Engine.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  3732. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  3733. texture.baseWidth = width;
  3734. texture.baseHeight = height;
  3735. texture.width = width;
  3736. texture.height = height;
  3737. texture.format = format;
  3738. texture.generateMipMaps = generateMipMaps;
  3739. texture.samplingMode = samplingMode;
  3740. texture.invertY = invertY;
  3741. texture._compression = compression;
  3742. texture.type = type;
  3743. if (!this._doNotHandleContextLost) {
  3744. texture._bufferView = data;
  3745. }
  3746. this.updateRawTexture(texture, data, format, invertY, compression, type);
  3747. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3748. // Filters
  3749. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3750. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3751. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3752. if (generateMipMaps) {
  3753. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3754. }
  3755. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3756. this._internalTexturesCache.push(texture);
  3757. return texture;
  3758. }
  3759. /**
  3760. * Creates a dynamic texture
  3761. * @param width defines the width of the texture
  3762. * @param height defines the height of the texture
  3763. * @param generateMipMaps defines if the engine should generate the mip levels
  3764. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3765. * @returns the dynamic texture inside an InternalTexture
  3766. */
  3767. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  3768. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC)
  3769. texture.baseWidth = width;
  3770. texture.baseHeight = height;
  3771. if (generateMipMaps) {
  3772. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  3773. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  3774. }
  3775. // this.resetTextureCache();
  3776. texture.width = width;
  3777. texture.height = height;
  3778. texture.isReady = false;
  3779. texture.generateMipMaps = generateMipMaps;
  3780. texture.samplingMode = samplingMode;
  3781. this.updateTextureSamplingMode(samplingMode, texture);
  3782. this._internalTexturesCache.push(texture);
  3783. return texture;
  3784. }
  3785. /**
  3786. * Update the sampling mode of a given texture
  3787. * @param samplingMode defines the required sampling mode
  3788. * @param texture defines the texture to update
  3789. */
  3790. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  3791. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  3792. if (texture.isCube) {
  3793. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3794. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3795. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3796. } else if (texture.is3D) {
  3797. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3798. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3799. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3800. } else {
  3801. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3802. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3803. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3804. }
  3805. texture.samplingMode = samplingMode;
  3806. }
  3807. /**
  3808. * Update the content of a dynamic texture
  3809. * @param texture defines the texture to update
  3810. * @param canvas defines the canvas containing the source
  3811. * @param invertY defines if data must be stored with Y axis inverted
  3812. * @param premulAlpha defines if alpha is stored as premultiplied
  3813. * @param format defines the format of the data
  3814. */
  3815. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number): void {
  3816. if (!texture) {
  3817. return;
  3818. }
  3819. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3820. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3821. if (premulAlpha) {
  3822. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  3823. }
  3824. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  3825. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  3826. if (texture.generateMipMaps) {
  3827. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3828. }
  3829. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3830. if (premulAlpha) {
  3831. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  3832. }
  3833. texture.isReady = true;
  3834. }
  3835. /**
  3836. * Update a video texture
  3837. * @param texture defines the texture to update
  3838. * @param video defines the video element to use
  3839. * @param invertY defines if data must be stored with Y axis inverted
  3840. */
  3841. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  3842. if (!texture || texture._isDisabled) {
  3843. return;
  3844. }
  3845. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3846. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  3847. try {
  3848. // Testing video texture support
  3849. if (this._videoTextureSupported === undefined) {
  3850. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3851. if (this._gl.getError() !== 0) {
  3852. this._videoTextureSupported = false;
  3853. } else {
  3854. this._videoTextureSupported = true;
  3855. }
  3856. }
  3857. // Copy video through the current working canvas if video texture is not supported
  3858. if (!this._videoTextureSupported) {
  3859. if (!texture._workingCanvas) {
  3860. texture._workingCanvas = document.createElement("canvas");
  3861. let context = texture._workingCanvas.getContext("2d");
  3862. if (!context) {
  3863. throw new Error("Unable to get 2d context");
  3864. }
  3865. texture._workingContext = context;
  3866. texture._workingCanvas.width = texture.width;
  3867. texture._workingCanvas.height = texture.height;
  3868. }
  3869. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  3870. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3871. } else {
  3872. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3873. }
  3874. if (texture.generateMipMaps) {
  3875. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3876. }
  3877. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3878. // this.resetTextureCache();
  3879. texture.isReady = true;
  3880. } catch (ex) {
  3881. // Something unexpected
  3882. // Let's disable the texture
  3883. texture._isDisabled = true;
  3884. }
  3885. }
  3886. /**
  3887. * Updates a depth texture Comparison Mode and Function.
  3888. * If the comparison Function is equal to 0, the mode will be set to none.
  3889. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  3890. * @param texture The texture to set the comparison function for
  3891. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  3892. */
  3893. public updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void {
  3894. if (this.webGLVersion === 1) {
  3895. Tools.Error("WebGL 1 does not support texture comparison.");
  3896. return;
  3897. }
  3898. var gl = this._gl;
  3899. if (texture.isCube) {
  3900. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  3901. if (comparisonFunction === 0) {
  3902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3903. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3904. }
  3905. else {
  3906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3908. }
  3909. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3910. } else {
  3911. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3912. if (comparisonFunction === 0) {
  3913. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3914. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3915. }
  3916. else {
  3917. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3918. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3919. }
  3920. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3921. }
  3922. texture._comparisonFunction = comparisonFunction;
  3923. }
  3924. private _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number) : void {
  3925. var width = (<{ width: number, height: number }>size).width || <number>size;
  3926. var height = (<{ width: number, height: number }>size).height || <number>size;
  3927. internalTexture.baseWidth = width;
  3928. internalTexture.baseHeight = height;
  3929. internalTexture.width = width;
  3930. internalTexture.height = height;
  3931. internalTexture.isReady = true;
  3932. internalTexture.samples = 1;
  3933. internalTexture.generateMipMaps = false;
  3934. internalTexture._generateDepthBuffer = true;
  3935. internalTexture._generateStencilBuffer = generateStencil;
  3936. internalTexture.samplingMode = bilinearFiltering ? Texture.BILINEAR_SAMPLINGMODE : Texture.NEAREST_SAMPLINGMODE;
  3937. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  3938. internalTexture._comparisonFunction = comparisonFunction;
  3939. var gl = this._gl;
  3940. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  3941. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  3942. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  3943. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  3944. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3945. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3946. if (comparisonFunction === 0) {
  3947. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  3948. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  3949. }
  3950. else {
  3951. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  3952. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  3953. }
  3954. }
  3955. /**
  3956. * Creates a depth stencil texture.
  3957. * This is only available in WebGL 2 or with the depth texture extension available.
  3958. * @param size The size of face edge in the texture.
  3959. * @param options The options defining the texture.
  3960. * @returns The texture
  3961. */
  3962. public createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  3963. if (options.isCube) {
  3964. let width = (<{ width: number, height: number }>size).width || <number>size;
  3965. return this._createDepthStencilCubeTexture(width, options);
  3966. }
  3967. else {
  3968. return this._createDepthStencilTexture(size, options);
  3969. }
  3970. }
  3971. /**
  3972. * Creates a depth stencil texture.
  3973. * This is only available in WebGL 2 or with the depth texture extension available.
  3974. * @param size The size of face edge in the texture.
  3975. * @param options The options defining the texture.
  3976. * @returns The texture
  3977. */
  3978. private _createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions) : InternalTexture {
  3979. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_DEPTHTEXTURE);
  3980. if (!this._caps.depthTextureExtension) {
  3981. Tools.Error("Depth texture is not supported by your browser or hardware.");
  3982. return internalTexture;
  3983. }
  3984. var internalOptions = {
  3985. bilinearFiltering: false,
  3986. comparisonFunction: 0,
  3987. generateStencil: false,
  3988. ...options
  3989. }
  3990. var gl = this._gl;
  3991. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  3992. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  3993. if (this.webGLVersion > 1) {
  3994. if (internalOptions.generateStencil) {
  3995. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  3996. }
  3997. else {
  3998. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  3999. }
  4000. }
  4001. else {
  4002. if (internalOptions.generateStencil) {
  4003. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4004. }
  4005. else {
  4006. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4007. }
  4008. }
  4009. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4010. return internalTexture;
  4011. }
  4012. /**
  4013. * Creates a depth stencil cube texture.
  4014. * This is only available in WebGL 2.
  4015. * @param size The size of face edge in the cube texture.
  4016. * @param options The options defining the cube texture.
  4017. * @returns The cube texture
  4018. */
  4019. private _createDepthStencilCubeTexture(size: number, options: DepthTextureCreationOptions) : InternalTexture {
  4020. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_UNKNOWN);
  4021. internalTexture.isCube = true;
  4022. if (this.webGLVersion === 1) {
  4023. Tools.Error("Depth cube texture is not supported by WebGL 1.");
  4024. return internalTexture;
  4025. }
  4026. var internalOptions = {
  4027. bilinearFiltering: false,
  4028. comparisonFunction: 0,
  4029. generateStencil: false,
  4030. ...options
  4031. }
  4032. var gl = this._gl;
  4033. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  4034. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4035. // Create the depth/stencil buffer
  4036. for (var face = 0; face < 6; face++) {
  4037. if (internalOptions.generateStencil) {
  4038. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4039. }
  4040. else {
  4041. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4042. }
  4043. }
  4044. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4045. return internalTexture;
  4046. }
  4047. /**
  4048. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  4049. * @param renderTarget The render target to set the frame buffer for
  4050. */
  4051. public setFrameBufferDepthStencilTexture(renderTarget: RenderTargetTexture): void {
  4052. // Create the framebuffer
  4053. var internalTexture = renderTarget.getInternalTexture();
  4054. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  4055. return;
  4056. }
  4057. var gl = this._gl;
  4058. var depthStencilTexture = renderTarget.depthStencilTexture;
  4059. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  4060. if (depthStencilTexture.isCube) {
  4061. if (depthStencilTexture._generateStencilBuffer) {
  4062. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4063. }
  4064. else {
  4065. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4066. }
  4067. }
  4068. else {
  4069. if (depthStencilTexture._generateStencilBuffer) {
  4070. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4071. }
  4072. else {
  4073. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4074. }
  4075. }
  4076. this.bindUnboundFramebuffer(null);
  4077. }
  4078. /**
  4079. * Creates a new render target texture
  4080. * @param size defines the size of the texture
  4081. * @param options defines the options used to create the texture
  4082. * @returns a new render target texture stored in an InternalTexture
  4083. */
  4084. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  4085. let fullOptions = new RenderTargetCreationOptions();
  4086. if (options !== undefined && typeof options === "object") {
  4087. fullOptions.generateMipMaps = options.generateMipMaps;
  4088. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4089. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  4090. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  4091. fullOptions.samplingMode = options.samplingMode === undefined ? Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  4092. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  4093. } else {
  4094. fullOptions.generateMipMaps = <boolean>options;
  4095. fullOptions.generateDepthBuffer = true;
  4096. fullOptions.generateStencilBuffer = false;
  4097. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4098. fullOptions.samplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  4099. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  4100. }
  4101. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4102. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4103. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4104. }
  4105. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4106. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4107. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4108. }
  4109. var gl = this._gl;
  4110. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4111. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  4112. var width = (<{ width: number, height: number }>size).width || <number>size;
  4113. var height = (<{ width: number, height: number }>size).height || <number>size;
  4114. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  4115. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4116. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4117. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4118. }
  4119. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4120. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4121. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4123. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4124. // Create the framebuffer
  4125. var currentFrameBuffer = this._currentFramebuffer;
  4126. var framebuffer = gl.createFramebuffer();
  4127. this.bindUnboundFramebuffer(framebuffer);
  4128. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4129. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  4130. if (fullOptions.generateMipMaps) {
  4131. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4132. }
  4133. // Unbind
  4134. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4135. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4136. this.bindUnboundFramebuffer(currentFrameBuffer);
  4137. texture._framebuffer = framebuffer;
  4138. texture.baseWidth = width;
  4139. texture.baseHeight = height;
  4140. texture.width = width;
  4141. texture.height = height;
  4142. texture.isReady = true;
  4143. texture.samples = 1;
  4144. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  4145. texture.samplingMode = fullOptions.samplingMode;
  4146. texture.type = fullOptions.type;
  4147. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4148. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  4149. // this.resetTextureCache();
  4150. this._internalTexturesCache.push(texture);
  4151. return texture;
  4152. }
  4153. /**
  4154. * Create a multi render target texture
  4155. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  4156. * @param size defines the size of the texture
  4157. * @param options defines the creation options
  4158. * @returns the cube texture as an InternalTexture
  4159. */
  4160. public createMultipleRenderTarget(size: any, options: IMultiRenderTargetOptions): InternalTexture[] {
  4161. var generateMipMaps = false;
  4162. var generateDepthBuffer = true;
  4163. var generateStencilBuffer = false;
  4164. var generateDepthTexture = false;
  4165. var textureCount = 1;
  4166. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  4167. var defaultSamplingMode = Texture.TRILINEAR_SAMPLINGMODE;
  4168. var types = new Array<number>();
  4169. var samplingModes = new Array<number>();
  4170. if (options !== undefined) {
  4171. generateMipMaps = options.generateMipMaps === undefined ? false: options.generateMipMaps;
  4172. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4173. generateStencilBuffer = options.generateStencilBuffer === undefined ? false: options.generateStencilBuffer;
  4174. generateDepthTexture = options.generateDepthTexture === undefined ? false: options.generateDepthTexture;
  4175. textureCount = options.textureCount || 1;
  4176. if (options.types) {
  4177. types = options.types;
  4178. }
  4179. if (options.samplingModes) {
  4180. samplingModes = options.samplingModes;
  4181. }
  4182. }
  4183. var gl = this._gl;
  4184. // Create the framebuffer
  4185. var framebuffer = gl.createFramebuffer();
  4186. this.bindUnboundFramebuffer(framebuffer);
  4187. var width = size.width || size;
  4188. var height = size.height || size;
  4189. var textures = [];
  4190. var attachments = []
  4191. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  4192. for (var i = 0; i < textureCount; i++) {
  4193. var samplingMode = samplingModes[i] || defaultSamplingMode;
  4194. var type = types[i] || defaultType;
  4195. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4196. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4197. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4198. }
  4199. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4200. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4201. samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4202. }
  4203. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4204. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4205. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4206. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4207. }
  4208. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4209. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4210. textures.push(texture);
  4211. attachments.push(attachment);
  4212. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  4213. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  4214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4215. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4216. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4218. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4219. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4220. if (generateMipMaps) {
  4221. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4222. }
  4223. // Unbind
  4224. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4225. texture._framebuffer = framebuffer;
  4226. texture._depthStencilBuffer = depthStencilBuffer;
  4227. texture.baseWidth = width;
  4228. texture.baseHeight = height;
  4229. texture.width = width;
  4230. texture.height = height;
  4231. texture.isReady = true;
  4232. texture.samples = 1;
  4233. texture.generateMipMaps = generateMipMaps;
  4234. texture.samplingMode = samplingMode;
  4235. texture.type = type;
  4236. texture._generateDepthBuffer = generateDepthBuffer;
  4237. texture._generateStencilBuffer = generateStencilBuffer;
  4238. texture._attachments = attachments;
  4239. this._internalTexturesCache.push(texture);
  4240. }
  4241. if (generateDepthTexture && this._caps.depthTextureExtension) {
  4242. // Depth texture
  4243. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4244. gl.activeTexture(gl.TEXTURE0);
  4245. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  4246. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4249. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4250. gl.texImage2D(
  4251. gl.TEXTURE_2D,
  4252. 0,
  4253. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  4254. width,
  4255. height,
  4256. 0,
  4257. gl.DEPTH_COMPONENT,
  4258. gl.UNSIGNED_SHORT,
  4259. null
  4260. );
  4261. gl.framebufferTexture2D(
  4262. gl.FRAMEBUFFER,
  4263. gl.DEPTH_ATTACHMENT,
  4264. gl.TEXTURE_2D,
  4265. depthTexture._webGLTexture,
  4266. 0
  4267. );
  4268. depthTexture._framebuffer = framebuffer;
  4269. depthTexture.baseWidth = width;
  4270. depthTexture.baseHeight = height;
  4271. depthTexture.width = width;
  4272. depthTexture.height = height;
  4273. depthTexture.isReady = true;
  4274. depthTexture.samples = 1;
  4275. depthTexture.generateMipMaps = generateMipMaps;
  4276. depthTexture.samplingMode = gl.NEAREST;
  4277. depthTexture._generateDepthBuffer = generateDepthBuffer;
  4278. depthTexture._generateStencilBuffer = generateStencilBuffer;
  4279. textures.push(depthTexture)
  4280. this._internalTexturesCache.push(depthTexture);
  4281. }
  4282. gl.drawBuffers(attachments);
  4283. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4284. this.bindUnboundFramebuffer(null);
  4285. this.resetTextureCache();
  4286. return textures;
  4287. }
  4288. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  4289. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  4290. var gl = this._gl;
  4291. // Create the depth/stencil buffer
  4292. if (generateStencilBuffer) {
  4293. depthStencilBuffer = gl.createRenderbuffer();
  4294. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4295. if (samples > 1) {
  4296. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  4297. } else {
  4298. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  4299. }
  4300. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4301. }
  4302. else if (generateDepthBuffer) {
  4303. depthStencilBuffer = gl.createRenderbuffer();
  4304. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4305. if (samples > 1) {
  4306. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  4307. } else {
  4308. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4309. }
  4310. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4311. }
  4312. return depthStencilBuffer;
  4313. }
  4314. /**
  4315. * Updates the sample count of a render target texture
  4316. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4317. * @param texture defines the texture to update
  4318. * @param samples defines the sample count to set
  4319. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4320. */
  4321. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  4322. if (this.webGLVersion < 2 || !texture) {
  4323. return 1;
  4324. }
  4325. if (texture.samples === samples) {
  4326. return samples;
  4327. }
  4328. var gl = this._gl;
  4329. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4330. // Dispose previous render buffers
  4331. if (texture._depthStencilBuffer) {
  4332. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  4333. texture._depthStencilBuffer = null;
  4334. }
  4335. if (texture._MSAAFramebuffer) {
  4336. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  4337. texture._MSAAFramebuffer = null;
  4338. }
  4339. if (texture._MSAARenderBuffer) {
  4340. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  4341. texture._MSAARenderBuffer = null;
  4342. }
  4343. if (samples > 1) {
  4344. let framebuffer = gl.createFramebuffer();
  4345. if (!framebuffer) {
  4346. throw new Error("Unable to create multi sampled framebuffer");
  4347. }
  4348. texture._MSAAFramebuffer = framebuffer;
  4349. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  4350. var colorRenderbuffer = gl.createRenderbuffer();
  4351. if (!colorRenderbuffer) {
  4352. throw new Error("Unable to create multi sampled framebuffer");
  4353. }
  4354. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4355. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4356. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  4357. texture._MSAARenderBuffer = colorRenderbuffer;
  4358. } else {
  4359. this.bindUnboundFramebuffer(texture._framebuffer);
  4360. }
  4361. texture.samples = samples;
  4362. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  4363. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4364. this.bindUnboundFramebuffer(null);
  4365. return samples;
  4366. }
  4367. /**
  4368. * Update the sample count for a given multiple render target texture
  4369. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4370. * @param textures defines the textures to update
  4371. * @param samples defines the sample count to set
  4372. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4373. */
  4374. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  4375. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  4376. return 1;
  4377. }
  4378. if (textures[0].samples === samples) {
  4379. return samples;
  4380. }
  4381. var gl = this._gl;
  4382. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4383. // Dispose previous render buffers
  4384. if (textures[0]._depthStencilBuffer) {
  4385. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  4386. textures[0]._depthStencilBuffer = null;
  4387. }
  4388. if (textures[0]._MSAAFramebuffer) {
  4389. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  4390. textures[0]._MSAAFramebuffer = null;
  4391. }
  4392. for (var i = 0; i < textures.length; i++) {
  4393. if (textures[i]._MSAARenderBuffer) {
  4394. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  4395. textures[i]._MSAARenderBuffer = null;
  4396. }
  4397. }
  4398. if (samples > 1) {
  4399. let framebuffer = gl.createFramebuffer();
  4400. if (!framebuffer) {
  4401. throw new Error("Unable to create multi sampled framebuffer");
  4402. }
  4403. this.bindUnboundFramebuffer(framebuffer);
  4404. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  4405. var attachments = [];
  4406. for (var i = 0; i < textures.length; i++) {
  4407. var texture = textures[i];
  4408. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4409. var colorRenderbuffer = gl.createRenderbuffer();
  4410. if (!colorRenderbuffer) {
  4411. throw new Error("Unable to create multi sampled framebuffer");
  4412. }
  4413. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4414. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4415. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  4416. texture._MSAAFramebuffer = framebuffer;
  4417. texture._MSAARenderBuffer = colorRenderbuffer;
  4418. texture.samples = samples;
  4419. texture._depthStencilBuffer = depthStencilBuffer;
  4420. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4421. attachments.push(attachment);
  4422. }
  4423. gl.drawBuffers(attachments);
  4424. } else {
  4425. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  4426. }
  4427. this.bindUnboundFramebuffer(null);
  4428. return samples;
  4429. }
  4430. /** @hidden */
  4431. public _uploadDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, format: number, type: number, data: ArrayBufferView) {
  4432. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  4433. }
  4434. /** @hidden */
  4435. public _uploadCompressedDataToTexture(target: number, lod: number, internalFormat: number, width: number, height: number, data: ArrayBufferView) {
  4436. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  4437. }
  4438. /**
  4439. * Creates a new render target cube texture
  4440. * @param size defines the size of the texture
  4441. * @param options defines the options used to create the texture
  4442. * @returns a new render target cube texture stored in an InternalTexture
  4443. */
  4444. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  4445. let fullOptions = {
  4446. generateMipMaps: true,
  4447. generateDepthBuffer: true,
  4448. generateStencilBuffer: false,
  4449. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  4450. samplingMode: Texture.TRILINEAR_SAMPLINGMODE,
  4451. format: Engine.TEXTUREFORMAT_RGBA,
  4452. ...options
  4453. };
  4454. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  4455. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4456. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4457. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4458. }
  4459. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4460. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4461. fullOptions.samplingMode = Texture.NEAREST_SAMPLINGMODE;
  4462. }
  4463. var gl = this._gl
  4464. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4465. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4466. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  4467. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4468. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4469. Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  4470. }
  4471. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4472. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4473. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4474. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4475. for (var face = 0; face < 6; face++) {
  4476. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4477. }
  4478. // Create the framebuffer
  4479. var framebuffer = gl.createFramebuffer();
  4480. this.bindUnboundFramebuffer(framebuffer);
  4481. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  4482. // MipMaps
  4483. if (fullOptions.generateMipMaps) {
  4484. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4485. }
  4486. // Unbind
  4487. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4488. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4489. this.bindUnboundFramebuffer(null);
  4490. texture._framebuffer = framebuffer;
  4491. texture.width = size;
  4492. texture.height = size;
  4493. texture.isReady = true;
  4494. texture.isCube = true;
  4495. texture.samples = 1;
  4496. texture.generateMipMaps = fullOptions.generateMipMaps;
  4497. texture.samplingMode = fullOptions.samplingMode;
  4498. texture.type = fullOptions.type;
  4499. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4500. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  4501. this._internalTexturesCache.push(texture);
  4502. return texture;
  4503. }
  4504. /**
  4505. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  4506. * @param rootUrl defines the url where the file to load is located
  4507. * @param scene defines the current scene
  4508. * @param scale defines scale to apply to the mip map selection
  4509. * @param offset defines offset to apply to the mip map selection
  4510. * @param onLoad defines an optional callback raised when the texture is loaded
  4511. * @param onError defines an optional callback raised if there is an issue to load the texture
  4512. * @param format defines the format of the data
  4513. * @param forcedExtension defines the extension to use to pick the right loader
  4514. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  4515. * @returns the cube texture as an InternalTexture
  4516. */
  4517. public createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, scale: number, offset: number,
  4518. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  4519. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null,
  4520. createPolynomials: boolean = true): InternalTexture {
  4521. var callback = (loadData: any) => {
  4522. if (!loadData) {
  4523. if (onLoad) {
  4524. onLoad(null);
  4525. }
  4526. return;
  4527. }
  4528. let texture = loadData.texture as InternalTexture;
  4529. if (!createPolynomials) {
  4530. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  4531. }
  4532. else if(loadData.info.sphericalPolynomial){
  4533. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  4534. }
  4535. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  4536. texture._lodGenerationScale = scale;
  4537. texture._lodGenerationOffset = offset;
  4538. if (this._caps.textureLOD) {
  4539. // Do not add extra process if texture lod is supported.
  4540. if (onLoad) {
  4541. onLoad(texture);
  4542. }
  4543. return;
  4544. }
  4545. const mipSlices = 3;
  4546. var gl = this._gl;
  4547. const width = loadData.width;
  4548. if (!width) {
  4549. return;
  4550. }
  4551. const textures: BaseTexture[] = [];
  4552. for (let i = 0; i < mipSlices; i++) {
  4553. //compute LOD from even spacing in smoothness (matching shader calculation)
  4554. let smoothness = i / (mipSlices - 1);
  4555. let roughness = 1 - smoothness;
  4556. let minLODIndex = offset; // roughness = 0
  4557. let maxLODIndex = Scalar.Log2(width) * scale + offset; // roughness = 1
  4558. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  4559. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  4560. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  4561. glTextureFromLod.isCube = true;
  4562. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  4563. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4564. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  4565. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4566. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4567. if (loadData.isDDS) {
  4568. var info: DDSInfo = loadData.info;
  4569. var data: any = loadData.data;
  4570. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  4571. DDSTools.UploadDDSLevels(this, this._gl, data, info, true, 6, mipmapIndex);
  4572. }
  4573. else {
  4574. Tools.Warn("DDS is the only prefiltered cube map supported so far.")
  4575. }
  4576. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4577. // Wrap in a base texture for easy binding.
  4578. const lodTexture = new BaseTexture(scene);
  4579. lodTexture.isCube = true;
  4580. lodTexture._texture = glTextureFromLod;
  4581. glTextureFromLod.isReady = true;
  4582. textures.push(lodTexture);
  4583. }
  4584. texture._lodTextureHigh = textures[2];
  4585. texture._lodTextureMid = textures[1];
  4586. texture._lodTextureLow = textures[0];
  4587. if (onLoad) {
  4588. onLoad(texture);
  4589. }
  4590. };
  4591. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials);
  4592. }
  4593. /**
  4594. * Creates a cube texture
  4595. * @param rootUrl defines the url where the files to load is located
  4596. * @param scene defines the current scene
  4597. * @param files defines the list of files to load (1 per face)
  4598. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  4599. * @param onLoad defines an optional callback raised when the texture is loaded
  4600. * @param onError defines an optional callback raised if there is an issue to load the texture
  4601. * @param format defines the format of the data
  4602. * @param forcedExtension defines the extension to use to pick the right loader
  4603. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  4604. * @returns the cube texture as an InternalTexture
  4605. */
  4606. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null, onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null, createPolynomials = false): InternalTexture {
  4607. var gl = this._gl;
  4608. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  4609. texture.isCube = true;
  4610. texture.url = rootUrl;
  4611. texture.generateMipMaps = !noMipmap;
  4612. if (!this._doNotHandleContextLost) {
  4613. texture._extension = forcedExtension;
  4614. texture._files = files;
  4615. }
  4616. var isKTX = false;
  4617. var isDDS = false;
  4618. var lastDot = rootUrl.lastIndexOf('.');
  4619. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  4620. if (this._textureFormatInUse) {
  4621. extension = this._textureFormatInUse;
  4622. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  4623. isKTX = true;
  4624. } else {
  4625. isDDS = (extension === ".dds");
  4626. }
  4627. let onerror = (request?: XMLHttpRequest, exception?: any) => {
  4628. if (onError && request) {
  4629. onError(request.status + " " + request.statusText, exception);
  4630. }
  4631. }
  4632. if (isKTX) {
  4633. this._loadFile(rootUrl, data => {
  4634. var ktx = new KhronosTextureContainer(data, 6);
  4635. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  4636. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4637. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4638. ktx.uploadLevels(this._gl, !noMipmap);
  4639. this.setCubeMapTextureParams(gl, loadMipmap);
  4640. texture.width = ktx.pixelWidth;
  4641. texture.height = ktx.pixelHeight;
  4642. texture.isReady = true;
  4643. }, undefined, undefined, true, onerror);
  4644. } else if (isDDS) {
  4645. if (files && files.length === 6) {
  4646. this._cascadeLoadFiles(
  4647. scene,
  4648. imgs => {
  4649. var info: DDSInfo | undefined;
  4650. var loadMipmap: boolean = false;
  4651. var width: number = 0;
  4652. for (let index = 0; index < imgs.length; index++) {
  4653. let data = imgs[index];
  4654. info = DDSTools.GetDDSInfo(data);
  4655. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4656. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4657. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  4658. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6, -1, index);
  4659. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4660. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4661. }
  4662. texture.width = info.width;
  4663. texture.height = info.height;
  4664. texture.type = info.textureType;
  4665. width = info.width;
  4666. }
  4667. this.setCubeMapTextureParams(gl, loadMipmap);
  4668. texture.isReady = true;
  4669. if (onLoad) {
  4670. onLoad({ isDDS: true, width: width, info, imgs, texture });
  4671. }
  4672. },
  4673. files,
  4674. onError);
  4675. } else {
  4676. this._loadFile(rootUrl,
  4677. data => {
  4678. var info = DDSTools.GetDDSInfo(data);
  4679. if(createPolynomials){
  4680. info.sphericalPolynomial = new SphericalPolynomial();
  4681. }
  4682. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4683. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4684. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  4685. DDSTools.UploadDDSLevels(this, this._gl, data, info, loadMipmap, 6);
  4686. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4687. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4688. }
  4689. this.setCubeMapTextureParams(gl, loadMipmap);
  4690. texture.width = info.width;
  4691. texture.height = info.height;
  4692. texture.isReady = true;
  4693. texture.type = info.textureType;
  4694. if (onLoad) {
  4695. onLoad({ isDDS: true, width: info.width, info, data, texture });
  4696. }
  4697. },
  4698. undefined,
  4699. undefined,
  4700. true,
  4701. onerror);
  4702. }
  4703. } else {
  4704. if (!files) {
  4705. throw new Error("Cannot load cubemap because files were not defined");
  4706. }
  4707. cascadeLoadImgs(rootUrl, scene, imgs => {
  4708. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  4709. var height = width;
  4710. this._prepareWorkingCanvas();
  4711. if (!this._workingCanvas || !this._workingContext) {
  4712. return;
  4713. }
  4714. this._workingCanvas.width = width;
  4715. this._workingCanvas.height = height;
  4716. var faces = [
  4717. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4718. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4719. ];
  4720. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4721. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4722. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  4723. for (var index = 0; index < faces.length; index++) {
  4724. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4725. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  4726. }
  4727. if (!noMipmap) {
  4728. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4729. }
  4730. this.setCubeMapTextureParams(gl, !noMipmap);
  4731. texture.width = width;
  4732. texture.height = height;
  4733. texture.isReady = true;
  4734. if (format) {
  4735. texture.format = format;
  4736. }
  4737. texture.onLoadedObservable.notifyObservers(texture);
  4738. texture.onLoadedObservable.clear();
  4739. if (onLoad) {
  4740. onLoad();
  4741. }
  4742. }, files, onError);
  4743. }
  4744. this._internalTexturesCache.push(texture);
  4745. return texture;
  4746. }
  4747. private setCubeMapTextureParams(gl: WebGLRenderingContext, loadMipmap: boolean) {
  4748. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4750. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4751. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4752. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4753. // this.resetTextureCache();
  4754. }
  4755. /**
  4756. * Update a raw cube texture
  4757. * @param texture defines the texture to udpdate
  4758. * @param data defines the data to store
  4759. * @param format defines the data format
  4760. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  4761. * @param invertY defines if data must be stored with Y axis inverted
  4762. * @param compression defines the compression used (null by default)
  4763. * @param level defines which level of the texture to update
  4764. */
  4765. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  4766. texture._bufferViewArray = data;
  4767. texture.format = format;
  4768. texture.type = type;
  4769. texture.invertY = invertY;
  4770. texture._compression = compression;
  4771. var gl = this._gl;
  4772. var textureType = this._getWebGLTextureType(type);
  4773. var internalFormat = this._getInternalFormat(format);
  4774. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4775. var needConversion = false;
  4776. if (internalFormat === gl.RGB) {
  4777. internalFormat = gl.RGBA;
  4778. needConversion = true;
  4779. }
  4780. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4781. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4782. if (texture.width % 4 !== 0) {
  4783. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  4784. }
  4785. // Data are known to be in +X +Y +Z -X -Y -Z
  4786. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  4787. let faceData = data[faceIndex];
  4788. if (compression) {
  4789. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, <DataView>faceData);
  4790. } else {
  4791. if (needConversion) {
  4792. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  4793. }
  4794. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  4795. }
  4796. }
  4797. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4798. if (isPot && texture.generateMipMaps && level === 0) {
  4799. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4800. }
  4801. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4802. // this.resetTextureCache();
  4803. texture.isReady = true;
  4804. }
  4805. /**
  4806. * Creates a new raw cube texture
  4807. * @param data defines the array of data to use to create each face
  4808. * @param size defines the size of the textures
  4809. * @param format defines the format of the data
  4810. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4811. * @param generateMipMaps defines if the engine should generate the mip levels
  4812. * @param invertY defines if data must be stored with Y axis inverted
  4813. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4814. * @param compression defines the compression used (null by default)
  4815. * @returns the cube texture as an InternalTexture
  4816. */
  4817. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  4818. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  4819. compression: Nullable<string> = null): InternalTexture {
  4820. var gl = this._gl;
  4821. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  4822. texture.isCube = true;
  4823. texture.generateMipMaps = generateMipMaps;
  4824. texture.format = format;
  4825. texture.type = type;
  4826. if (!this._doNotHandleContextLost) {
  4827. texture._bufferViewArray = data;
  4828. }
  4829. var textureType = this._getWebGLTextureType(type);
  4830. var internalFormat = this._getInternalFormat(format);
  4831. if (internalFormat === gl.RGB) {
  4832. internalFormat = gl.RGBA;
  4833. }
  4834. var width = size;
  4835. var height = width;
  4836. texture.width = width;
  4837. texture.height = height;
  4838. // Double check on POT to generate Mips.
  4839. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4840. if (!isPot) {
  4841. generateMipMaps = false;
  4842. }
  4843. // Upload data if needed. The texture won't be ready until then.
  4844. if (data) {
  4845. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  4846. }
  4847. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  4848. // Filters
  4849. if (data && generateMipMaps) {
  4850. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4851. }
  4852. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  4853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4855. }
  4856. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  4857. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4859. }
  4860. else {
  4861. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4862. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4863. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4864. }
  4865. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4866. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4867. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4868. return texture;
  4869. }
  4870. /**
  4871. * Creates a new raw cube texture from a specified url
  4872. * @param url defines the url where the data is located
  4873. * @param scene defines the current scene
  4874. * @param size defines the size of the textures
  4875. * @param format defines the format of the data
  4876. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4877. * @param noMipmap defines if the engine should avoid generating the mip levels
  4878. * @param callback defines a callback used to extract texture data from loaded data
  4879. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  4880. * @param onLoad defines a callback called when texture is loaded
  4881. * @param onError defines a callback called if there is an error
  4882. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4883. * @param invertY defines if data must be stored with Y axis inverted
  4884. * @returns the cube texture as an InternalTexture
  4885. */
  4886. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  4887. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  4888. mipmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  4889. onLoad: Nullable<() => void> = null,
  4890. onError: Nullable<(message?: string, exception?: any) => void> = null,
  4891. samplingMode = Texture.TRILINEAR_SAMPLINGMODE,
  4892. invertY = false): InternalTexture {
  4893. var gl = this._gl;
  4894. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  4895. scene._addPendingData(texture);
  4896. texture.url = url;
  4897. this._internalTexturesCache.push(texture);
  4898. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  4899. scene._removePendingData(texture);
  4900. if (onError && request) {
  4901. onError(request.status + " " + request.statusText, exception);
  4902. }
  4903. };
  4904. var internalCallback = (data: any) => {
  4905. var width = texture.width;
  4906. var faceDataArrays = callback(data);
  4907. if (!faceDataArrays) {
  4908. return;
  4909. }
  4910. if (mipmapGenerator) {
  4911. var textureType = this._getWebGLTextureType(type);
  4912. var internalFormat = this._getInternalFormat(format);
  4913. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4914. var needConversion = false;
  4915. if (internalFormat === gl.RGB) {
  4916. internalFormat = gl.RGBA;
  4917. needConversion = true;
  4918. }
  4919. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4920. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4921. var mipData = mipmapGenerator(faceDataArrays);
  4922. for (var level = 0; level < mipData.length; level++) {
  4923. var mipSize = width >> level;
  4924. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  4925. let mipFaceData = mipData[level][faceIndex];
  4926. if (needConversion) {
  4927. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  4928. }
  4929. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  4930. }
  4931. }
  4932. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4933. }
  4934. else {
  4935. texture.generateMipMaps = !noMipmap;
  4936. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  4937. }
  4938. texture.isReady = true;
  4939. // this.resetTextureCache();
  4940. scene._removePendingData(texture);
  4941. if (onLoad) {
  4942. onLoad();
  4943. }
  4944. };
  4945. this._loadFile(url, data => {
  4946. internalCallback(data);
  4947. }, undefined, scene.database, true, onerror);
  4948. return texture;
  4949. };
  4950. /**
  4951. * Update a raw 3D texture
  4952. * @param texture defines the texture to update
  4953. * @param data defines the data to store
  4954. * @param format defines the data format
  4955. * @param invertY defines if data must be stored with Y axis inverted
  4956. * @param compression defines the used compression (can be null)
  4957. */
  4958. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null): void {
  4959. var internalFormat = this._getInternalFormat(format);
  4960. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  4961. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4962. if (!this._doNotHandleContextLost) {
  4963. texture._bufferView = data;
  4964. texture.format = format;
  4965. texture.invertY = invertY;
  4966. texture._compression = compression;
  4967. }
  4968. if (texture.width % 4 !== 0) {
  4969. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  4970. }
  4971. if (compression && data) {
  4972. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  4973. } else {
  4974. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4975. }
  4976. if (texture.generateMipMaps) {
  4977. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  4978. }
  4979. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  4980. // this.resetTextureCache();
  4981. texture.isReady = true;
  4982. }
  4983. /**
  4984. * Creates a new raw 3D texture
  4985. * @param data defines the data used to create the texture
  4986. * @param width defines the width of the texture
  4987. * @param height defines the height of the texture
  4988. * @param depth defines the depth of the texture
  4989. * @param format defines the format of the texture
  4990. * @param generateMipMaps defines if the engine must generate mip levels
  4991. * @param invertY defines if data must be stored with Y axis inverted
  4992. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4993. * @param compression defines the compressed used (can be null)
  4994. * @returns a new raw 3D texture (stored in an InternalTexture)
  4995. */
  4996. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null): InternalTexture {
  4997. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  4998. texture.baseWidth = width;
  4999. texture.baseHeight = height;
  5000. texture.baseDepth = depth;
  5001. texture.width = width;
  5002. texture.height = height;
  5003. texture.depth = depth;
  5004. texture.format = format;
  5005. texture.generateMipMaps = generateMipMaps;
  5006. texture.samplingMode = samplingMode;
  5007. texture.is3D = true;
  5008. if (!this._doNotHandleContextLost) {
  5009. texture._bufferView = data;
  5010. }
  5011. this.updateRawTexture3D(texture, data, format, invertY, compression);
  5012. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  5013. // Filters
  5014. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  5015. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5016. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5017. if (generateMipMaps) {
  5018. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  5019. }
  5020. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5021. this._internalTexturesCache.push(texture);
  5022. return texture;
  5023. }
  5024. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  5025. var gl = this._gl;
  5026. if (!gl) {
  5027. return;
  5028. }
  5029. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5030. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5031. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5032. if (!noMipmap && !isCompressed) {
  5033. gl.generateMipmap(gl.TEXTURE_2D);
  5034. }
  5035. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  5036. // this.resetTextureCache();
  5037. if (scene) {
  5038. scene._removePendingData(texture);
  5039. }
  5040. texture.onLoadedObservable.notifyObservers(texture);
  5041. texture.onLoadedObservable.clear();
  5042. }
  5043. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  5044. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Texture.TRILINEAR_SAMPLINGMODE): void {
  5045. var potWidth = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  5046. var potHeight = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  5047. var gl = this._gl;
  5048. if (!gl) {
  5049. return;
  5050. }
  5051. if (!texture._webGLTexture) {
  5052. // this.resetTextureCache();
  5053. if (scene) {
  5054. scene._removePendingData(texture);
  5055. }
  5056. return;
  5057. }
  5058. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  5059. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5060. texture.baseWidth = width;
  5061. texture.baseHeight = height;
  5062. texture.width = potWidth;
  5063. texture.height = potHeight;
  5064. texture.isReady = true;
  5065. if (processFunction(potWidth, potHeight, () => {
  5066. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5067. })) {
  5068. // Returning as texture needs extra async steps
  5069. return;
  5070. }
  5071. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5072. }
  5073. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  5074. // Create new RGBA data container.
  5075. var rgbaData: any;
  5076. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  5077. rgbaData = new Float32Array(width * height * 4);
  5078. }
  5079. else {
  5080. rgbaData = new Uint32Array(width * height * 4);
  5081. }
  5082. // Convert each pixel.
  5083. for (let x = 0; x < width; x++) {
  5084. for (let y = 0; y < height; y++) {
  5085. let index = (y * width + x) * 3;
  5086. let newIndex = (y * width + x) * 4;
  5087. // Map Old Value to new value.
  5088. rgbaData[newIndex + 0] = rgbData[index + 0];
  5089. rgbaData[newIndex + 1] = rgbData[index + 1];
  5090. rgbaData[newIndex + 2] = rgbData[index + 2];
  5091. // Add fully opaque alpha channel.
  5092. rgbaData[newIndex + 3] = 1;
  5093. }
  5094. }
  5095. return rgbaData;
  5096. }
  5097. /** @hidden */
  5098. public _releaseFramebufferObjects(texture: InternalTexture): void {
  5099. var gl = this._gl;
  5100. if (texture._framebuffer) {
  5101. gl.deleteFramebuffer(texture._framebuffer);
  5102. texture._framebuffer = null;
  5103. }
  5104. if (texture._depthStencilBuffer) {
  5105. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  5106. texture._depthStencilBuffer = null;
  5107. }
  5108. if (texture._MSAAFramebuffer) {
  5109. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  5110. texture._MSAAFramebuffer = null;
  5111. }
  5112. if (texture._MSAARenderBuffer) {
  5113. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  5114. texture._MSAARenderBuffer = null;
  5115. }
  5116. }
  5117. /** @hidden */
  5118. public _releaseTexture(texture: InternalTexture): void {
  5119. var gl = this._gl;
  5120. this._releaseFramebufferObjects(texture);
  5121. gl.deleteTexture(texture._webGLTexture);
  5122. // Unbind channels
  5123. this.unbindAllTextures();
  5124. var index = this._internalTexturesCache.indexOf(texture);
  5125. if (index !== -1) {
  5126. this._internalTexturesCache.splice(index, 1);
  5127. }
  5128. // Integrated fixed lod samplers.
  5129. if (texture._lodTextureHigh) {
  5130. texture._lodTextureHigh.dispose();
  5131. }
  5132. if (texture._lodTextureMid) {
  5133. texture._lodTextureMid.dispose();
  5134. }
  5135. if (texture._lodTextureLow) {
  5136. texture._lodTextureLow.dispose();
  5137. }
  5138. // Set output texture of post process to null if the texture has been released/disposed
  5139. this.scenes.forEach((scene)=>{
  5140. scene.postProcesses.forEach((postProcess)=>{
  5141. if(postProcess._outputTexture == texture){
  5142. postProcess._outputTexture = null;
  5143. }
  5144. });
  5145. scene.cameras.forEach((camera)=>{
  5146. camera._postProcesses.forEach((postProcess)=>{
  5147. if(postProcess){
  5148. if(postProcess._outputTexture == texture){
  5149. postProcess._outputTexture = null;
  5150. }
  5151. }
  5152. });
  5153. });
  5154. })
  5155. }
  5156. private setProgram(program: WebGLProgram): void {
  5157. if (this._currentProgram !== program) {
  5158. this._gl.useProgram(program);
  5159. this._currentProgram = program;
  5160. }
  5161. }
  5162. private _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  5163. /**
  5164. * Binds an effect to the webGL context
  5165. * @param effect defines the effect to bind
  5166. */
  5167. public bindSamplers(effect: Effect): void {
  5168. this.setProgram(effect.getProgram());
  5169. var samplers = effect.getSamplers();
  5170. for (var index = 0; index < samplers.length; index++) {
  5171. var uniform = effect.getUniform(samplers[index]);
  5172. if (uniform) {
  5173. this._boundUniforms[index] = uniform;
  5174. }
  5175. }
  5176. this._currentEffect = null;
  5177. }
  5178. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  5179. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  5180. return;
  5181. }
  5182. // Remove
  5183. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5184. // Bind last to it
  5185. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  5186. // Bind to dummy
  5187. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  5188. }
  5189. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  5190. if (!internalTexture) {
  5191. return -1;
  5192. }
  5193. internalTexture._initialSlot = channel;
  5194. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  5195. if (channel !== internalTexture._designatedSlot) {
  5196. this._textureCollisions.addCount(1, false);
  5197. }
  5198. } else {
  5199. if (channel !== internalTexture._designatedSlot) {
  5200. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  5201. return internalTexture._designatedSlot;
  5202. } else {
  5203. // No slot for this texture, let's pick a new one (if we find a free slot)
  5204. if (this._nextFreeTextureSlots.length) {
  5205. return this._nextFreeTextureSlots[0];
  5206. }
  5207. // We need to recycle the oldest bound texture, sorry.
  5208. this._textureCollisions.addCount(1, false);
  5209. return this._removeDesignatedSlot(<InternalTexture>this._firstBoundInternalTextureTracker.next);
  5210. }
  5211. }
  5212. }
  5213. return channel;
  5214. }
  5215. private _linkTrackers(previous: Nullable<IInternalTextureTracker>, next: Nullable<IInternalTextureTracker>) {
  5216. previous!.next = next;
  5217. next!.previous = previous;
  5218. }
  5219. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  5220. let currentSlot = internalTexture._designatedSlot;
  5221. if (currentSlot === -1) {
  5222. return -1;
  5223. }
  5224. internalTexture._designatedSlot = -1;
  5225. if (this.disableTextureBindingOptimization) {
  5226. return -1;
  5227. }
  5228. // Remove from bound list
  5229. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5230. // Free the slot
  5231. this._boundTexturesCache[currentSlot] = null;
  5232. this._nextFreeTextureSlots.push(currentSlot);
  5233. return currentSlot;
  5234. }
  5235. private _activateCurrentTexture() {
  5236. if (this._currentTextureChannel !== this._activeChannel) {
  5237. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  5238. this._currentTextureChannel = this._activeChannel;
  5239. }
  5240. }
  5241. /** @hidden */
  5242. protected _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): void {
  5243. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  5244. this._activeChannel = texture._designatedSlot;
  5245. }
  5246. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  5247. let isTextureForRendering = texture && texture._initialSlot > -1;
  5248. if (currentTextureBound !== texture || force) {
  5249. if (currentTextureBound) {
  5250. this._removeDesignatedSlot(currentTextureBound);
  5251. }
  5252. this._activateCurrentTexture();
  5253. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  5254. this._boundTexturesCache[this._activeChannel] = texture;
  5255. if (texture) {
  5256. if (!this.disableTextureBindingOptimization) {
  5257. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  5258. if (slotIndex > -1) {
  5259. this._nextFreeTextureSlots.splice(slotIndex, 1);
  5260. }
  5261. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  5262. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  5263. }
  5264. texture._designatedSlot = this._activeChannel;
  5265. }
  5266. } else if (forTextureDataUpdate) {
  5267. this._activateCurrentTexture();
  5268. }
  5269. if (isTextureForRendering && !forTextureDataUpdate) {
  5270. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  5271. }
  5272. }
  5273. /** @hidden */
  5274. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  5275. if (channel < 0) {
  5276. return;
  5277. }
  5278. if (texture) {
  5279. channel = this._getCorrectTextureChannel(channel, texture);
  5280. }
  5281. this._activeChannel = channel;
  5282. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  5283. }
  5284. /**
  5285. * Sets a texture to the webGL context from a postprocess
  5286. * @param channel defines the channel to use
  5287. * @param postProcess defines the source postprocess
  5288. */
  5289. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  5290. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  5291. }
  5292. /**
  5293. * Binds the output of the passed in post process to the texture channel specified
  5294. * @param channel The channel the texture should be bound to
  5295. * @param postProcess The post process which's output should be bound
  5296. */
  5297. public setTextureFromPostProcessOutput(channel: number, postProcess: Nullable<PostProcess>): void {
  5298. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  5299. }
  5300. /**
  5301. * Unbind all textures from the webGL context
  5302. */
  5303. public unbindAllTextures(): void {
  5304. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  5305. this._activeChannel = channel;
  5306. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5307. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5308. if (this.webGLVersion > 1) {
  5309. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5310. }
  5311. }
  5312. }
  5313. /**
  5314. * Sets a texture to the according uniform.
  5315. * @param channel The texture channel
  5316. * @param uniform The uniform to set
  5317. * @param texture The texture to apply
  5318. */
  5319. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  5320. if (channel < 0) {
  5321. return;
  5322. }
  5323. if (uniform) {
  5324. this._boundUniforms[channel] = uniform;
  5325. }
  5326. this._setTexture(channel, texture);
  5327. }
  5328. /**
  5329. * Sets a depth stencil texture from a render target to the according uniform.
  5330. * @param channel The texture channel
  5331. * @param uniform The uniform to set
  5332. * @param texture The render target texture containing the depth stencil texture to apply
  5333. */
  5334. public setDepthStencilTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<RenderTargetTexture>): void {
  5335. if (channel < 0) {
  5336. return;
  5337. }
  5338. if (uniform) {
  5339. this._boundUniforms[channel] = uniform;
  5340. }
  5341. if (!texture || !texture.depthStencilTexture) {
  5342. this._setTexture(channel, null);
  5343. }
  5344. else {
  5345. this._setTexture(channel, texture, false, true);
  5346. }
  5347. }
  5348. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  5349. let uniform = this._boundUniforms[sourceSlot];
  5350. if (uniform._currentState === destination) {
  5351. return;
  5352. }
  5353. this._gl.uniform1i(uniform, destination);
  5354. uniform._currentState = destination;
  5355. }
  5356. private _getTextureWrapMode(mode: number): number {
  5357. switch(mode) {
  5358. case Texture.WRAP_ADDRESSMODE:
  5359. return this._gl.REPEAT;
  5360. case Texture.CLAMP_ADDRESSMODE:
  5361. return this._gl.CLAMP_TO_EDGE;
  5362. case Texture.MIRROR_ADDRESSMODE:
  5363. return this._gl.MIRRORED_REPEAT;
  5364. }
  5365. return this._gl.REPEAT;
  5366. }
  5367. private _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  5368. // Not ready?
  5369. if (!texture) {
  5370. if (this._boundTexturesCache[channel] != null) {
  5371. this._activeChannel = channel;
  5372. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5373. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5374. if (this.webGLVersion > 1) {
  5375. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5376. }
  5377. }
  5378. return false;
  5379. }
  5380. // Video
  5381. if ((<VideoTexture>texture).video) {
  5382. this._activeChannel = channel;
  5383. (<VideoTexture>texture).update();
  5384. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  5385. texture.delayLoad();
  5386. return false;
  5387. }
  5388. let internalTexture: InternalTexture;
  5389. if (depthStencilTexture) {
  5390. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  5391. }
  5392. else if (texture.isReady()) {
  5393. internalTexture = <InternalTexture>texture.getInternalTexture();
  5394. }
  5395. else if (texture.isCube) {
  5396. internalTexture = this.emptyCubeTexture;
  5397. }
  5398. else if (texture.is3D) {
  5399. internalTexture = this.emptyTexture3D;
  5400. }
  5401. else {
  5402. internalTexture = this.emptyTexture;
  5403. }
  5404. if (!isPartOfTextureArray) {
  5405. channel = this._getCorrectTextureChannel(channel, internalTexture);
  5406. }
  5407. let needToBind = true;
  5408. if (this._boundTexturesCache[channel] === internalTexture) {
  5409. this._moveBoundTextureOnTop(internalTexture);
  5410. if (!isPartOfTextureArray) {
  5411. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  5412. }
  5413. needToBind = false;
  5414. }
  5415. this._activeChannel = channel;
  5416. if (internalTexture && internalTexture.is3D) {
  5417. if (needToBind) {
  5418. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  5419. }
  5420. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5421. internalTexture._cachedWrapU = texture.wrapU;
  5422. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5423. }
  5424. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5425. internalTexture._cachedWrapV = texture.wrapV;
  5426. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5427. }
  5428. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  5429. internalTexture._cachedWrapR = texture.wrapR;
  5430. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  5431. }
  5432. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  5433. }
  5434. else if (internalTexture && internalTexture.isCube) {
  5435. if (needToBind) {
  5436. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  5437. }
  5438. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5439. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5440. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5441. var textureWrapMode = (texture.coordinatesMode !== Texture.CUBIC_MODE && texture.coordinatesMode !== Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5442. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  5443. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5444. }
  5445. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5446. } else {
  5447. if (needToBind) {
  5448. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  5449. }
  5450. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5451. internalTexture._cachedWrapU = texture.wrapU;
  5452. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5453. }
  5454. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5455. internalTexture._cachedWrapV = texture.wrapV;
  5456. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5457. }
  5458. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5459. }
  5460. return true;
  5461. }
  5462. /**
  5463. * Sets an array of texture to the webGL context
  5464. * @param channel defines the channel where the texture array must be set
  5465. * @param uniform defines the associated uniform location
  5466. * @param textures defines the array of textures to bind
  5467. */
  5468. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  5469. if (channel < 0 || !uniform) {
  5470. return;
  5471. }
  5472. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  5473. this._textureUnits = new Int32Array(textures.length);
  5474. }
  5475. for (let i = 0; i < textures.length; i++) {
  5476. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  5477. }
  5478. this._gl.uniform1iv(uniform, this._textureUnits);
  5479. for (var index = 0; index < textures.length; index++) {
  5480. this._setTexture(this._textureUnits[index], textures[index], true);
  5481. }
  5482. }
  5483. /** @hidden */
  5484. public _setAnisotropicLevel(target: number, texture: BaseTexture) {
  5485. var internalTexture = texture.getInternalTexture();
  5486. if (!internalTexture) {
  5487. return;
  5488. }
  5489. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5490. var value = texture.anisotropicFilteringLevel;
  5491. if (internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPNEAREST
  5492. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR_MIPLINEAR
  5493. && internalTexture.samplingMode !== Texture.LINEAR_LINEAR) {
  5494. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  5495. }
  5496. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  5497. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  5498. internalTexture._cachedAnisotropicFilteringLevel = value;
  5499. }
  5500. }
  5501. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  5502. this._bindTextureDirectly(target, texture, true, true);
  5503. this._gl.texParameterf(target, parameter, value);
  5504. }
  5505. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  5506. if (texture) {
  5507. this._bindTextureDirectly(target, texture, true, true);
  5508. }
  5509. this._gl.texParameteri(target, parameter, value);
  5510. }
  5511. /**
  5512. * Reads pixels from the current frame buffer. Please note that this function can be slow
  5513. * @param x defines the x coordinate of the rectangle where pixels must be read
  5514. * @param y defines the y coordinate of the rectangle where pixels must be read
  5515. * @param width defines the width of the rectangle where pixels must be read
  5516. * @param height defines the height of the rectangle where pixels must be read
  5517. * @returns a Uint8Array containing RGBA colors
  5518. */
  5519. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  5520. var data = new Uint8Array(height * width * 4);
  5521. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5522. return data;
  5523. }
  5524. /**
  5525. * Add an externaly attached data from its key.
  5526. * This method call will fail and return false, if such key already exists.
  5527. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  5528. * @param key the unique key that identifies the data
  5529. * @param data the data object to associate to the key for this Engine instance
  5530. * @return true if no such key were already present and the data was added successfully, false otherwise
  5531. */
  5532. public addExternalData<T>(key: string, data: T): boolean {
  5533. if (!this._externalData) {
  5534. this._externalData = new StringDictionary<Object>();
  5535. }
  5536. return this._externalData.add(key, data);
  5537. }
  5538. /**
  5539. * Get an externaly attached data from its key
  5540. * @param key the unique key that identifies the data
  5541. * @return the associated data, if present (can be null), or undefined if not present
  5542. */
  5543. public getExternalData<T>(key: string): T {
  5544. if (!this._externalData) {
  5545. this._externalData = new StringDictionary<Object>();
  5546. }
  5547. return <T>this._externalData.get(key);
  5548. }
  5549. /**
  5550. * Get an externaly attached data from its key, create it using a factory if it's not already present
  5551. * @param key the unique key that identifies the data
  5552. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  5553. * @return the associated data, can be null if the factory returned null.
  5554. */
  5555. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  5556. if (!this._externalData) {
  5557. this._externalData = new StringDictionary<Object>();
  5558. }
  5559. return <T>this._externalData.getOrAddWithFactory(key, factory);
  5560. }
  5561. /**
  5562. * Remove an externaly attached data from the Engine instance
  5563. * @param key the unique key that identifies the data
  5564. * @return true if the data was successfully removed, false if it doesn't exist
  5565. */
  5566. public removeExternalData(key: string): boolean {
  5567. if (!this._externalData) {
  5568. this._externalData = new StringDictionary<Object>();
  5569. }
  5570. return this._externalData.remove(key);
  5571. }
  5572. /**
  5573. * Unbind all vertex attributes from the webGL context
  5574. */
  5575. public unbindAllAttributes() {
  5576. if (this._mustWipeVertexAttributes) {
  5577. this._mustWipeVertexAttributes = false;
  5578. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  5579. this._gl.disableVertexAttribArray(i);
  5580. this._vertexAttribArraysEnabled[i] = false;
  5581. this._currentBufferPointers[i].active = false;
  5582. }
  5583. return;
  5584. }
  5585. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  5586. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  5587. continue;
  5588. }
  5589. this._gl.disableVertexAttribArray(i);
  5590. this._vertexAttribArraysEnabled[i] = false;
  5591. this._currentBufferPointers[i].active = false;
  5592. }
  5593. }
  5594. /**
  5595. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  5596. */
  5597. public releaseEffects() {
  5598. for (var name in this._compiledEffects) {
  5599. this._deleteProgram(this._compiledEffects[name]._program)
  5600. }
  5601. this._compiledEffects = {};
  5602. }
  5603. /**
  5604. * Dispose and release all associated resources
  5605. */
  5606. public dispose(): void {
  5607. this.hideLoadingUI();
  5608. this.stopRenderLoop();
  5609. // Release postProcesses
  5610. while (this.postProcesses.length) {
  5611. this.postProcesses[0].dispose();
  5612. }
  5613. // Empty texture
  5614. if (this._emptyTexture) {
  5615. this._releaseTexture(this._emptyTexture);
  5616. this._emptyTexture = null;
  5617. }
  5618. if (this._emptyCubeTexture) {
  5619. this._releaseTexture(this._emptyCubeTexture);
  5620. this._emptyCubeTexture = null;
  5621. }
  5622. // Rescale PP
  5623. if (this._rescalePostProcess) {
  5624. this._rescalePostProcess.dispose();
  5625. }
  5626. // Release scenes
  5627. while (this.scenes.length) {
  5628. this.scenes[0].dispose();
  5629. }
  5630. // Release audio engine
  5631. if (Engine.audioEngine) {
  5632. Engine.audioEngine.dispose();
  5633. }
  5634. // Release effects
  5635. this.releaseEffects();
  5636. // Unbind
  5637. this.unbindAllAttributes();
  5638. this._boundUniforms = [];
  5639. if (this._dummyFramebuffer) {
  5640. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  5641. }
  5642. //WebVR
  5643. this.disableVR();
  5644. // Events
  5645. if (Tools.IsWindowObjectExist()) {
  5646. window.removeEventListener("blur", this._onBlur);
  5647. window.removeEventListener("focus", this._onFocus);
  5648. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  5649. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  5650. if (this._renderingCanvas) {
  5651. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  5652. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  5653. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  5654. if (!this._doNotHandleContextLost) {
  5655. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  5656. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  5657. }
  5658. }
  5659. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5660. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5661. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5662. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5663. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5664. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5665. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5666. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5667. if (this._onVrDisplayConnect) {
  5668. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  5669. if (this._onVrDisplayDisconnect) {
  5670. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  5671. }
  5672. if (this._onVrDisplayPresentChange) {
  5673. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  5674. }
  5675. this._onVrDisplayConnect = null;
  5676. this._onVrDisplayDisconnect = null;
  5677. }
  5678. }
  5679. // Remove from Instances
  5680. var index = Engine.Instances.indexOf(this);
  5681. if (index >= 0) {
  5682. Engine.Instances.splice(index, 1);
  5683. }
  5684. this._workingCanvas = null;
  5685. this._workingContext = null;
  5686. this._currentBufferPointers = [];
  5687. this._renderingCanvas = null;
  5688. this._currentProgram = null;
  5689. this._bindedRenderFunction = null;
  5690. this.onResizeObservable.clear();
  5691. this.onCanvasBlurObservable.clear();
  5692. this.onCanvasFocusObservable.clear();
  5693. this.onCanvasPointerOutObservable.clear();
  5694. this.onBeginFrameObservable.clear();
  5695. this.onEndFrameObservable.clear();
  5696. Effect.ResetCache();
  5697. // Abort active requests
  5698. for (let request of this._activeRequests) {
  5699. request.abort();
  5700. }
  5701. }
  5702. // Loading screen
  5703. /**
  5704. * Display the loading screen
  5705. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5706. */
  5707. public displayLoadingUI(): void {
  5708. if (!Tools.IsWindowObjectExist()) {
  5709. return;
  5710. }
  5711. const loadingScreen = this.loadingScreen;
  5712. if (loadingScreen) {
  5713. loadingScreen.displayLoadingUI();
  5714. }
  5715. }
  5716. /**
  5717. * Hide the loading screen
  5718. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5719. */
  5720. public hideLoadingUI(): void {
  5721. if (!Tools.IsWindowObjectExist()) {
  5722. return;
  5723. }
  5724. const loadingScreen = this.loadingScreen;
  5725. if (loadingScreen) {
  5726. loadingScreen.hideLoadingUI();
  5727. }
  5728. }
  5729. /**
  5730. * Gets the current loading screen object
  5731. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5732. */
  5733. public get loadingScreen(): ILoadingScreen {
  5734. if (!this._loadingScreen && DefaultLoadingScreen && this._renderingCanvas)
  5735. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas)
  5736. return this._loadingScreen;
  5737. }
  5738. /**
  5739. * Sets the current loading screen object
  5740. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5741. */
  5742. public set loadingScreen(loadingScreen: ILoadingScreen) {
  5743. this._loadingScreen = loadingScreen;
  5744. }
  5745. /**
  5746. * Sets the current loading screen text
  5747. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5748. */
  5749. public set loadingUIText(text: string) {
  5750. this.loadingScreen.loadingUIText = text;
  5751. }
  5752. /**
  5753. * Sets the current loading screen background color
  5754. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5755. */
  5756. public set loadingUIBackgroundColor(color: string) {
  5757. this.loadingScreen.loadingUIBackgroundColor = color;
  5758. }
  5759. /**
  5760. * Attach a new callback raised when context lost event is fired
  5761. * @param callback defines the callback to call
  5762. */
  5763. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5764. if (this._renderingCanvas) {
  5765. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  5766. }
  5767. }
  5768. /**
  5769. * Attach a new callback raised when context restored event is fired
  5770. * @param callback defines the callback to call
  5771. */
  5772. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5773. if (this._renderingCanvas) {
  5774. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  5775. }
  5776. }
  5777. /**
  5778. * Gets the source code of the vertex shader associated with a specific webGL program
  5779. * @param program defines the program to use
  5780. * @returns a string containing the source code of the vertex shader associated with the program
  5781. */
  5782. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  5783. var shaders = this._gl.getAttachedShaders(program);
  5784. if (!shaders) {
  5785. return null;
  5786. }
  5787. return this._gl.getShaderSource(shaders[0]);
  5788. }
  5789. /**
  5790. * Gets the source code of the fragment shader associated with a specific webGL program
  5791. * @param program defines the program to use
  5792. * @returns a string containing the source code of the fragment shader associated with the program
  5793. */
  5794. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  5795. var shaders = this._gl.getAttachedShaders(program);
  5796. if (!shaders) {
  5797. return null;
  5798. }
  5799. return this._gl.getShaderSource(shaders[1]);
  5800. }
  5801. /**
  5802. * Get the current error code of the webGL context
  5803. * @returns the error code
  5804. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  5805. */
  5806. public getError(): number {
  5807. return this._gl.getError();
  5808. }
  5809. // FPS
  5810. /**
  5811. * Gets the current framerate
  5812. * @returns a number representing the framerate
  5813. */
  5814. public getFps(): number {
  5815. return this._fps;
  5816. }
  5817. /**
  5818. * Gets the time spent between current and previous frame
  5819. * @returns a number representing the delta time in ms
  5820. */
  5821. public getDeltaTime(): number {
  5822. return this._deltaTime;
  5823. }
  5824. private _measureFps(): void {
  5825. this._performanceMonitor.sampleFrame();
  5826. this._fps = this._performanceMonitor.averageFPS;
  5827. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  5828. }
  5829. /** @hidden */
  5830. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1): ArrayBufferView {
  5831. let gl = this._gl;
  5832. if (!this._dummyFramebuffer) {
  5833. let dummy = gl.createFramebuffer();
  5834. if (!dummy) {
  5835. throw new Error("Unable to create dummy framebuffer");
  5836. }
  5837. this._dummyFramebuffer = dummy;
  5838. }
  5839. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  5840. if (faceIndex > -1) {
  5841. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  5842. } else {
  5843. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  5844. }
  5845. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  5846. let buffer: ArrayBufferView;
  5847. switch (readType) {
  5848. case gl.UNSIGNED_BYTE:
  5849. buffer = new Uint8Array(4 * width * height);
  5850. readType = gl.UNSIGNED_BYTE;
  5851. break;
  5852. default:
  5853. buffer = new Float32Array(4 * width * height);
  5854. readType = gl.FLOAT;
  5855. break;
  5856. }
  5857. gl.readPixels(0, 0, width, height, gl.RGBA, readType, <DataView>buffer);
  5858. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  5859. return buffer;
  5860. }
  5861. private _canRenderToFloatFramebuffer(): boolean {
  5862. if (this._webGLVersion > 1) {
  5863. return this._caps.colorBufferFloat;
  5864. }
  5865. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  5866. }
  5867. private _canRenderToHalfFloatFramebuffer(): boolean {
  5868. if (this._webGLVersion > 1) {
  5869. return this._caps.colorBufferFloat;
  5870. }
  5871. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  5872. }
  5873. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  5874. private _canRenderToFramebuffer(type: number): boolean {
  5875. let gl = this._gl;
  5876. //clear existing errors
  5877. while (gl.getError() !== gl.NO_ERROR) { }
  5878. let successful = true;
  5879. let texture = gl.createTexture();
  5880. gl.bindTexture(gl.TEXTURE_2D, texture);
  5881. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  5882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  5883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  5884. let fb = gl.createFramebuffer();
  5885. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  5886. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5887. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  5888. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  5889. successful = successful && (gl.getError() === gl.NO_ERROR);
  5890. //try render by clearing frame buffer's color buffer
  5891. if (successful) {
  5892. gl.clear(gl.COLOR_BUFFER_BIT);
  5893. successful = successful && (gl.getError() === gl.NO_ERROR);
  5894. }
  5895. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  5896. if (successful) {
  5897. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  5898. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5899. let readFormat = gl.RGBA;
  5900. let readType = gl.UNSIGNED_BYTE;
  5901. let buffer = new Uint8Array(4);
  5902. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  5903. successful = successful && (gl.getError() === gl.NO_ERROR);
  5904. }
  5905. //clean up
  5906. gl.deleteTexture(texture);
  5907. gl.deleteFramebuffer(fb);
  5908. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5909. //clear accumulated errors
  5910. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  5911. return successful;
  5912. }
  5913. /** @hidden */
  5914. public _getWebGLTextureType(type: number): number {
  5915. if (type === Engine.TEXTURETYPE_FLOAT) {
  5916. return this._gl.FLOAT;
  5917. }
  5918. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5919. // Add Half Float Constant.
  5920. return this._gl.HALF_FLOAT_OES;
  5921. }
  5922. return this._gl.UNSIGNED_BYTE;
  5923. };
  5924. private _getInternalFormat(format: number): number {
  5925. var internalFormat = this._gl.RGBA;
  5926. switch (format) {
  5927. case Engine.TEXTUREFORMAT_ALPHA:
  5928. internalFormat = this._gl.ALPHA;
  5929. break;
  5930. case Engine.TEXTUREFORMAT_LUMINANCE:
  5931. internalFormat = this._gl.LUMINANCE;
  5932. break;
  5933. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5934. internalFormat = this._gl.LUMINANCE_ALPHA;
  5935. break;
  5936. case Engine.TEXTUREFORMAT_RGB:
  5937. case Engine.TEXTUREFORMAT_RGB32F:
  5938. internalFormat = this._gl.RGB;
  5939. break;
  5940. case Engine.TEXTUREFORMAT_RGBA:
  5941. case Engine.TEXTUREFORMAT_RGBA32F:
  5942. internalFormat = this._gl.RGBA;
  5943. break;
  5944. case Engine.TEXTUREFORMAT_R32F:
  5945. internalFormat = this._gl.RED;
  5946. break;
  5947. case Engine.TEXTUREFORMAT_RG32F:
  5948. internalFormat = this._gl.RG;
  5949. break;
  5950. }
  5951. return internalFormat;
  5952. }
  5953. /** @hidden */
  5954. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  5955. if (this._webGLVersion === 1) {
  5956. if (format) {
  5957. switch(format) {
  5958. case Engine.TEXTUREFORMAT_LUMINANCE:
  5959. return this._gl.LUMINANCE;
  5960. }
  5961. }
  5962. return this._gl.RGBA;
  5963. }
  5964. if (type === Engine.TEXTURETYPE_FLOAT) {
  5965. if (format) {
  5966. switch(format) {
  5967. case Engine.TEXTUREFORMAT_R32F:
  5968. return this._gl.R32F;
  5969. case Engine.TEXTUREFORMAT_RG32F:
  5970. return this._gl.RG32F;
  5971. case Engine.TEXTUREFORMAT_RGB32F:
  5972. return this._gl.RGB32F;
  5973. }
  5974. }
  5975. return this._gl.RGBA32F;
  5976. }
  5977. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5978. return this._gl.RGBA16F;
  5979. }
  5980. if (format) {
  5981. switch(format) {
  5982. case Engine.TEXTUREFORMAT_LUMINANCE:
  5983. return this._gl.LUMINANCE;
  5984. case Engine.TEXTUREFORMAT_RGB:
  5985. return this._gl.RGB;
  5986. }
  5987. }
  5988. return this._gl.RGBA;
  5989. };
  5990. /** @hidden */
  5991. public _getRGBAMultiSampleBufferFormat(type: number): number {
  5992. if (type === Engine.TEXTURETYPE_FLOAT) {
  5993. return this._gl.RGBA32F;
  5994. }
  5995. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  5996. return this._gl.RGBA16F;
  5997. }
  5998. return this._gl.RGBA8;
  5999. };
  6000. /**
  6001. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  6002. * @return the new query
  6003. */
  6004. public createQuery(): WebGLQuery {
  6005. return this._gl.createQuery();
  6006. }
  6007. /**
  6008. * Delete and release a webGL query
  6009. * @param query defines the query to delete
  6010. * @return the current engine
  6011. */
  6012. public deleteQuery(query: WebGLQuery): Engine {
  6013. this._gl.deleteQuery(query);
  6014. return this;
  6015. }
  6016. /**
  6017. * Check if a given query has resolved and got its value
  6018. * @param query defines the query to check
  6019. * @returns true if the query got its value
  6020. */
  6021. public isQueryResultAvailable(query: WebGLQuery): boolean {
  6022. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE) as boolean;
  6023. }
  6024. /**
  6025. * Gets the value of a given query
  6026. * @param query defines the query to check
  6027. * @returns the value of the query
  6028. */
  6029. public getQueryResult(query: WebGLQuery): number {
  6030. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT) as number;
  6031. }
  6032. /**
  6033. * Initiates an occlusion query
  6034. * @param algorithmType defines the algorithm to use
  6035. * @param query defines the query to use
  6036. * @returns the current engine
  6037. * @see http://doc.babylonjs.com/features/occlusionquery
  6038. */
  6039. public beginOcclusionQuery(algorithmType: number, query: WebGLQuery): Engine {
  6040. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  6041. this._gl.beginQuery(glAlgorithm, query);
  6042. return this;
  6043. }
  6044. /**
  6045. * Ends an occlusion query
  6046. * @see http://doc.babylonjs.com/features/occlusionquery
  6047. * @param algorithmType defines the algorithm to use
  6048. * @returns the current engine
  6049. */
  6050. public endOcclusionQuery(algorithmType: number): Engine {
  6051. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  6052. this._gl.endQuery(glAlgorithm);
  6053. return this;
  6054. }
  6055. /* Time queries */
  6056. private _createTimeQuery(): WebGLQuery {
  6057. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  6058. if (timerQuery.createQueryEXT) {
  6059. return timerQuery.createQueryEXT();
  6060. }
  6061. return this.createQuery();
  6062. }
  6063. private _deleteTimeQuery(query: WebGLQuery): void {
  6064. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  6065. if (timerQuery.deleteQueryEXT) {
  6066. timerQuery.deleteQueryEXT(query);
  6067. return;
  6068. }
  6069. this.deleteQuery(query);
  6070. }
  6071. private _getTimeQueryResult(query: WebGLQuery): any {
  6072. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  6073. if (timerQuery.getQueryObjectEXT) {
  6074. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  6075. }
  6076. return this.getQueryResult(query);
  6077. }
  6078. private _getTimeQueryAvailability(query: WebGLQuery): any {
  6079. let timerQuery = <EXT_disjoint_timer_query>this._caps.timerQuery;
  6080. if (timerQuery.getQueryObjectEXT) {
  6081. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  6082. }
  6083. return this.isQueryResultAvailable(query);
  6084. }
  6085. private _currentNonTimestampToken: Nullable<_TimeToken>;
  6086. /**
  6087. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  6088. * Please note that only one query can be issued at a time
  6089. * @returns a time token used to track the time span
  6090. */
  6091. public startTimeQuery(): Nullable<_TimeToken> {
  6092. let timerQuery = this._caps.timerQuery;
  6093. if (!timerQuery) {
  6094. return null;
  6095. }
  6096. let token = new _TimeToken();
  6097. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  6098. if (this._caps.canUseTimestampForTimerQuery) {
  6099. token._startTimeQuery = this._createTimeQuery();
  6100. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  6101. } else {
  6102. if (this._currentNonTimestampToken) {
  6103. return this._currentNonTimestampToken;
  6104. }
  6105. token._timeElapsedQuery = this._createTimeQuery();
  6106. if (timerQuery.beginQueryEXT) {
  6107. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  6108. } else {
  6109. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  6110. }
  6111. this._currentNonTimestampToken = token;
  6112. }
  6113. return token;
  6114. }
  6115. /**
  6116. * Ends a time query
  6117. * @param token defines the token used to measure the time span
  6118. * @returns the time spent (in ns)
  6119. */
  6120. public endTimeQuery(token: _TimeToken): int {
  6121. let timerQuery = this._caps.timerQuery;
  6122. if (!timerQuery || !token) {
  6123. return -1;
  6124. }
  6125. if (this._caps.canUseTimestampForTimerQuery) {
  6126. if (!token._startTimeQuery) {
  6127. return -1;
  6128. }
  6129. if (!token._endTimeQuery) {
  6130. token._endTimeQuery = this._createTimeQuery();
  6131. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  6132. }
  6133. } else if (!token._timeElapsedQueryEnded) {
  6134. if (!token._timeElapsedQuery) {
  6135. return -1;
  6136. }
  6137. if (timerQuery.endQueryEXT) {
  6138. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  6139. } else {
  6140. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  6141. }
  6142. token._timeElapsedQueryEnded = true;
  6143. }
  6144. let disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  6145. let available: boolean = false;
  6146. if (token._endTimeQuery) {
  6147. available = this._getTimeQueryAvailability(token._endTimeQuery);
  6148. } else if (token._timeElapsedQuery) {
  6149. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  6150. }
  6151. if (available && !disjoint) {
  6152. let result = 0;
  6153. if (this._caps.canUseTimestampForTimerQuery) {
  6154. if (!token._startTimeQuery || !token._endTimeQuery) {
  6155. return -1;
  6156. }
  6157. let timeStart = this._getTimeQueryResult(token._startTimeQuery);
  6158. let timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  6159. result = timeEnd - timeStart;
  6160. this._deleteTimeQuery(token._startTimeQuery);
  6161. this._deleteTimeQuery(token._endTimeQuery);
  6162. token._startTimeQuery = null;
  6163. token._endTimeQuery = null;
  6164. } else {
  6165. if (!token._timeElapsedQuery) {
  6166. return -1;
  6167. }
  6168. result = this._getTimeQueryResult(token._timeElapsedQuery);
  6169. this._deleteTimeQuery(token._timeElapsedQuery);
  6170. token._timeElapsedQuery = null;
  6171. token._timeElapsedQueryEnded = false;
  6172. this._currentNonTimestampToken = null;
  6173. }
  6174. return result;
  6175. }
  6176. return -1;
  6177. }
  6178. private getGlAlgorithmType(algorithmType: number): number {
  6179. return algorithmType === AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  6180. }
  6181. // Transform feedback
  6182. /**
  6183. * Creates a webGL transform feedback object
  6184. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  6185. * @returns the webGL transform feedback object
  6186. */
  6187. public createTransformFeedback(): WebGLTransformFeedback {
  6188. return this._gl.createTransformFeedback();
  6189. }
  6190. /**
  6191. * Delete a webGL transform feedback object
  6192. * @param value defines the webGL transform feedback object to delete
  6193. */
  6194. public deleteTransformFeedback(value: WebGLTransformFeedback): void {
  6195. this._gl.deleteTransformFeedback(value);
  6196. }
  6197. /**
  6198. * Bind a webGL transform feedback object to the webgl context
  6199. * @param value defines the webGL transform feedback object to bind
  6200. */
  6201. public bindTransformFeedback(value: Nullable<WebGLTransformFeedback>): void {
  6202. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  6203. }
  6204. /**
  6205. * Begins a transform feedback operation
  6206. * @param usePoints defines if points or triangles must be used
  6207. */
  6208. public beginTransformFeedback(usePoints: boolean = true): void {
  6209. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  6210. }
  6211. /**
  6212. * Ends a transform feedback operation
  6213. */
  6214. public endTransformFeedback(): void {
  6215. this._gl.endTransformFeedback();
  6216. }
  6217. /**
  6218. * Specify the varyings to use with transform feedback
  6219. * @param program defines the associated webGL program
  6220. * @param value defines the list of strings representing the varying names
  6221. */
  6222. public setTranformFeedbackVaryings(program: WebGLProgram, value: string[]): void {
  6223. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  6224. }
  6225. /**
  6226. * Bind a webGL buffer for a transform feedback operation
  6227. * @param value defines the webGL buffer to bind
  6228. */
  6229. public bindTransformFeedbackBuffer(value: Nullable<WebGLBuffer>): void {
  6230. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  6231. }
  6232. /** @hidden */
  6233. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, database?: Database, useArrayBuffer?: boolean, onError?: (request?: XMLHttpRequest, exception?: any) => void): IFileRequest {
  6234. let request = Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  6235. this._activeRequests.push(request);
  6236. request.onCompleteObservable.add(request => {
  6237. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  6238. });
  6239. return request;
  6240. }
  6241. /** @hidden */
  6242. public _loadFileAsync(url: string, database?: Database, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  6243. return new Promise((resolve, reject) => {
  6244. this._loadFile(url, (data) => {
  6245. resolve(data);
  6246. }, undefined, database, useArrayBuffer, (request, exception) => {
  6247. reject(exception);
  6248. })
  6249. });
  6250. }
  6251. private _partialLoadFile(url: string, index: number, loadedFiles: (string | ArrayBuffer)[], scene: Nullable<Scene>, onfinish: (files: (string | ArrayBuffer)[]) => void, onErrorCallBack: Nullable<(message?: string, exception?: any) => void> = null): void {
  6252. var onload = (data: string | ArrayBuffer) => {
  6253. loadedFiles[index] = data;
  6254. (<any>loadedFiles)._internalCount++;
  6255. if ((<any>loadedFiles)._internalCount === 6) {
  6256. onfinish(loadedFiles);
  6257. }
  6258. };
  6259. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  6260. if (onErrorCallBack && request) {
  6261. onErrorCallBack(request.status + " " + request.statusText, exception);
  6262. }
  6263. };
  6264. this._loadFile(url, onload, undefined, undefined, true, onerror);
  6265. }
  6266. private _cascadeLoadFiles(scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  6267. var loadedFiles: (string | ArrayBuffer)[] = [];
  6268. (<any>loadedFiles)._internalCount = 0;
  6269. for (let index = 0; index < 6; index++) {
  6270. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  6271. }
  6272. }
  6273. // Statics
  6274. /**
  6275. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  6276. * @returns true if the engine can be created
  6277. * @ignorenaming
  6278. */
  6279. public static isSupported(): boolean {
  6280. try {
  6281. var tempcanvas = document.createElement("canvas");
  6282. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6283. return gl != null && !!window.WebGLRenderingContext;
  6284. } catch (e) {
  6285. return false;
  6286. }
  6287. }
  6288. }
  6289. }