engine.ts 267 KB

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