engine.ts 312 KB

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