babylon.engine.ts 320 KB

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