babylon.engine.ts 330 KB

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