engine.ts 258 KB

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