babylon.engine.ts 332 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573
  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.7";
  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. * Event raised when a new scene is created
  516. */
  517. public onNewSceneAddedObservable = new Observable<Scene>();
  518. /**
  519. * Gets the list of created postprocesses
  520. */
  521. public postProcesses = new Array<PostProcess>();
  522. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  523. public validateShaderPrograms = false;
  524. // Observables
  525. /**
  526. * Observable event triggered each time the rendering canvas is resized
  527. */
  528. public onResizeObservable = new Observable<Engine>();
  529. /**
  530. * Observable event triggered each time the canvas loses focus
  531. */
  532. public onCanvasBlurObservable = new Observable<Engine>();
  533. /**
  534. * Observable event triggered each time the canvas gains focus
  535. */
  536. public onCanvasFocusObservable = new Observable<Engine>();
  537. /**
  538. * Observable event triggered each time the canvas receives pointerout event
  539. */
  540. public onCanvasPointerOutObservable = new Observable<PointerEvent>();
  541. /**
  542. * Observable event triggered before each texture is initialized
  543. */
  544. public onBeforeTextureInitObservable = new Observable<Texture>();
  545. //WebVR
  546. private _vrDisplay: any = undefined;
  547. private _vrSupported: boolean = false;
  548. private _oldSize: Size;
  549. private _oldHardwareScaleFactor: number;
  550. private _vrExclusivePointerMode = false;
  551. private _webVRInitPromise: Promise<IDisplayChangedEventArgs>;
  552. /**
  553. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  554. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  555. */
  556. public get isInVRExclusivePointerMode(): boolean {
  557. return this._vrExclusivePointerMode;
  558. }
  559. // Uniform buffers list
  560. /**
  561. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  562. */
  563. public disableUniformBuffers = false;
  564. /** @hidden */
  565. public _uniformBuffers = new Array<UniformBuffer>();
  566. /**
  567. * Gets a boolean indicating that the engine supports uniform buffers
  568. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  569. */
  570. public get supportsUniformBuffers(): boolean {
  571. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  572. }
  573. // Observables
  574. /**
  575. * Observable raised when the engine begins a new frame
  576. */
  577. public onBeginFrameObservable = new Observable<Engine>();
  578. /**
  579. * If set, will be used to request the next animation frame for the render loop
  580. */
  581. public customAnimationFrameRequester: Nullable<ICustomAnimationFrameRequester> = null;
  582. /**
  583. * Observable raised when the engine ends the current frame
  584. */
  585. public onEndFrameObservable = new Observable<Engine>();
  586. /**
  587. * Observable raised when the engine is about to compile a shader
  588. */
  589. public onBeforeShaderCompilationObservable = new Observable<Engine>();
  590. /**
  591. * Observable raised when the engine has jsut compiled a shader
  592. */
  593. public onAfterShaderCompilationObservable = new Observable<Engine>();
  594. // Private Members
  595. /** @hidden */
  596. public _gl: WebGLRenderingContext;
  597. private _renderingCanvas: Nullable<HTMLCanvasElement>;
  598. private _windowIsBackground = false;
  599. private _webGLVersion = 1.0;
  600. /**
  601. * Gets a boolean indicating that only power of 2 textures are supported
  602. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  603. */
  604. public get needPOTTextures(): boolean {
  605. return this._webGLVersion < 2 || this.forcePOTTextures;
  606. }
  607. /** @hidden */
  608. public _badOS = false;
  609. /** @hidden */
  610. public _badDesktopOS = false;
  611. /**
  612. * Gets or sets a value indicating if we want to disable texture binding optimization.
  613. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  614. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  615. */
  616. public disableTextureBindingOptimization = false;
  617. /**
  618. * Gets the audio engine
  619. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  620. * @ignorenaming
  621. */
  622. public static audioEngine: IAudioEngine;
  623. /**
  624. * Default AudioEngine factory responsible of creating the Audio Engine.
  625. * By default, this will create a BabylonJS Audio Engine if the workload has been embedded.
  626. */
  627. public static AudioEngineFactory: (hostElement: Nullable<HTMLElement>) => IAudioEngine;
  628. /**
  629. * Default offline support factory responsible of creating a tool used to store data locally.
  630. * By default, this will create a Database object if the workload has been embedded.
  631. */
  632. public static OfflineProviderFactory: (urlToScene: string, callbackManifestChecked: (checked: boolean) => any, disableManifestCheck: boolean) => IOfflineProvider;
  633. // Focus
  634. private _onFocus: () => void;
  635. private _onBlur: () => void;
  636. private _onCanvasPointerOut: (event: PointerEvent) => void;
  637. private _onCanvasBlur: () => void;
  638. private _onCanvasFocus: () => void;
  639. private _onFullscreenChange: () => void;
  640. private _onPointerLockChange: () => void;
  641. private _onVRDisplayPointerRestricted: () => void;
  642. private _onVRDisplayPointerUnrestricted: () => void;
  643. // VRDisplay connection
  644. private _onVrDisplayConnect: Nullable<(display: any) => void>;
  645. private _onVrDisplayDisconnect: Nullable<() => void>;
  646. private _onVrDisplayPresentChange: Nullable<() => void>;
  647. /**
  648. * Observable signaled when VR display mode changes
  649. */
  650. public onVRDisplayChangedObservable = new Observable<IDisplayChangedEventArgs>();
  651. /**
  652. * Observable signaled when VR request present is complete
  653. */
  654. public onVRRequestPresentComplete = new Observable<boolean>();
  655. /**
  656. * Observable signaled when VR request present starts
  657. */
  658. public onVRRequestPresentStart = new Observable<Engine>();
  659. private _hardwareScalingLevel: number;
  660. /** @hidden */
  661. protected _caps: EngineCapabilities;
  662. private _pointerLockRequested: boolean;
  663. private _isStencilEnable: boolean;
  664. private _colorWrite = true;
  665. private _loadingScreen: ILoadingScreen;
  666. /** @hidden */
  667. public _drawCalls = new PerfCounter();
  668. /** @hidden */
  669. public _textureCollisions = new PerfCounter();
  670. private _glVersion: string;
  671. private _glRenderer: string;
  672. private _glVendor: string;
  673. private _videoTextureSupported: boolean;
  674. private _renderingQueueLaunched = false;
  675. private _activeRenderLoops = new Array<() => void>();
  676. // Deterministic lockstepMaxSteps
  677. private _deterministicLockstep: boolean = false;
  678. private _lockstepMaxSteps: number = 4;
  679. // Lost context
  680. /**
  681. * Observable signaled when a context lost event is raised
  682. */
  683. public onContextLostObservable = new Observable<Engine>();
  684. /**
  685. * Observable signaled when a context restored event is raised
  686. */
  687. public onContextRestoredObservable = new Observable<Engine>();
  688. private _onContextLost: (evt: Event) => void;
  689. private _onContextRestored: (evt: Event) => void;
  690. private _contextWasLost = false;
  691. private _doNotHandleContextLost = false;
  692. /**
  693. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  694. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  695. */
  696. public get doNotHandleContextLost(): boolean {
  697. return this._doNotHandleContextLost;
  698. }
  699. public set doNotHandleContextLost(value: boolean) {
  700. this._doNotHandleContextLost = value;
  701. }
  702. // FPS
  703. private _performanceMonitor = new PerformanceMonitor();
  704. private _fps = 60;
  705. private _deltaTime = 0;
  706. /**
  707. * Turn this value on if you want to pause FPS computation when in background
  708. */
  709. public disablePerformanceMonitorInBackground = false;
  710. /**
  711. * Gets the performance monitor attached to this engine
  712. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  713. */
  714. public get performanceMonitor(): PerformanceMonitor {
  715. return this._performanceMonitor;
  716. }
  717. // States
  718. /** @hidden */
  719. protected _depthCullingState = new _DepthCullingState();
  720. /** @hidden */
  721. protected _stencilState = new _StencilState();
  722. /** @hidden */
  723. protected _alphaState = new _AlphaState();
  724. /** @hidden */
  725. protected _alphaMode = Engine.ALPHA_DISABLE;
  726. // Cache
  727. protected _internalTexturesCache = new Array<InternalTexture>();
  728. /** @hidden */
  729. protected _activeChannel = 0;
  730. private _currentTextureChannel = -1;
  731. /** @hidden */
  732. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  733. /** @hidden */
  734. protected _currentEffect: Nullable<Effect>;
  735. /** @hidden */
  736. protected _currentProgram: Nullable<WebGLProgram>;
  737. private _compiledEffects: { [key: string]: Effect } = {};
  738. private _vertexAttribArraysEnabled: boolean[] = [];
  739. /** @hidden */
  740. protected _cachedViewport: Nullable<Viewport>;
  741. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  742. /** @hidden */
  743. protected _cachedVertexBuffers: any;
  744. /** @hidden */
  745. protected _cachedIndexBuffer: Nullable<WebGLBuffer>;
  746. /** @hidden */
  747. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  748. /** @hidden */
  749. protected _currentRenderTarget: Nullable<InternalTexture>;
  750. private _uintIndicesCurrentlySet = false;
  751. private _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  752. /** @hidden */
  753. protected _currentFramebuffer: Nullable<WebGLFramebuffer> = null;
  754. private _currentBufferPointers = new Array<BufferPointer>();
  755. private _currentInstanceLocations = new Array<number>();
  756. private _currentInstanceBuffers = new Array<WebGLBuffer>();
  757. private _textureUnits: Int32Array;
  758. private _firstBoundInternalTextureTracker = new DummyInternalTextureTracker();
  759. private _lastBoundInternalTextureTracker = new DummyInternalTextureTracker();
  760. private _workingCanvas: Nullable<HTMLCanvasElement>;
  761. private _workingContext: Nullable<CanvasRenderingContext2D>;
  762. private _rescalePostProcess: PassPostProcess;
  763. private _dummyFramebuffer: WebGLFramebuffer;
  764. private _externalData: StringDictionary<Object>;
  765. private _bindedRenderFunction: any;
  766. private _vaoRecordInProgress = false;
  767. private _mustWipeVertexAttributes = false;
  768. private _emptyTexture: Nullable<InternalTexture>;
  769. private _emptyCubeTexture: Nullable<InternalTexture>;
  770. private _emptyTexture3D: Nullable<InternalTexture>;
  771. /** @hidden */
  772. public _frameHandler: number;
  773. private _nextFreeTextureSlots = new Array<number>();
  774. private _maxSimultaneousTextures = 0;
  775. private _activeRequests = new Array<IFileRequest>();
  776. // Hardware supported Compressed Textures
  777. private _texturesSupported = new Array<string>();
  778. private _textureFormatInUse: Nullable<string>;
  779. /**
  780. * Gets the list of texture formats supported
  781. */
  782. public get texturesSupported(): Array<string> {
  783. return this._texturesSupported;
  784. }
  785. /**
  786. * Gets the list of texture formats in use
  787. */
  788. public get textureFormatInUse(): Nullable<string> {
  789. return this._textureFormatInUse;
  790. }
  791. /**
  792. * Gets the current viewport
  793. */
  794. public get currentViewport(): Nullable<Viewport> {
  795. return this._cachedViewport;
  796. }
  797. /**
  798. * Gets the default empty texture
  799. */
  800. public get emptyTexture(): InternalTexture {
  801. if (!this._emptyTexture) {
  802. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  803. }
  804. return this._emptyTexture;
  805. }
  806. /**
  807. * Gets the default empty 3D texture
  808. */
  809. public get emptyTexture3D(): InternalTexture {
  810. if (!this._emptyTexture3D) {
  811. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  812. }
  813. return this._emptyTexture3D;
  814. }
  815. /**
  816. * Gets the default empty cube texture
  817. */
  818. public get emptyCubeTexture(): InternalTexture {
  819. if (!this._emptyCubeTexture) {
  820. var faceData = new Uint8Array(4);
  821. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  822. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  823. }
  824. return this._emptyCubeTexture;
  825. }
  826. /**
  827. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  828. */
  829. public readonly premultipliedAlpha: boolean = true;
  830. /**
  831. * Creates a new engine
  832. * @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
  833. * @param antialias defines enable antialiasing (default: false)
  834. * @param options defines further options to be sent to the getContext() function
  835. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  836. */
  837. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  838. // Register promises
  839. PromisePolyfill.Apply();
  840. let canvas: Nullable<HTMLCanvasElement> = null;
  841. Engine.Instances.push(this);
  842. if (!canvasOrContext) {
  843. return;
  844. }
  845. options = options || {};
  846. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  847. canvas = <HTMLCanvasElement>canvasOrContext;
  848. this._renderingCanvas = canvas;
  849. if (antialias != null) {
  850. options.antialias = antialias;
  851. }
  852. if (options.deterministicLockstep === undefined) {
  853. options.deterministicLockstep = false;
  854. }
  855. if (options.lockstepMaxSteps === undefined) {
  856. options.lockstepMaxSteps = 4;
  857. }
  858. if (options.preserveDrawingBuffer === undefined) {
  859. options.preserveDrawingBuffer = false;
  860. }
  861. if (options.audioEngine === undefined) {
  862. options.audioEngine = true;
  863. }
  864. if (options.stencil === undefined) {
  865. options.stencil = true;
  866. }
  867. if (options.premultipliedAlpha === false) {
  868. this.premultipliedAlpha = false;
  869. }
  870. this._deterministicLockstep = options.deterministicLockstep;
  871. this._lockstepMaxSteps = options.lockstepMaxSteps;
  872. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  873. // Exceptions
  874. if (navigator && navigator.userAgent) {
  875. let ua = navigator.userAgent;
  876. for (var exception of Engine.ExceptionList) {
  877. let key = exception.key;
  878. let targets = exception.targets;
  879. if (ua.indexOf(key) > -1) {
  880. if (exception.capture && exception.captureConstraint) {
  881. let capture = exception.capture;
  882. let constraint = exception.captureConstraint;
  883. let regex = new RegExp(capture);
  884. let matches = regex.exec(ua);
  885. if (matches && matches.length > 0) {
  886. let capturedValue = parseInt(matches[matches.length - 1]);
  887. if (capturedValue >= constraint) {
  888. continue;
  889. }
  890. }
  891. }
  892. for (var target of targets) {
  893. switch (target) {
  894. case "uniformBuffer":
  895. this.disableUniformBuffers = true;
  896. break;
  897. case "textureBindingOptimization":
  898. this.disableTextureBindingOptimization = true;
  899. break;
  900. }
  901. }
  902. }
  903. }
  904. }
  905. // GL
  906. if (!options.disableWebGL2Support) {
  907. try {
  908. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  909. if (this._gl) {
  910. this._webGLVersion = 2.0;
  911. // Prevent weird browsers to lie :-)
  912. if (!this._gl.deleteQuery) {
  913. this._webGLVersion = 1.0;
  914. }
  915. }
  916. } catch (e) {
  917. // Do nothing
  918. }
  919. }
  920. if (!this._gl) {
  921. if (!canvas) {
  922. throw new Error("The provided canvas is null or undefined.");
  923. }
  924. try {
  925. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  926. } catch (e) {
  927. throw new Error("WebGL not supported");
  928. }
  929. }
  930. if (!this._gl) {
  931. throw new Error("WebGL not supported");
  932. }
  933. this._onCanvasFocus = () => {
  934. this.onCanvasFocusObservable.notifyObservers(this);
  935. };
  936. this._onCanvasBlur = () => {
  937. this.onCanvasBlurObservable.notifyObservers(this);
  938. };
  939. canvas.addEventListener("focus", this._onCanvasFocus);
  940. canvas.addEventListener("blur", this._onCanvasBlur);
  941. this._onBlur = () => {
  942. if (this.disablePerformanceMonitorInBackground) {
  943. this._performanceMonitor.disable();
  944. }
  945. this._windowIsBackground = true;
  946. };
  947. this._onFocus = () => {
  948. if (this.disablePerformanceMonitorInBackground) {
  949. this._performanceMonitor.enable();
  950. }
  951. this._windowIsBackground = false;
  952. };
  953. this._onCanvasPointerOut = (ev) => {
  954. this.onCanvasPointerOutObservable.notifyObservers(ev);
  955. };
  956. if (Tools.IsWindowObjectExist()) {
  957. window.addEventListener("blur", this._onBlur);
  958. window.addEventListener("focus", this._onFocus);
  959. }
  960. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  961. // Context lost
  962. if (!this._doNotHandleContextLost) {
  963. this._onContextLost = (evt: Event) => {
  964. evt.preventDefault();
  965. this._contextWasLost = true;
  966. Tools.Warn("WebGL context lost.");
  967. this.onContextLostObservable.notifyObservers(this);
  968. };
  969. this._onContextRestored = (evt: Event) => {
  970. // Adding a timeout to avoid race condition at browser level
  971. setTimeout(() => {
  972. // Rebuild gl context
  973. this._initGLContext();
  974. // Rebuild effects
  975. this._rebuildEffects();
  976. // Rebuild textures
  977. this._rebuildInternalTextures();
  978. // Rebuild buffers
  979. this._rebuildBuffers();
  980. // Cache
  981. this.wipeCaches(true);
  982. Tools.Warn("WebGL context successfully restored.");
  983. this.onContextRestoredObservable.notifyObservers(this);
  984. this._contextWasLost = false;
  985. }, 0);
  986. };
  987. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  988. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  989. }
  990. } else {
  991. this._gl = <WebGLRenderingContext>canvasOrContext;
  992. this._renderingCanvas = this._gl.canvas;
  993. if (this._gl.renderbufferStorageMultisample) {
  994. this._webGLVersion = 2.0;
  995. }
  996. const attributes = this._gl.getContextAttributes();
  997. if (attributes) {
  998. options.stencil = attributes.stencil;
  999. }
  1000. }
  1001. // Viewport
  1002. const devicePixelRatio = Tools.IsWindowObjectExist() ? (window.devicePixelRatio || 1.0) : 1.0;
  1003. var limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
  1004. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0;
  1005. this.resize();
  1006. this._isStencilEnable = options.stencil ? true : false;
  1007. this._initGLContext();
  1008. if (canvas) {
  1009. // Fullscreen
  1010. this._onFullscreenChange = () => {
  1011. if ((<any>document).fullscreen !== undefined) {
  1012. this.isFullscreen = (<any>document).fullscreen;
  1013. } else if (document.mozFullScreen !== undefined) {
  1014. this.isFullscreen = document.mozFullScreen;
  1015. } else if (document.webkitIsFullScreen !== undefined) {
  1016. this.isFullscreen = document.webkitIsFullScreen;
  1017. } else if (document.msIsFullScreen !== undefined) {
  1018. this.isFullscreen = document.msIsFullScreen;
  1019. }
  1020. // Pointer lock
  1021. if (this.isFullscreen && this._pointerLockRequested && canvas) {
  1022. canvas.requestPointerLock = canvas.requestPointerLock ||
  1023. canvas.msRequestPointerLock ||
  1024. canvas.mozRequestPointerLock ||
  1025. canvas.webkitRequestPointerLock;
  1026. if (canvas.requestPointerLock) {
  1027. canvas.requestPointerLock();
  1028. }
  1029. }
  1030. };
  1031. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  1032. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  1033. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  1034. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  1035. // Pointer lock
  1036. this._onPointerLockChange = () => {
  1037. this.isPointerLock = (document.mozPointerLockElement === canvas ||
  1038. document.webkitPointerLockElement === canvas ||
  1039. document.msPointerLockElement === canvas ||
  1040. document.pointerLockElement === canvas
  1041. );
  1042. };
  1043. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  1044. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  1045. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  1046. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  1047. this._onVRDisplayPointerRestricted = () => {
  1048. if (canvas) {
  1049. canvas.requestPointerLock();
  1050. }
  1051. };
  1052. this._onVRDisplayPointerUnrestricted = () => {
  1053. document.exitPointerLock();
  1054. };
  1055. if (Tools.IsWindowObjectExist()) {
  1056. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  1057. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  1058. }
  1059. }
  1060. // Create Audio Engine if needed.
  1061. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  1062. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  1063. }
  1064. // Prepare buffer pointers
  1065. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  1066. this._currentBufferPointers[i] = new BufferPointer();
  1067. }
  1068. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  1069. // Load WebVR Devices
  1070. if (options.autoEnableWebVR) {
  1071. this.initWebVR();
  1072. }
  1073. // Detect if we are running on a faulty buggy OS.
  1074. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  1075. // Detect if we are running on a faulty buggy desktop OS.
  1076. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  1077. console.log(`Babylon.js v${Engine.Version} - ${this.description}`);
  1078. this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;
  1079. }
  1080. private _rebuildInternalTextures(): void {
  1081. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  1082. for (var internalTexture of currentState) {
  1083. internalTexture._rebuild();
  1084. }
  1085. }
  1086. private _rebuildEffects(): void {
  1087. for (var key in this._compiledEffects) {
  1088. let effect = <Effect>this._compiledEffects[key];
  1089. effect._prepareEffect();
  1090. }
  1091. Effect.ResetCache();
  1092. }
  1093. /**
  1094. * Gets a boolean indicating if all created effects are ready
  1095. * @returns true if all effects are ready
  1096. */
  1097. public areAllEffectsReady(): boolean {
  1098. for (var key in this._compiledEffects) {
  1099. let effect = <Effect>this._compiledEffects[key];
  1100. if (!effect.isReady()) {
  1101. return false;
  1102. }
  1103. }
  1104. return true;
  1105. }
  1106. private _rebuildBuffers(): void {
  1107. // Index / Vertex
  1108. for (var scene of this.scenes) {
  1109. scene.resetCachedMaterial();
  1110. scene._rebuildGeometries();
  1111. scene._rebuildTextures();
  1112. }
  1113. // Uniforms
  1114. for (var uniformBuffer of this._uniformBuffers) {
  1115. uniformBuffer._rebuild();
  1116. }
  1117. }
  1118. private _initGLContext(): void {
  1119. // Caps
  1120. this._caps = new EngineCapabilities();
  1121. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  1122. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  1123. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  1124. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  1125. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  1126. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  1127. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  1128. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  1129. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  1130. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  1131. // Infos
  1132. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  1133. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  1134. if (rendererInfo != null) {
  1135. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  1136. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  1137. }
  1138. if (!this._glVendor) {
  1139. this._glVendor = "Unknown vendor";
  1140. }
  1141. if (!this._glRenderer) {
  1142. this._glRenderer = "Unknown renderer";
  1143. }
  1144. // Constants
  1145. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  1146. if (this._gl.RGBA16F !== 0x881A) {
  1147. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  1148. }
  1149. if (this._gl.RGBA32F !== 0x8814) {
  1150. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  1151. }
  1152. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  1153. this._gl.DEPTH24_STENCIL8 = 35056;
  1154. }
  1155. // Extensions
  1156. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  1157. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  1158. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  1159. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  1160. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  1161. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  1162. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  1163. 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');
  1164. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  1165. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  1166. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  1167. this._caps.highPrecisionShaderSupported = false;
  1168. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  1169. if (this._caps.timerQuery) {
  1170. if (this._webGLVersion === 1) {
  1171. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  1172. }
  1173. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  1174. }
  1175. // Checks if some of the format renders first to allow the use of webgl inspector.
  1176. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  1177. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  1178. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  1179. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  1180. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  1181. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  1182. if (this._webGLVersion > 1) {
  1183. this._gl.HALF_FLOAT_OES = 0x140B;
  1184. }
  1185. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  1186. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  1187. // Draw buffers
  1188. if (this._webGLVersion > 1) {
  1189. this._caps.drawBuffersExtension = true;
  1190. } else {
  1191. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  1192. if (drawBuffersExtension !== null) {
  1193. this._caps.drawBuffersExtension = true;
  1194. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  1195. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  1196. for (var i = 0; i < 16; i++) {
  1197. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
  1198. }
  1199. } else {
  1200. this._caps.drawBuffersExtension = false;
  1201. }
  1202. }
  1203. // Shader compiler threads
  1204. this._caps.parallelShaderCompile = this._gl.getExtension('KHR_parallel_shader_compile');
  1205. if (this._caps.parallelShaderCompile) {
  1206. const threads = this._gl.getParameter(this._caps.parallelShaderCompile.MAX_SHADER_COMPILER_THREADS_KHR);
  1207. this._caps.parallelShaderCompile.maxShaderCompilerThreadsKHR(threads);
  1208. }
  1209. // Depth Texture
  1210. if (this._webGLVersion > 1) {
  1211. this._caps.depthTextureExtension = true;
  1212. } else {
  1213. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  1214. if (depthTextureExtension != null) {
  1215. this._caps.depthTextureExtension = true;
  1216. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  1217. }
  1218. }
  1219. // Vertex array object
  1220. if (this._webGLVersion > 1) {
  1221. this._caps.vertexArrayObject = true;
  1222. } else {
  1223. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  1224. if (vertexArrayObjectExtension != null) {
  1225. this._caps.vertexArrayObject = true;
  1226. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  1227. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  1228. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  1229. } else {
  1230. this._caps.vertexArrayObject = false;
  1231. }
  1232. }
  1233. // Instances count
  1234. if (this._webGLVersion > 1) {
  1235. this._caps.instancedArrays = true;
  1236. } else {
  1237. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  1238. if (instanceExtension != null) {
  1239. this._caps.instancedArrays = true;
  1240. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  1241. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  1242. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  1243. } else {
  1244. this._caps.instancedArrays = false;
  1245. }
  1246. }
  1247. // Intelligently add supported compressed formats in order to check for.
  1248. // Check for ASTC support first as it is most powerful and to be very cross platform.
  1249. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  1250. // Likely no hardware which supports both PVR & DXT, so order matters little.
  1251. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  1252. if (this._caps.astc) { this.texturesSupported.push('-astc.ktx'); }
  1253. if (this._caps.s3tc) { this.texturesSupported.push('-dxt.ktx'); }
  1254. if (this._caps.pvrtc) { this.texturesSupported.push('-pvrtc.ktx'); }
  1255. if (this._caps.etc2) { this.texturesSupported.push('-etc2.ktx'); }
  1256. if (this._caps.etc1) { this.texturesSupported.push('-etc1.ktx'); }
  1257. if (this._gl.getShaderPrecisionFormat) {
  1258. var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
  1259. var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  1260. if (vertex_highp && fragment_highp) {
  1261. this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
  1262. }
  1263. }
  1264. // Depth buffer
  1265. this.setDepthBuffer(true);
  1266. this.setDepthFunctionToLessOrEqual();
  1267. this.setDepthWrite(true);
  1268. // Texture maps
  1269. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  1270. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1271. this._nextFreeTextureSlots.push(slot);
  1272. }
  1273. }
  1274. /**
  1275. * Gets version of the current webGL context
  1276. */
  1277. public get webGLVersion(): number {
  1278. return this._webGLVersion;
  1279. }
  1280. /**
  1281. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  1282. */
  1283. public get isStencilEnable(): boolean {
  1284. return this._isStencilEnable;
  1285. }
  1286. private _prepareWorkingCanvas(): void {
  1287. if (this._workingCanvas) {
  1288. return;
  1289. }
  1290. this._workingCanvas = document.createElement("canvas");
  1291. let context = this._workingCanvas.getContext("2d");
  1292. if (context) {
  1293. this._workingContext = context;
  1294. }
  1295. }
  1296. /**
  1297. * Reset the texture cache to empty state
  1298. */
  1299. public resetTextureCache() {
  1300. for (var key in this._boundTexturesCache) {
  1301. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  1302. continue;
  1303. }
  1304. let boundTexture = this._boundTexturesCache[key];
  1305. if (boundTexture) {
  1306. this._removeDesignatedSlot(boundTexture);
  1307. }
  1308. this._boundTexturesCache[key] = null;
  1309. }
  1310. if (!this.disableTextureBindingOptimization) {
  1311. this._nextFreeTextureSlots = [];
  1312. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  1313. this._nextFreeTextureSlots.push(slot);
  1314. }
  1315. }
  1316. this._currentTextureChannel = -1;
  1317. }
  1318. /**
  1319. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  1320. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1321. * @returns true if engine is in deterministic lock step mode
  1322. */
  1323. public isDeterministicLockStep(): boolean {
  1324. return this._deterministicLockstep;
  1325. }
  1326. /**
  1327. * Gets the max steps when engine is running in deterministic lock step
  1328. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  1329. * @returns the max steps
  1330. */
  1331. public getLockstepMaxSteps(): number {
  1332. return this._lockstepMaxSteps;
  1333. }
  1334. /**
  1335. * Gets an object containing information about the current webGL context
  1336. * @returns an object containing the vender, the renderer and the version of the current webGL context
  1337. */
  1338. public getGlInfo() {
  1339. return {
  1340. vendor: this._glVendor,
  1341. renderer: this._glRenderer,
  1342. version: this._glVersion
  1343. };
  1344. }
  1345. /**
  1346. * Gets current aspect ratio
  1347. * @param camera defines the camera to use to get the aspect ratio
  1348. * @param useScreen defines if screen size must be used (or the current render target if any)
  1349. * @returns a number defining the aspect ratio
  1350. */
  1351. public getAspectRatio(camera: Camera, useScreen = false): number {
  1352. var viewport = camera.viewport;
  1353. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  1354. }
  1355. /**
  1356. * Gets current screen aspect ratio
  1357. * @returns a number defining the aspect ratio
  1358. */
  1359. public getScreenAspectRatio(): number {
  1360. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  1361. }
  1362. /**
  1363. * Gets the current render width
  1364. * @param useScreen defines if screen size must be used (or the current render target if any)
  1365. * @returns a number defining the current render width
  1366. */
  1367. public getRenderWidth(useScreen = false): number {
  1368. if (!useScreen && this._currentRenderTarget) {
  1369. return this._currentRenderTarget.width;
  1370. }
  1371. return this._gl.drawingBufferWidth;
  1372. }
  1373. /**
  1374. * Gets the current render height
  1375. * @param useScreen defines if screen size must be used (or the current render target if any)
  1376. * @returns a number defining the current render height
  1377. */
  1378. public getRenderHeight(useScreen = false): number {
  1379. if (!useScreen && this._currentRenderTarget) {
  1380. return this._currentRenderTarget.height;
  1381. }
  1382. return this._gl.drawingBufferHeight;
  1383. }
  1384. /**
  1385. * Gets the HTML canvas attached with the current webGL context
  1386. * @returns a HTML canvas
  1387. */
  1388. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  1389. return this._renderingCanvas;
  1390. }
  1391. /**
  1392. * Gets the client rect of the HTML canvas attached with the current webGL context
  1393. * @returns a client rectanglee
  1394. */
  1395. public getRenderingCanvasClientRect(): Nullable<ClientRect> {
  1396. if (!this._renderingCanvas) {
  1397. return null;
  1398. }
  1399. return this._renderingCanvas.getBoundingClientRect();
  1400. }
  1401. /**
  1402. * Defines the 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. * @param level defines the level to use
  1406. */
  1407. public setHardwareScalingLevel(level: number): void {
  1408. this._hardwareScalingLevel = level;
  1409. this.resize();
  1410. }
  1411. /**
  1412. * Gets the current hardware scaling level.
  1413. * By default the hardware scaling level is computed from the window device ratio.
  1414. * 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.
  1415. * @returns a number indicating the current hardware scaling level
  1416. */
  1417. public getHardwareScalingLevel(): number {
  1418. return this._hardwareScalingLevel;
  1419. }
  1420. /**
  1421. * Gets the list of loaded textures
  1422. * @returns an array containing all loaded textures
  1423. */
  1424. public getLoadedTexturesCache(): InternalTexture[] {
  1425. return this._internalTexturesCache;
  1426. }
  1427. /**
  1428. * Gets the object containing all engine capabilities
  1429. * @returns the EngineCapabilities object
  1430. */
  1431. public getCaps(): EngineCapabilities {
  1432. return this._caps;
  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. * @param excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (default: empty array)
  3632. * @returns a InternalTexture for assignment back into BABYLON.Texture
  3633. */
  3634. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<Scene>, samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  3635. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  3636. buffer: Nullable<string | ArrayBuffer | HTMLImageElement | Blob> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  3637. forcedExtension: Nullable<string> = null, excludeLoaders: Array<IInternalTextureLoader> = []): InternalTexture {
  3638. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  3639. var fromData = url.substr(0, 5) === "data:";
  3640. var fromBlob = url.substr(0, 5) === "blob:";
  3641. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  3642. let texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_URL);
  3643. // establish the file extension, if possible
  3644. var lastDot = url.lastIndexOf('.');
  3645. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  3646. let loader: Nullable<IInternalTextureLoader> = null;
  3647. for (let availableLoader of Engine._TextureLoaders) {
  3648. if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  3649. loader = availableLoader;
  3650. break;
  3651. }
  3652. }
  3653. if (loader) {
  3654. url = loader.transformUrl(url, this._textureFormatInUse);
  3655. }
  3656. if (scene) {
  3657. scene._addPendingData(texture);
  3658. }
  3659. texture.url = url;
  3660. texture.generateMipMaps = !noMipmap;
  3661. texture.samplingMode = samplingMode;
  3662. texture.invertY = invertY;
  3663. if (!this._doNotHandleContextLost) {
  3664. // Keep a link to the buffer only if we plan to handle context lost
  3665. texture._buffer = buffer;
  3666. }
  3667. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  3668. if (onLoad && !fallback) {
  3669. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  3670. }
  3671. if (!fallback) { this._internalTexturesCache.push(texture); }
  3672. let onInternalError = (message?: string, exception?: any) => {
  3673. if (scene) {
  3674. scene._removePendingData(texture);
  3675. }
  3676. let customFallback = false;
  3677. if (loader) {
  3678. const fallbackUrl = loader.getFallbackTextureUrl(url, this._textureFormatInUse);
  3679. if (fallbackUrl) {
  3680. // Add Back
  3681. customFallback = true;
  3682. excludeLoaders.push(loader);
  3683. Tools.Warn((loader.constructor as any).name + " failed when trying to load " + texture.url + ", falling back to the next supported loader");
  3684. this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture, undefined, undefined, excludeLoaders);
  3685. return;
  3686. }
  3687. }
  3688. if (!customFallback) {
  3689. if (onLoadObserver) {
  3690. texture.onLoadedObservable.remove(onLoadObserver);
  3691. }
  3692. if (Tools.UseFallbackTexture) {
  3693. this.createTexture(Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  3694. return;
  3695. }
  3696. }
  3697. if (onError) {
  3698. onError(message || "Unknown error", exception);
  3699. }
  3700. };
  3701. // processing for non-image formats
  3702. if (loader) {
  3703. var callback = (data: string | ArrayBuffer) => {
  3704. loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void, loadFailed) => {
  3705. if (loadFailed) {
  3706. onInternalError("TextureLoader failed to load data");
  3707. }else {
  3708. this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, () => {
  3709. done();
  3710. return false;
  3711. }, samplingMode);
  3712. }
  3713. });
  3714. };
  3715. if (!buffer) {
  3716. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, (request?: XMLHttpRequest, exception?: any) => {
  3717. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  3718. });
  3719. } else {
  3720. callback(buffer as ArrayBuffer);
  3721. }
  3722. } else {
  3723. var onload = (img: HTMLImageElement) => {
  3724. if (fromBlob && !this._doNotHandleContextLost) {
  3725. // We need to store the image if we need to rebuild the texture
  3726. // in case of a webgl context lost
  3727. texture._buffer = img;
  3728. }
  3729. this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  3730. let gl = this._gl;
  3731. var isPot = (img.width === potWidth && img.height === potHeight);
  3732. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  3733. if (isPot) {
  3734. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3735. return false;
  3736. }
  3737. let maxTextureSize = this._caps.maxTextureSize;
  3738. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  3739. this._prepareWorkingCanvas();
  3740. if (!this._workingCanvas || !this._workingContext) {
  3741. return false;
  3742. }
  3743. this._workingCanvas.width = potWidth;
  3744. this._workingCanvas.height = potHeight;
  3745. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3746. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  3747. texture.width = potWidth;
  3748. texture.height = potHeight;
  3749. return false;
  3750. } else {
  3751. // Using shaders when possible to rescale because canvas.drawImage is lossy
  3752. let source = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  3753. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  3754. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  3755. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  3756. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  3757. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  3758. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  3759. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  3760. this._releaseTexture(source);
  3761. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3762. continuationCallback();
  3763. });
  3764. }
  3765. return true;
  3766. }, samplingMode);
  3767. };
  3768. if (!fromData || isBase64) {
  3769. if (buffer instanceof HTMLImageElement) {
  3770. onload(buffer);
  3771. } else {
  3772. Tools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null);
  3773. }
  3774. }
  3775. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  3776. Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null);
  3777. }
  3778. else {
  3779. onload(<HTMLImageElement>buffer);
  3780. }
  3781. }
  3782. return texture;
  3783. }
  3784. private _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<Scene>, internalFormat: number, onComplete: () => void): void {
  3785. let rtt = this.createRenderTargetTexture({
  3786. width: destination.width,
  3787. height: destination.height,
  3788. }, {
  3789. generateMipMaps: false,
  3790. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  3791. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  3792. generateDepthBuffer: false,
  3793. generateStencilBuffer: false
  3794. }
  3795. );
  3796. if (!this._rescalePostProcess) {
  3797. this._rescalePostProcess = new PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  3798. }
  3799. this._rescalePostProcess.getEffect().executeWhenCompiled(() => {
  3800. this._rescalePostProcess.onApply = function(effect) {
  3801. effect._bindTexture("textureSampler", source);
  3802. };
  3803. let hostingScene = scene;
  3804. if (!hostingScene) {
  3805. hostingScene = this.scenes[this.scenes.length - 1];
  3806. }
  3807. hostingScene.postProcessManager.directRender([this._rescalePostProcess], rtt, true);
  3808. this._bindTextureDirectly(this._gl.TEXTURE_2D, destination, true);
  3809. this._gl.copyTexImage2D(this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  3810. this.unBindFramebuffer(rtt);
  3811. this._releaseTexture(rtt);
  3812. if (onComplete) {
  3813. onComplete();
  3814. }
  3815. });
  3816. }
  3817. /**
  3818. * Update a raw texture
  3819. * @param texture defines the texture to update
  3820. * @param data defines the data to store in the texture
  3821. * @param format defines the format of the data
  3822. * @param invertY defines if data must be stored with Y axis inverted
  3823. * @param compression defines the compression used (null by default)
  3824. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3825. */
  3826. public updateRawTexture(texture: Nullable<InternalTexture>, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, type = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  3827. if (!texture) {
  3828. return;
  3829. }
  3830. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  3831. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  3832. // babylon's internalFormat but gl's texImage2D format
  3833. var internalFormat = this._getInternalFormat(format);
  3834. var textureType = this._getWebGLTextureType(type);
  3835. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3836. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  3837. if (!this._doNotHandleContextLost) {
  3838. texture._bufferView = data;
  3839. texture.format = format;
  3840. texture.type = type;
  3841. texture.invertY = invertY;
  3842. texture._compression = compression;
  3843. }
  3844. if (texture.width % 4 !== 0) {
  3845. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  3846. }
  3847. if (compression && data) {
  3848. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, 0, <DataView>data);
  3849. } else {
  3850. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  3851. }
  3852. if (texture.generateMipMaps) {
  3853. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3854. }
  3855. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3856. // this.resetTextureCache();
  3857. texture.isReady = true;
  3858. }
  3859. /**
  3860. * Creates a raw texture
  3861. * @param data defines the data to store in the texture
  3862. * @param width defines the width of the texture
  3863. * @param height defines the height of the texture
  3864. * @param format defines the format of the data
  3865. * @param generateMipMaps defines if the engine should generate the mip levels
  3866. * @param invertY defines if data must be stored with Y axis inverted
  3867. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3868. * @param compression defines the compression used (null by default)
  3869. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  3870. * @returns the raw texture inside an InternalTexture
  3871. */
  3872. 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 {
  3873. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW);
  3874. texture.baseWidth = width;
  3875. texture.baseHeight = height;
  3876. texture.width = width;
  3877. texture.height = height;
  3878. texture.format = format;
  3879. texture.generateMipMaps = generateMipMaps;
  3880. texture.samplingMode = samplingMode;
  3881. texture.invertY = invertY;
  3882. texture._compression = compression;
  3883. texture.type = type;
  3884. if (!this._doNotHandleContextLost) {
  3885. texture._bufferView = data;
  3886. }
  3887. this.updateRawTexture(texture, data, format, invertY, compression, type);
  3888. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  3889. // Filters
  3890. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  3891. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3892. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3893. if (generateMipMaps) {
  3894. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3895. }
  3896. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3897. this._internalTexturesCache.push(texture);
  3898. return texture;
  3899. }
  3900. private _unpackFlipYCached: Nullable<boolean> = null;
  3901. /**
  3902. * In case you are sharing the context with other applications, it might
  3903. * be interested to not cache the unpack flip y state to ensure a consistent
  3904. * value would be set.
  3905. */
  3906. public enableUnpackFlipYCached = true;
  3907. /** @hidden */
  3908. public _unpackFlipY(value: boolean): void {
  3909. if (this._unpackFlipYCached !== value) {
  3910. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  3911. if (this.enableUnpackFlipYCached) {
  3912. this._unpackFlipYCached = value;
  3913. }
  3914. }
  3915. }
  3916. /** @hidden */
  3917. public _getUnpackAlignement(): number {
  3918. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  3919. }
  3920. /**
  3921. * Creates a dynamic texture
  3922. * @param width defines the width of the texture
  3923. * @param height defines the height of the texture
  3924. * @param generateMipMaps defines if the engine should generate the mip levels
  3925. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  3926. * @returns the dynamic texture inside an InternalTexture
  3927. */
  3928. public createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number): InternalTexture {
  3929. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_DYNAMIC);
  3930. texture.baseWidth = width;
  3931. texture.baseHeight = height;
  3932. if (generateMipMaps) {
  3933. width = this.needPOTTextures ? Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  3934. height = this.needPOTTextures ? Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  3935. }
  3936. // this.resetTextureCache();
  3937. texture.width = width;
  3938. texture.height = height;
  3939. texture.isReady = false;
  3940. texture.generateMipMaps = generateMipMaps;
  3941. texture.samplingMode = samplingMode;
  3942. this.updateTextureSamplingMode(samplingMode, texture);
  3943. this._internalTexturesCache.push(texture);
  3944. return texture;
  3945. }
  3946. /**
  3947. * Update the sampling mode of a given texture
  3948. * @param samplingMode defines the required sampling mode
  3949. * @param texture defines the texture to update
  3950. */
  3951. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture): void {
  3952. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  3953. if (texture.isCube) {
  3954. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3955. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3956. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3957. } else if (texture.is3D) {
  3958. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3959. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3960. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3961. } else {
  3962. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  3963. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3964. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3965. }
  3966. texture.samplingMode = samplingMode;
  3967. }
  3968. /**
  3969. * Update the content of a dynamic texture
  3970. * @param texture defines the texture to update
  3971. * @param canvas defines the canvas containing the source
  3972. * @param invertY defines if data must be stored with Y axis inverted
  3973. * @param premulAlpha defines if alpha is stored as premultiplied
  3974. * @param format defines the format of the data
  3975. * @param forceBindTexture if the texture should be forced to be bound eg. after a graphics context loss (Default: false)
  3976. */
  3977. public updateDynamicTexture(texture: Nullable<InternalTexture>, canvas: HTMLCanvasElement, invertY: boolean, premulAlpha: boolean = false, format?: number, forceBindTexture: boolean = false): void {
  3978. if (!texture) {
  3979. return;
  3980. }
  3981. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true, forceBindTexture);
  3982. this._unpackFlipY(invertY);
  3983. if (premulAlpha) {
  3984. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  3985. }
  3986. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  3987. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  3988. if (texture.generateMipMaps) {
  3989. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3990. }
  3991. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3992. if (premulAlpha) {
  3993. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  3994. }
  3995. texture.isReady = true;
  3996. }
  3997. /**
  3998. * Update a video texture
  3999. * @param texture defines the texture to update
  4000. * @param video defines the video element to use
  4001. * @param invertY defines if data must be stored with Y axis inverted
  4002. */
  4003. public updateVideoTexture(texture: Nullable<InternalTexture>, video: HTMLVideoElement, invertY: boolean): void {
  4004. if (!texture || texture._isDisabled) {
  4005. return;
  4006. }
  4007. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  4008. this._unpackFlipY(!invertY); // Video are upside down by default
  4009. try {
  4010. // Testing video texture support
  4011. if (this._videoTextureSupported === undefined) {
  4012. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4013. if (this._gl.getError() !== 0) {
  4014. this._videoTextureSupported = false;
  4015. } else {
  4016. this._videoTextureSupported = true;
  4017. }
  4018. }
  4019. // Copy video through the current working canvas if video texture is not supported
  4020. if (!this._videoTextureSupported) {
  4021. if (!texture._workingCanvas) {
  4022. texture._workingCanvas = document.createElement("canvas");
  4023. let context = texture._workingCanvas.getContext("2d");
  4024. if (!context) {
  4025. throw new Error("Unable to get 2d context");
  4026. }
  4027. texture._workingContext = context;
  4028. texture._workingCanvas.width = texture.width;
  4029. texture._workingCanvas.height = texture.height;
  4030. }
  4031. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  4032. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4033. } else {
  4034. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4035. }
  4036. if (texture.generateMipMaps) {
  4037. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4038. }
  4039. if (!wasPreviouslyBound) {
  4040. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  4041. }
  4042. // this.resetTextureCache();
  4043. texture.isReady = true;
  4044. } catch (ex) {
  4045. // Something unexpected
  4046. // Let's disable the texture
  4047. texture._isDisabled = true;
  4048. }
  4049. }
  4050. /**
  4051. * Updates a depth texture Comparison Mode and Function.
  4052. * If the comparison Function is equal to 0, the mode will be set to none.
  4053. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  4054. * @param texture The texture to set the comparison function for
  4055. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  4056. */
  4057. public updateTextureComparisonFunction(texture: InternalTexture, comparisonFunction: number): void {
  4058. if (this.webGLVersion === 1) {
  4059. Tools.Error("WebGL 1 does not support texture comparison.");
  4060. return;
  4061. }
  4062. var gl = this._gl;
  4063. if (texture.isCube) {
  4064. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  4065. if (comparisonFunction === 0) {
  4066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  4067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  4068. }
  4069. else {
  4070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  4071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  4072. }
  4073. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4074. } else {
  4075. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  4076. if (comparisonFunction === 0) {
  4077. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  4078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  4079. }
  4080. else {
  4081. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  4082. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  4083. }
  4084. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  4085. }
  4086. texture._comparisonFunction = comparisonFunction;
  4087. }
  4088. private _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number): void {
  4089. var width = (<{ width: number, height: number }>size).width || <number>size;
  4090. var height = (<{ width: number, height: number }>size).height || <number>size;
  4091. internalTexture.baseWidth = width;
  4092. internalTexture.baseHeight = height;
  4093. internalTexture.width = width;
  4094. internalTexture.height = height;
  4095. internalTexture.isReady = true;
  4096. internalTexture.samples = 1;
  4097. internalTexture.generateMipMaps = false;
  4098. internalTexture._generateDepthBuffer = true;
  4099. internalTexture._generateStencilBuffer = generateStencil;
  4100. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4101. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4102. internalTexture._comparisonFunction = comparisonFunction;
  4103. var gl = this._gl;
  4104. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4105. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  4106. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  4107. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  4108. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4109. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4110. if (comparisonFunction === 0) {
  4111. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  4112. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  4113. }
  4114. else {
  4115. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  4116. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  4117. }
  4118. }
  4119. /**
  4120. * Creates a depth stencil texture.
  4121. * This is only available in WebGL 2 or with the depth texture extension available.
  4122. * @param size The size of face edge in the texture.
  4123. * @param options The options defining the texture.
  4124. * @returns The texture
  4125. */
  4126. public createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions): InternalTexture {
  4127. if (options.isCube) {
  4128. let width = (<{ width: number, height: number }>size).width || <number>size;
  4129. return this._createDepthStencilCubeTexture(width, options);
  4130. }
  4131. else {
  4132. return this._createDepthStencilTexture(size, options);
  4133. }
  4134. }
  4135. /**
  4136. * Creates a depth stencil texture.
  4137. * This is only available in WebGL 2 or with the depth texture extension available.
  4138. * @param size The size of face edge in the texture.
  4139. * @param options The options defining the texture.
  4140. * @returns The texture
  4141. */
  4142. private _createDepthStencilTexture(size: number | { width: number, height: number }, options: DepthTextureCreationOptions): InternalTexture {
  4143. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_DEPTHTEXTURE);
  4144. if (!this._caps.depthTextureExtension) {
  4145. Tools.Error("Depth texture is not supported by your browser or hardware.");
  4146. return internalTexture;
  4147. }
  4148. var internalOptions = {
  4149. bilinearFiltering: false,
  4150. comparisonFunction: 0,
  4151. generateStencil: false,
  4152. ...options
  4153. };
  4154. var gl = this._gl;
  4155. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  4156. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4157. if (this.webGLVersion > 1) {
  4158. if (internalOptions.generateStencil) {
  4159. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4160. }
  4161. else {
  4162. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4163. }
  4164. }
  4165. else {
  4166. if (internalOptions.generateStencil) {
  4167. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  4168. }
  4169. else {
  4170. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4171. }
  4172. }
  4173. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4174. return internalTexture;
  4175. }
  4176. /**
  4177. * Creates a depth stencil cube texture.
  4178. * This is only available in WebGL 2.
  4179. * @param size The size of face edge in the cube texture.
  4180. * @param options The options defining the cube texture.
  4181. * @returns The cube texture
  4182. */
  4183. private _createDepthStencilCubeTexture(size: number, options: DepthTextureCreationOptions): InternalTexture {
  4184. var internalTexture = new InternalTexture(this, InternalTexture.DATASOURCE_UNKNOWN);
  4185. internalTexture.isCube = true;
  4186. if (this.webGLVersion === 1) {
  4187. Tools.Error("Depth cube texture is not supported by WebGL 1.");
  4188. return internalTexture;
  4189. }
  4190. var internalOptions = {
  4191. bilinearFiltering: false,
  4192. comparisonFunction: 0,
  4193. generateStencil: false,
  4194. ...options
  4195. };
  4196. var gl = this._gl;
  4197. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  4198. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  4199. // Create the depth/stencil buffer
  4200. for (var face = 0; face < 6; face++) {
  4201. if (internalOptions.generateStencil) {
  4202. 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);
  4203. }
  4204. else {
  4205. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  4206. }
  4207. }
  4208. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4209. return internalTexture;
  4210. }
  4211. /**
  4212. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  4213. * @param renderTarget The render target to set the frame buffer for
  4214. */
  4215. public setFrameBufferDepthStencilTexture(renderTarget: RenderTargetTexture): void {
  4216. // Create the framebuffer
  4217. var internalTexture = renderTarget.getInternalTexture();
  4218. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  4219. return;
  4220. }
  4221. var gl = this._gl;
  4222. var depthStencilTexture = renderTarget.depthStencilTexture;
  4223. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  4224. if (depthStencilTexture.isCube) {
  4225. if (depthStencilTexture._generateStencilBuffer) {
  4226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4227. }
  4228. else {
  4229. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  4230. }
  4231. }
  4232. else {
  4233. if (depthStencilTexture._generateStencilBuffer) {
  4234. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4235. }
  4236. else {
  4237. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  4238. }
  4239. }
  4240. this.bindUnboundFramebuffer(null);
  4241. }
  4242. /**
  4243. * Creates a new render target texture
  4244. * @param size defines the size of the texture
  4245. * @param options defines the options used to create the texture
  4246. * @returns a new render target texture stored in an InternalTexture
  4247. */
  4248. public createRenderTargetTexture(size: number | { width: number, height: number }, options: boolean | RenderTargetCreationOptions): InternalTexture {
  4249. let fullOptions = new RenderTargetCreationOptions();
  4250. if (options !== undefined && typeof options === "object") {
  4251. fullOptions.generateMipMaps = options.generateMipMaps;
  4252. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4253. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  4254. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  4255. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  4256. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  4257. } else {
  4258. fullOptions.generateMipMaps = <boolean>options;
  4259. fullOptions.generateDepthBuffer = true;
  4260. fullOptions.generateStencilBuffer = false;
  4261. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4262. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  4263. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  4264. }
  4265. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4266. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4267. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4268. }
  4269. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4270. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4271. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4272. }
  4273. var gl = this._gl;
  4274. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4275. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  4276. var width = (<{ width: number, height: number }>size).width || <number>size;
  4277. var height = (<{ width: number, height: number }>size).height || <number>size;
  4278. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  4279. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4280. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4281. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4282. }
  4283. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4286. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4287. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  4288. // Create the framebuffer
  4289. var currentFrameBuffer = this._currentFramebuffer;
  4290. var framebuffer = gl.createFramebuffer();
  4291. this.bindUnboundFramebuffer(framebuffer);
  4292. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4293. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  4294. if (fullOptions.generateMipMaps) {
  4295. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4296. }
  4297. // Unbind
  4298. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4299. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4300. this.bindUnboundFramebuffer(currentFrameBuffer);
  4301. texture._framebuffer = framebuffer;
  4302. texture.baseWidth = width;
  4303. texture.baseHeight = height;
  4304. texture.width = width;
  4305. texture.height = height;
  4306. texture.isReady = true;
  4307. texture.samples = 1;
  4308. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  4309. texture.samplingMode = fullOptions.samplingMode;
  4310. texture.type = fullOptions.type;
  4311. texture.format = fullOptions.format;
  4312. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4313. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  4314. // this.resetTextureCache();
  4315. this._internalTexturesCache.push(texture);
  4316. return texture;
  4317. }
  4318. /**
  4319. * Create a multi render target texture
  4320. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  4321. * @param size defines the size of the texture
  4322. * @param options defines the creation options
  4323. * @returns the cube texture as an InternalTexture
  4324. */
  4325. public createMultipleRenderTarget(size: any, options: IMultiRenderTargetOptions): InternalTexture[] {
  4326. var generateMipMaps = false;
  4327. var generateDepthBuffer = true;
  4328. var generateStencilBuffer = false;
  4329. var generateDepthTexture = false;
  4330. var textureCount = 1;
  4331. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  4332. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  4333. var types = new Array<number>();
  4334. var samplingModes = new Array<number>();
  4335. if (options !== undefined) {
  4336. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  4337. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4338. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  4339. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  4340. textureCount = options.textureCount || 1;
  4341. if (options.types) {
  4342. types = options.types;
  4343. }
  4344. if (options.samplingModes) {
  4345. samplingModes = options.samplingModes;
  4346. }
  4347. }
  4348. var gl = this._gl;
  4349. // Create the framebuffer
  4350. var framebuffer = gl.createFramebuffer();
  4351. this.bindUnboundFramebuffer(framebuffer);
  4352. var width = size.width || size;
  4353. var height = size.height || size;
  4354. var textures = [];
  4355. var attachments = [];
  4356. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  4357. for (var i = 0; i < textureCount; i++) {
  4358. var samplingMode = samplingModes[i] || defaultSamplingMode;
  4359. var type = types[i] || defaultType;
  4360. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4361. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4362. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4363. }
  4364. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4365. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4366. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4367. }
  4368. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  4369. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4370. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4371. Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4372. }
  4373. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4374. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4375. textures.push(texture);
  4376. attachments.push(attachment);
  4377. gl.activeTexture((<any>gl)["TEXTURE" + i]);
  4378. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  4379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4381. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4382. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4383. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  4384. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  4385. if (generateMipMaps) {
  4386. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4387. }
  4388. // Unbind
  4389. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  4390. texture._framebuffer = framebuffer;
  4391. texture._depthStencilBuffer = depthStencilBuffer;
  4392. texture.baseWidth = width;
  4393. texture.baseHeight = height;
  4394. texture.width = width;
  4395. texture.height = height;
  4396. texture.isReady = true;
  4397. texture.samples = 1;
  4398. texture.generateMipMaps = generateMipMaps;
  4399. texture.samplingMode = samplingMode;
  4400. texture.type = type;
  4401. texture._generateDepthBuffer = generateDepthBuffer;
  4402. texture._generateStencilBuffer = generateStencilBuffer;
  4403. texture._attachments = attachments;
  4404. this._internalTexturesCache.push(texture);
  4405. }
  4406. if (generateDepthTexture && this._caps.depthTextureExtension) {
  4407. // Depth texture
  4408. var depthTexture = new InternalTexture(this, InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  4409. gl.activeTexture(gl.TEXTURE0);
  4410. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  4411. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  4412. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  4413. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4414. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4415. gl.texImage2D(
  4416. gl.TEXTURE_2D,
  4417. 0,
  4418. this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16,
  4419. width,
  4420. height,
  4421. 0,
  4422. gl.DEPTH_COMPONENT,
  4423. gl.UNSIGNED_SHORT,
  4424. null
  4425. );
  4426. gl.framebufferTexture2D(
  4427. gl.FRAMEBUFFER,
  4428. gl.DEPTH_ATTACHMENT,
  4429. gl.TEXTURE_2D,
  4430. depthTexture._webGLTexture,
  4431. 0
  4432. );
  4433. depthTexture._framebuffer = framebuffer;
  4434. depthTexture.baseWidth = width;
  4435. depthTexture.baseHeight = height;
  4436. depthTexture.width = width;
  4437. depthTexture.height = height;
  4438. depthTexture.isReady = true;
  4439. depthTexture.samples = 1;
  4440. depthTexture.generateMipMaps = generateMipMaps;
  4441. depthTexture.samplingMode = gl.NEAREST;
  4442. depthTexture._generateDepthBuffer = generateDepthBuffer;
  4443. depthTexture._generateStencilBuffer = generateStencilBuffer;
  4444. textures.push(depthTexture);
  4445. this._internalTexturesCache.push(depthTexture);
  4446. }
  4447. gl.drawBuffers(attachments);
  4448. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4449. this.bindUnboundFramebuffer(null);
  4450. this.resetTextureCache();
  4451. return textures;
  4452. }
  4453. private _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  4454. var depthStencilBuffer: Nullable<WebGLRenderbuffer> = null;
  4455. var gl = this._gl;
  4456. // Create the depth/stencil buffer
  4457. if (generateStencilBuffer) {
  4458. depthStencilBuffer = gl.createRenderbuffer();
  4459. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4460. if (samples > 1) {
  4461. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  4462. } else {
  4463. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  4464. }
  4465. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4466. }
  4467. else if (generateDepthBuffer) {
  4468. depthStencilBuffer = gl.createRenderbuffer();
  4469. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  4470. if (samples > 1) {
  4471. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  4472. } else {
  4473. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4474. }
  4475. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  4476. }
  4477. return depthStencilBuffer;
  4478. }
  4479. /**
  4480. * Updates the sample count of a render target texture
  4481. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4482. * @param texture defines the texture to update
  4483. * @param samples defines the sample count to set
  4484. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4485. */
  4486. public updateRenderTargetTextureSampleCount(texture: Nullable<InternalTexture>, samples: number): number {
  4487. if (this.webGLVersion < 2 || !texture) {
  4488. return 1;
  4489. }
  4490. if (texture.samples === samples) {
  4491. return samples;
  4492. }
  4493. var gl = this._gl;
  4494. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4495. // Dispose previous render buffers
  4496. if (texture._depthStencilBuffer) {
  4497. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  4498. texture._depthStencilBuffer = null;
  4499. }
  4500. if (texture._MSAAFramebuffer) {
  4501. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  4502. texture._MSAAFramebuffer = null;
  4503. }
  4504. if (texture._MSAARenderBuffer) {
  4505. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  4506. texture._MSAARenderBuffer = null;
  4507. }
  4508. if (samples > 1) {
  4509. let framebuffer = gl.createFramebuffer();
  4510. if (!framebuffer) {
  4511. throw new Error("Unable to create multi sampled framebuffer");
  4512. }
  4513. texture._MSAAFramebuffer = framebuffer;
  4514. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  4515. var colorRenderbuffer = gl.createRenderbuffer();
  4516. if (!colorRenderbuffer) {
  4517. throw new Error("Unable to create multi sampled framebuffer");
  4518. }
  4519. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4520. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4521. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  4522. texture._MSAARenderBuffer = colorRenderbuffer;
  4523. } else {
  4524. this.bindUnboundFramebuffer(texture._framebuffer);
  4525. }
  4526. texture.samples = samples;
  4527. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  4528. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4529. this.bindUnboundFramebuffer(null);
  4530. return samples;
  4531. }
  4532. /**
  4533. * Update the sample count for a given multiple render target texture
  4534. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  4535. * @param textures defines the textures to update
  4536. * @param samples defines the sample count to set
  4537. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  4538. */
  4539. public updateMultipleRenderTargetTextureSampleCount(textures: Nullable<InternalTexture[]>, samples: number): number {
  4540. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  4541. return 1;
  4542. }
  4543. if (textures[0].samples === samples) {
  4544. return samples;
  4545. }
  4546. var gl = this._gl;
  4547. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  4548. // Dispose previous render buffers
  4549. if (textures[0]._depthStencilBuffer) {
  4550. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  4551. textures[0]._depthStencilBuffer = null;
  4552. }
  4553. if (textures[0]._MSAAFramebuffer) {
  4554. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  4555. textures[0]._MSAAFramebuffer = null;
  4556. }
  4557. for (var i = 0; i < textures.length; i++) {
  4558. if (textures[i]._MSAARenderBuffer) {
  4559. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  4560. textures[i]._MSAARenderBuffer = null;
  4561. }
  4562. }
  4563. if (samples > 1) {
  4564. let framebuffer = gl.createFramebuffer();
  4565. if (!framebuffer) {
  4566. throw new Error("Unable to create multi sampled framebuffer");
  4567. }
  4568. this.bindUnboundFramebuffer(framebuffer);
  4569. let depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  4570. var attachments = [];
  4571. for (var i = 0; i < textures.length; i++) {
  4572. var texture = textures[i];
  4573. var attachment = (<any>gl)[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  4574. var colorRenderbuffer = gl.createRenderbuffer();
  4575. if (!colorRenderbuffer) {
  4576. throw new Error("Unable to create multi sampled framebuffer");
  4577. }
  4578. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  4579. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  4580. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  4581. texture._MSAAFramebuffer = framebuffer;
  4582. texture._MSAARenderBuffer = colorRenderbuffer;
  4583. texture.samples = samples;
  4584. texture._depthStencilBuffer = depthStencilBuffer;
  4585. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4586. attachments.push(attachment);
  4587. }
  4588. gl.drawBuffers(attachments);
  4589. } else {
  4590. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  4591. }
  4592. this.bindUnboundFramebuffer(null);
  4593. return samples;
  4594. }
  4595. /** @hidden */
  4596. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  4597. var gl = this._gl;
  4598. var target = gl.TEXTURE_2D;
  4599. if (texture.isCube) {
  4600. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4601. }
  4602. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  4603. }
  4604. /** @hidden */
  4605. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  4606. var gl = this._gl;
  4607. var textureType = this._getWebGLTextureType(texture.type);
  4608. var format = this._getInternalFormat(texture.format);
  4609. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  4610. this._unpackFlipY(texture.invertY);
  4611. var target = gl.TEXTURE_2D;
  4612. if (texture.isCube) {
  4613. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4614. }
  4615. const lodMaxWidth = Math.round(Scalar.Log2(texture.width));
  4616. const lodMaxHeight = Math.round(Scalar.Log2(texture.height));
  4617. const width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  4618. const height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  4619. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  4620. }
  4621. /** @hidden */
  4622. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  4623. var gl = this._gl;
  4624. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4625. this._bindTextureDirectly(bindTarget, texture, true);
  4626. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  4627. this._bindTextureDirectly(bindTarget, null, true);
  4628. }
  4629. /** @hidden */
  4630. public _uploadImageToTexture(texture: InternalTexture, image: HTMLImageElement, faceIndex: number = 0, lod: number = 0) {
  4631. var gl = this._gl;
  4632. var textureType = this._getWebGLTextureType(texture.type);
  4633. var format = this._getInternalFormat(texture.format);
  4634. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  4635. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  4636. this._bindTextureDirectly(bindTarget, texture, true);
  4637. this._unpackFlipY(texture.invertY);
  4638. var target = gl.TEXTURE_2D;
  4639. if (texture.isCube) {
  4640. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  4641. }
  4642. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  4643. this._bindTextureDirectly(bindTarget, null, true);
  4644. }
  4645. /**
  4646. * Creates a new render target cube texture
  4647. * @param size defines the size of the texture
  4648. * @param options defines the options used to create the texture
  4649. * @returns a new render target cube texture stored in an InternalTexture
  4650. */
  4651. public createRenderTargetCubeTexture(size: number, options?: Partial<RenderTargetCreationOptions>): InternalTexture {
  4652. let fullOptions = {
  4653. generateMipMaps: true,
  4654. generateDepthBuffer: true,
  4655. generateStencilBuffer: false,
  4656. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  4657. samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  4658. format: Engine.TEXTUREFORMAT_RGBA,
  4659. ...options
  4660. };
  4661. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  4662. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  4663. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4664. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4665. }
  4666. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  4667. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  4668. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  4669. }
  4670. var gl = this._gl;
  4671. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RENDERTARGET);
  4672. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4673. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  4674. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4675. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4676. Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  4677. }
  4678. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  4679. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  4680. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4681. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4682. for (var face = 0; face < 6; face++) {
  4683. 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);
  4684. }
  4685. // Create the framebuffer
  4686. var framebuffer = gl.createFramebuffer();
  4687. this.bindUnboundFramebuffer(framebuffer);
  4688. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  4689. // MipMaps
  4690. if (fullOptions.generateMipMaps) {
  4691. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4692. }
  4693. // Unbind
  4694. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4695. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4696. this.bindUnboundFramebuffer(null);
  4697. texture._framebuffer = framebuffer;
  4698. texture.width = size;
  4699. texture.height = size;
  4700. texture.isReady = true;
  4701. texture.isCube = true;
  4702. texture.samples = 1;
  4703. texture.generateMipMaps = fullOptions.generateMipMaps;
  4704. texture.samplingMode = fullOptions.samplingMode;
  4705. texture.type = fullOptions.type;
  4706. texture.format = fullOptions.format;
  4707. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  4708. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  4709. this._internalTexturesCache.push(texture);
  4710. return texture;
  4711. }
  4712. /**
  4713. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  4714. * @param rootUrl defines the url where the file to load is located
  4715. * @param scene defines the current scene
  4716. * @param lodScale defines scale to apply to the mip map selection
  4717. * @param lodOffset defines offset to apply to the mip map selection
  4718. * @param onLoad defines an optional callback raised when the texture is loaded
  4719. * @param onError defines an optional callback raised if there is an issue to load the texture
  4720. * @param format defines the format of the data
  4721. * @param forcedExtension defines the extension to use to pick the right loader
  4722. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  4723. * @returns the cube texture as an InternalTexture
  4724. */
  4725. public createPrefilteredCubeTexture(rootUrl: string, scene: Nullable<Scene>, lodScale: number, lodOffset: number,
  4726. onLoad: Nullable<(internalTexture: Nullable<InternalTexture>) => void> = null,
  4727. onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null,
  4728. createPolynomials: boolean = true): InternalTexture {
  4729. var callback = (loadData: any) => {
  4730. if (!loadData) {
  4731. if (onLoad) {
  4732. onLoad(null);
  4733. }
  4734. return;
  4735. }
  4736. let texture = loadData.texture as InternalTexture;
  4737. if (!createPolynomials) {
  4738. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  4739. }
  4740. else if (loadData.info.sphericalPolynomial) {
  4741. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  4742. }
  4743. texture._dataSource = InternalTexture.DATASOURCE_CUBEPREFILTERED;
  4744. if (this._caps.textureLOD) {
  4745. // Do not add extra process if texture lod is supported.
  4746. if (onLoad) {
  4747. onLoad(texture);
  4748. }
  4749. return;
  4750. }
  4751. const mipSlices = 3;
  4752. var gl = this._gl;
  4753. const width = loadData.width;
  4754. if (!width) {
  4755. return;
  4756. }
  4757. const textures: BaseTexture[] = [];
  4758. for (let i = 0; i < mipSlices; i++) {
  4759. //compute LOD from even spacing in smoothness (matching shader calculation)
  4760. let smoothness = i / (mipSlices - 1);
  4761. let roughness = 1 - smoothness;
  4762. let minLODIndex = lodOffset; // roughness = 0
  4763. let maxLODIndex = Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  4764. let lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  4765. let mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  4766. var glTextureFromLod = new InternalTexture(this, InternalTexture.DATASOURCE_TEMP);
  4767. glTextureFromLod.type = texture.type;
  4768. glTextureFromLod.format = texture.format;
  4769. glTextureFromLod.width = Math.pow(2, Math.max(Scalar.Log2(width) - mipmapIndex, 0));
  4770. glTextureFromLod.height = glTextureFromLod.width;
  4771. glTextureFromLod.isCube = true;
  4772. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  4773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4774. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  4775. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4777. if (loadData.isDDS) {
  4778. var info: DDSInfo = loadData.info;
  4779. var data: any = loadData.data;
  4780. this._unpackFlipY(info.isCompressed);
  4781. DDSTools.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  4782. }
  4783. else {
  4784. Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  4785. }
  4786. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4787. // Wrap in a base texture for easy binding.
  4788. const lodTexture = new BaseTexture(scene);
  4789. lodTexture.isCube = true;
  4790. lodTexture._texture = glTextureFromLod;
  4791. glTextureFromLod.isReady = true;
  4792. textures.push(lodTexture);
  4793. }
  4794. texture._lodTextureHigh = textures[2];
  4795. texture._lodTextureMid = textures[1];
  4796. texture._lodTextureLow = textures[0];
  4797. if (onLoad) {
  4798. onLoad(texture);
  4799. }
  4800. };
  4801. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  4802. }
  4803. /**
  4804. * Creates a cube texture
  4805. * @param rootUrl defines the url where the files to load is located
  4806. * @param scene defines the current scene
  4807. * @param files defines the list of files to load (1 per face)
  4808. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  4809. * @param onLoad defines an optional callback raised when the texture is loaded
  4810. * @param onError defines an optional callback raised if there is an issue to load the texture
  4811. * @param format defines the format of the data
  4812. * @param forcedExtension defines the extension to use to pick the right loader
  4813. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  4814. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  4815. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  4816. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  4817. * @param excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (defualt: empty array)
  4818. * @returns the cube texture as an InternalTexture
  4819. */
  4820. public createCubeTexture(rootUrl: string, scene: Nullable<Scene>, files: Nullable<string[]>, noMipmap?: boolean, onLoad: Nullable<(data?: any) => void> = null, onError: Nullable<(message?: string, exception?: any) => void> = null, format?: number, forcedExtension: any = null, createPolynomials = false, lodScale: number = 0, lodOffset: number = 0, fallback: Nullable<InternalTexture> = null, excludeLoaders: Array<IInternalTextureLoader> = []): InternalTexture {
  4821. var gl = this._gl;
  4822. var texture = fallback ? fallback : new InternalTexture(this, InternalTexture.DATASOURCE_CUBE);
  4823. texture.isCube = true;
  4824. texture.url = rootUrl;
  4825. texture.generateMipMaps = !noMipmap;
  4826. texture._lodGenerationScale = lodScale;
  4827. texture._lodGenerationOffset = lodOffset;
  4828. if (!this._doNotHandleContextLost) {
  4829. texture._extension = forcedExtension;
  4830. texture._files = files;
  4831. }
  4832. var lastDot = rootUrl.lastIndexOf('.');
  4833. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  4834. let loader: Nullable<IInternalTextureLoader> = null;
  4835. for (let availableLoader of Engine._TextureLoaders) {
  4836. if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  4837. loader = availableLoader;
  4838. break;
  4839. }
  4840. }
  4841. let onInternalError = (request?: XMLHttpRequest, exception?: any) => {
  4842. if (loader) {
  4843. const fallbackUrl = loader.getFallbackTextureUrl(texture.url, this._textureFormatInUse);
  4844. Tools.Warn((loader.constructor as any).name + " failed when trying to load " + texture.url + ", falling back to the next supported loader");
  4845. if (fallbackUrl) {
  4846. excludeLoaders.push(loader);
  4847. this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture, excludeLoaders);
  4848. return;
  4849. }
  4850. }
  4851. if (onError && request) {
  4852. onError(request.status + " " + request.statusText, exception);
  4853. }
  4854. };
  4855. if (loader) {
  4856. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  4857. const onloaddata = (data: any) => {
  4858. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4859. loader!.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  4860. };
  4861. if (files && files.length === 6) {
  4862. if (loader.supportCascades) {
  4863. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  4864. }
  4865. else if (onError) {
  4866. onError("Textures type does not support cascades.");
  4867. }
  4868. }
  4869. else {
  4870. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  4871. }
  4872. }
  4873. else {
  4874. if (!files) {
  4875. throw new Error("Cannot load cubemap because files were not defined");
  4876. }
  4877. this._cascadeLoadImgs(rootUrl, scene, (imgs) => {
  4878. var width = this.needPOTTextures ? Tools.GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width;
  4879. var height = width;
  4880. this._prepareWorkingCanvas();
  4881. if (!this._workingCanvas || !this._workingContext) {
  4882. return;
  4883. }
  4884. this._workingCanvas.width = width;
  4885. this._workingCanvas.height = height;
  4886. var faces = [
  4887. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4888. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4889. ];
  4890. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4891. this._unpackFlipY(false);
  4892. let internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  4893. for (var index = 0; index < faces.length; index++) {
  4894. this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4895. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  4896. }
  4897. if (!noMipmap) {
  4898. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4899. }
  4900. this._setCubeMapTextureParams(!noMipmap);
  4901. texture.width = width;
  4902. texture.height = height;
  4903. texture.isReady = true;
  4904. if (format) {
  4905. texture.format = format;
  4906. }
  4907. texture.onLoadedObservable.notifyObservers(texture);
  4908. texture.onLoadedObservable.clear();
  4909. if (onLoad) {
  4910. onLoad();
  4911. }
  4912. }, files, onError);
  4913. }
  4914. this._internalTexturesCache.push(texture);
  4915. return texture;
  4916. }
  4917. /**
  4918. * @hidden
  4919. */
  4920. public _setCubeMapTextureParams(loadMipmap: boolean): void {
  4921. var gl = this._gl;
  4922. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4923. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4924. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4925. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4926. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  4927. // this.resetTextureCache();
  4928. }
  4929. /**
  4930. * Update a raw cube texture
  4931. * @param texture defines the texture to udpdate
  4932. * @param data defines the data to store
  4933. * @param format defines the data format
  4934. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  4935. * @param invertY defines if data must be stored with Y axis inverted
  4936. * @param compression defines the compression used (null by default)
  4937. * @param level defines which level of the texture to update
  4938. */
  4939. public updateRawCubeTexture(texture: InternalTexture, data: ArrayBufferView[], format: number, type: number, invertY: boolean, compression: Nullable<string> = null, level = 0): void {
  4940. texture._bufferViewArray = data;
  4941. texture.format = format;
  4942. texture.type = type;
  4943. texture.invertY = invertY;
  4944. texture._compression = compression;
  4945. var gl = this._gl;
  4946. var textureType = this._getWebGLTextureType(type);
  4947. var internalFormat = this._getInternalFormat(format);
  4948. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  4949. var needConversion = false;
  4950. if (internalFormat === gl.RGB) {
  4951. internalFormat = gl.RGBA;
  4952. needConversion = true;
  4953. }
  4954. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  4955. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  4956. if (texture.width % 4 !== 0) {
  4957. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  4958. }
  4959. // Data are known to be in +X +Y +Z -X -Y -Z
  4960. for (let faceIndex = 0; faceIndex < 6; faceIndex++) {
  4961. let faceData = data[faceIndex];
  4962. if (compression) {
  4963. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (<any>(this.getCaps().s3tc))[compression], texture.width, texture.height, 0, <DataView>faceData);
  4964. } else {
  4965. if (needConversion) {
  4966. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  4967. }
  4968. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  4969. }
  4970. }
  4971. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  4972. if (isPot && texture.generateMipMaps && level === 0) {
  4973. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  4974. }
  4975. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  4976. // this.resetTextureCache();
  4977. texture.isReady = true;
  4978. }
  4979. /**
  4980. * Creates a new raw cube texture
  4981. * @param data defines the array of data to use to create each face
  4982. * @param size defines the size of the textures
  4983. * @param format defines the format of the data
  4984. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  4985. * @param generateMipMaps defines if the engine should generate the mip levels
  4986. * @param invertY defines if data must be stored with Y axis inverted
  4987. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  4988. * @param compression defines the compression used (null by default)
  4989. * @returns the cube texture as an InternalTexture
  4990. */
  4991. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  4992. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  4993. compression: Nullable<string> = null): InternalTexture {
  4994. var gl = this._gl;
  4995. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_CUBERAW);
  4996. texture.isCube = true;
  4997. texture.format = format;
  4998. texture.type = type;
  4999. if (!this._doNotHandleContextLost) {
  5000. texture._bufferViewArray = data;
  5001. }
  5002. var textureType = this._getWebGLTextureType(type);
  5003. var internalFormat = this._getInternalFormat(format);
  5004. if (internalFormat === gl.RGB) {
  5005. internalFormat = gl.RGBA;
  5006. }
  5007. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  5008. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  5009. generateMipMaps = false;
  5010. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  5011. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  5012. }
  5013. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  5014. generateMipMaps = false;
  5015. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  5016. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  5017. }
  5018. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  5019. generateMipMaps = false;
  5020. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  5021. }
  5022. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  5023. generateMipMaps = false;
  5024. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  5025. }
  5026. var width = size;
  5027. var height = width;
  5028. texture.width = width;
  5029. texture.height = height;
  5030. // Double check on POT to generate Mips.
  5031. var isPot = !this.needPOTTextures || (Tools.IsExponentOfTwo(texture.width) && Tools.IsExponentOfTwo(texture.height));
  5032. if (!isPot) {
  5033. generateMipMaps = false;
  5034. }
  5035. // Upload data if needed. The texture won't be ready until then.
  5036. if (data) {
  5037. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  5038. }
  5039. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  5040. // Filters
  5041. if (data && generateMipMaps) {
  5042. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  5043. }
  5044. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  5045. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  5046. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  5047. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5048. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5049. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  5050. texture.generateMipMaps = generateMipMaps;
  5051. return texture;
  5052. }
  5053. /**
  5054. * Creates a new raw cube texture from a specified url
  5055. * @param url defines the url where the data is located
  5056. * @param scene defines the current scene
  5057. * @param size defines the size of the textures
  5058. * @param format defines the format of the data
  5059. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  5060. * @param noMipmap defines if the engine should avoid generating the mip levels
  5061. * @param callback defines a callback used to extract texture data from loaded data
  5062. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  5063. * @param onLoad defines a callback called when texture is loaded
  5064. * @param onError defines a callback called if there is an error
  5065. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  5066. * @param invertY defines if data must be stored with Y axis inverted
  5067. * @returns the cube texture as an InternalTexture
  5068. */
  5069. public createRawCubeTextureFromUrl(url: string, scene: Scene, size: number, format: number, type: number, noMipmap: boolean,
  5070. callback: (ArrayBuffer: ArrayBuffer) => Nullable<ArrayBufferView[]>,
  5071. mipmapGenerator: Nullable<((faces: ArrayBufferView[]) => ArrayBufferView[][])>,
  5072. onLoad: Nullable<() => void> = null,
  5073. onError: Nullable<(message?: string, exception?: any) => void> = null,
  5074. samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE,
  5075. invertY = false): InternalTexture {
  5076. var gl = this._gl;
  5077. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  5078. scene._addPendingData(texture);
  5079. texture.url = url;
  5080. this._internalTexturesCache.push(texture);
  5081. var onerror = (request?: XMLHttpRequest, exception?: any) => {
  5082. scene._removePendingData(texture);
  5083. if (onError && request) {
  5084. onError(request.status + " " + request.statusText, exception);
  5085. }
  5086. };
  5087. var internalCallback = (data: any) => {
  5088. var width = texture.width;
  5089. var faceDataArrays = callback(data);
  5090. if (!faceDataArrays) {
  5091. return;
  5092. }
  5093. if (mipmapGenerator) {
  5094. var textureType = this._getWebGLTextureType(type);
  5095. var internalFormat = this._getInternalFormat(format);
  5096. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  5097. var needConversion = false;
  5098. if (internalFormat === gl.RGB) {
  5099. internalFormat = gl.RGBA;
  5100. needConversion = true;
  5101. }
  5102. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  5103. this._unpackFlipY(false);
  5104. var mipData = mipmapGenerator(faceDataArrays);
  5105. for (var level = 0; level < mipData.length; level++) {
  5106. var mipSize = width >> level;
  5107. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  5108. let mipFaceData = mipData[level][faceIndex];
  5109. if (needConversion) {
  5110. mipFaceData = this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  5111. }
  5112. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  5113. }
  5114. }
  5115. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  5116. }
  5117. else {
  5118. this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  5119. }
  5120. texture.isReady = true;
  5121. // this.resetTextureCache();
  5122. scene._removePendingData(texture);
  5123. if (onLoad) {
  5124. onLoad();
  5125. }
  5126. };
  5127. this._loadFile(url, (data) => {
  5128. internalCallback(data);
  5129. }, undefined, scene.offlineProvider, true, onerror);
  5130. return texture;
  5131. }
  5132. /**
  5133. * Update a raw 3D texture
  5134. * @param texture defines the texture to update
  5135. * @param data defines the data to store
  5136. * @param format defines the data format
  5137. * @param invertY defines if data must be stored with Y axis inverted
  5138. * @param compression defines the used compression (can be null)
  5139. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  5140. */
  5141. public updateRawTexture3D(texture: InternalTexture, data: Nullable<ArrayBufferView>, format: number, invertY: boolean, compression: Nullable<string> = null, textureType = Engine.TEXTURETYPE_UNSIGNED_INT): void {
  5142. var internalType = this._getWebGLTextureType(textureType);
  5143. var internalFormat = this._getInternalFormat(format);
  5144. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  5145. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  5146. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  5147. if (!this._doNotHandleContextLost) {
  5148. texture._bufferView = data;
  5149. texture.format = format;
  5150. texture.invertY = invertY;
  5151. texture._compression = compression;
  5152. }
  5153. if (texture.width % 4 !== 0) {
  5154. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  5155. }
  5156. if (compression && data) {
  5157. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, (<any>this.getCaps().s3tc)[compression], texture.width, texture.height, texture.depth, 0, data);
  5158. } else {
  5159. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  5160. }
  5161. if (texture.generateMipMaps) {
  5162. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  5163. }
  5164. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5165. // this.resetTextureCache();
  5166. texture.isReady = true;
  5167. }
  5168. /**
  5169. * Creates a new raw 3D texture
  5170. * @param data defines the data used to create the texture
  5171. * @param width defines the width of the texture
  5172. * @param height defines the height of the texture
  5173. * @param depth defines the depth of the texture
  5174. * @param format defines the format of the texture
  5175. * @param generateMipMaps defines if the engine must generate mip levels
  5176. * @param invertY defines if data must be stored with Y axis inverted
  5177. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  5178. * @param compression defines the compressed used (can be null)
  5179. * @param textureType defines the compressed used (can be null)
  5180. * @returns a new raw 3D texture (stored in an InternalTexture)
  5181. */
  5182. 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 {
  5183. var texture = new InternalTexture(this, InternalTexture.DATASOURCE_RAW3D);
  5184. texture.baseWidth = width;
  5185. texture.baseHeight = height;
  5186. texture.baseDepth = depth;
  5187. texture.width = width;
  5188. texture.height = height;
  5189. texture.depth = depth;
  5190. texture.format = format;
  5191. texture.type = textureType;
  5192. texture.generateMipMaps = generateMipMaps;
  5193. texture.samplingMode = samplingMode;
  5194. texture.is3D = true;
  5195. if (!this._doNotHandleContextLost) {
  5196. texture._bufferView = data;
  5197. }
  5198. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  5199. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  5200. // Filters
  5201. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  5202. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5203. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5204. if (generateMipMaps) {
  5205. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  5206. }
  5207. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5208. this._internalTexturesCache.push(texture);
  5209. return texture;
  5210. }
  5211. private _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<Scene>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  5212. var gl = this._gl;
  5213. if (!gl) {
  5214. return;
  5215. }
  5216. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  5217. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5218. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5219. if (!noMipmap && !isCompressed) {
  5220. gl.generateMipmap(gl.TEXTURE_2D);
  5221. }
  5222. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  5223. // this.resetTextureCache();
  5224. if (scene) {
  5225. scene._removePendingData(texture);
  5226. }
  5227. texture.onLoadedObservable.notifyObservers(texture);
  5228. texture.onLoadedObservable.clear();
  5229. }
  5230. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<Scene>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  5231. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE): void {
  5232. var maxTextureSize = this.getCaps().maxTextureSize;
  5233. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  5234. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  5235. var gl = this._gl;
  5236. if (!gl) {
  5237. return;
  5238. }
  5239. if (!texture._webGLTexture) {
  5240. // this.resetTextureCache();
  5241. if (scene) {
  5242. scene._removePendingData(texture);
  5243. }
  5244. return;
  5245. }
  5246. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  5247. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  5248. texture.baseWidth = width;
  5249. texture.baseHeight = height;
  5250. texture.width = potWidth;
  5251. texture.height = potHeight;
  5252. texture.isReady = true;
  5253. if (processFunction(potWidth, potHeight, () => {
  5254. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5255. })) {
  5256. // Returning as texture needs extra async steps
  5257. return;
  5258. }
  5259. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  5260. }
  5261. private _convertRGBtoRGBATextureData(rgbData: any, width: number, height: number, textureType: number): ArrayBufferView {
  5262. // Create new RGBA data container.
  5263. var rgbaData: any;
  5264. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  5265. rgbaData = new Float32Array(width * height * 4);
  5266. }
  5267. else {
  5268. rgbaData = new Uint32Array(width * height * 4);
  5269. }
  5270. // Convert each pixel.
  5271. for (let x = 0; x < width; x++) {
  5272. for (let y = 0; y < height; y++) {
  5273. let index = (y * width + x) * 3;
  5274. let newIndex = (y * width + x) * 4;
  5275. // Map Old Value to new value.
  5276. rgbaData[newIndex + 0] = rgbData[index + 0];
  5277. rgbaData[newIndex + 1] = rgbData[index + 1];
  5278. rgbaData[newIndex + 2] = rgbData[index + 2];
  5279. // Add fully opaque alpha channel.
  5280. rgbaData[newIndex + 3] = 1;
  5281. }
  5282. }
  5283. return rgbaData;
  5284. }
  5285. /** @hidden */
  5286. public _releaseFramebufferObjects(texture: InternalTexture): void {
  5287. var gl = this._gl;
  5288. if (texture._framebuffer) {
  5289. gl.deleteFramebuffer(texture._framebuffer);
  5290. texture._framebuffer = null;
  5291. }
  5292. if (texture._depthStencilBuffer) {
  5293. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  5294. texture._depthStencilBuffer = null;
  5295. }
  5296. if (texture._MSAAFramebuffer) {
  5297. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  5298. texture._MSAAFramebuffer = null;
  5299. }
  5300. if (texture._MSAARenderBuffer) {
  5301. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  5302. texture._MSAARenderBuffer = null;
  5303. }
  5304. }
  5305. /** @hidden */
  5306. public _releaseTexture(texture: InternalTexture): void {
  5307. var gl = this._gl;
  5308. this._releaseFramebufferObjects(texture);
  5309. gl.deleteTexture(texture._webGLTexture);
  5310. // Unbind channels
  5311. this.unbindAllTextures();
  5312. var index = this._internalTexturesCache.indexOf(texture);
  5313. if (index !== -1) {
  5314. this._internalTexturesCache.splice(index, 1);
  5315. }
  5316. // Integrated fixed lod samplers.
  5317. if (texture._lodTextureHigh) {
  5318. texture._lodTextureHigh.dispose();
  5319. }
  5320. if (texture._lodTextureMid) {
  5321. texture._lodTextureMid.dispose();
  5322. }
  5323. if (texture._lodTextureLow) {
  5324. texture._lodTextureLow.dispose();
  5325. }
  5326. // Set output texture of post process to null if the texture has been released/disposed
  5327. this.scenes.forEach((scene) => {
  5328. scene.postProcesses.forEach((postProcess) => {
  5329. if (postProcess._outputTexture == texture) {
  5330. postProcess._outputTexture = null;
  5331. }
  5332. });
  5333. scene.cameras.forEach((camera) => {
  5334. camera._postProcesses.forEach((postProcess) => {
  5335. if (postProcess) {
  5336. if (postProcess._outputTexture == texture) {
  5337. postProcess._outputTexture = null;
  5338. }
  5339. }
  5340. });
  5341. });
  5342. });
  5343. }
  5344. private setProgram(program: WebGLProgram): void {
  5345. if (this._currentProgram !== program) {
  5346. this._gl.useProgram(program);
  5347. this._currentProgram = program;
  5348. }
  5349. }
  5350. private _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  5351. /**
  5352. * Binds an effect to the webGL context
  5353. * @param effect defines the effect to bind
  5354. */
  5355. public bindSamplers(effect: Effect): void {
  5356. this.setProgram(effect.getProgram());
  5357. var samplers = effect.getSamplers();
  5358. for (var index = 0; index < samplers.length; index++) {
  5359. var uniform = effect.getUniform(samplers[index]);
  5360. if (uniform) {
  5361. this._boundUniforms[index] = uniform;
  5362. }
  5363. }
  5364. this._currentEffect = null;
  5365. }
  5366. private _moveBoundTextureOnTop(internalTexture: InternalTexture): void {
  5367. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  5368. return;
  5369. }
  5370. // Remove
  5371. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5372. // Bind last to it
  5373. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  5374. // Bind to dummy
  5375. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  5376. }
  5377. private _getCorrectTextureChannel(channel: number, internalTexture: Nullable<InternalTexture>): number {
  5378. if (!internalTexture) {
  5379. return -1;
  5380. }
  5381. internalTexture._initialSlot = channel;
  5382. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  5383. if (channel !== internalTexture._designatedSlot) {
  5384. this._textureCollisions.addCount(1, false);
  5385. }
  5386. } else {
  5387. if (channel !== internalTexture._designatedSlot) {
  5388. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  5389. return internalTexture._designatedSlot;
  5390. } else {
  5391. // No slot for this texture, let's pick a new one (if we find a free slot)
  5392. if (this._nextFreeTextureSlots.length) {
  5393. return this._nextFreeTextureSlots[0];
  5394. }
  5395. // We need to recycle the oldest bound texture, sorry.
  5396. this._textureCollisions.addCount(1, false);
  5397. return this._removeDesignatedSlot(<InternalTexture>this._firstBoundInternalTextureTracker.next);
  5398. }
  5399. }
  5400. }
  5401. return channel;
  5402. }
  5403. private _linkTrackers(previous: Nullable<IInternalTextureTracker>, next: Nullable<IInternalTextureTracker>) {
  5404. previous!.next = next;
  5405. next!.previous = previous;
  5406. }
  5407. private _removeDesignatedSlot(internalTexture: InternalTexture): number {
  5408. let currentSlot = internalTexture._designatedSlot;
  5409. if (currentSlot === -1) {
  5410. return -1;
  5411. }
  5412. internalTexture._designatedSlot = -1;
  5413. if (this.disableTextureBindingOptimization) {
  5414. return -1;
  5415. }
  5416. // Remove from bound list
  5417. this._linkTrackers(internalTexture.previous, internalTexture.next);
  5418. // Free the slot
  5419. this._boundTexturesCache[currentSlot] = null;
  5420. this._nextFreeTextureSlots.push(currentSlot);
  5421. return currentSlot;
  5422. }
  5423. private _activateCurrentTexture() {
  5424. if (this._currentTextureChannel !== this._activeChannel) {
  5425. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  5426. this._currentTextureChannel = this._activeChannel;
  5427. }
  5428. }
  5429. /** @hidden */
  5430. protected _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): boolean {
  5431. var wasPreviouslyBound = false;
  5432. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  5433. this._activeChannel = texture._designatedSlot;
  5434. }
  5435. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  5436. let isTextureForRendering = texture && texture._initialSlot > -1;
  5437. if (currentTextureBound !== texture || force) {
  5438. if (currentTextureBound) {
  5439. this._removeDesignatedSlot(currentTextureBound);
  5440. }
  5441. this._activateCurrentTexture();
  5442. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  5443. this._boundTexturesCache[this._activeChannel] = texture;
  5444. if (texture) {
  5445. if (!this.disableTextureBindingOptimization) {
  5446. let slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  5447. if (slotIndex > -1) {
  5448. this._nextFreeTextureSlots.splice(slotIndex, 1);
  5449. }
  5450. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  5451. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  5452. }
  5453. texture._designatedSlot = this._activeChannel;
  5454. }
  5455. } else if (forTextureDataUpdate) {
  5456. wasPreviouslyBound = true;
  5457. this._activateCurrentTexture();
  5458. }
  5459. if (isTextureForRendering && !forTextureDataUpdate) {
  5460. this._bindSamplerUniformToChannel(texture!._initialSlot, this._activeChannel);
  5461. }
  5462. return wasPreviouslyBound;
  5463. }
  5464. /** @hidden */
  5465. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  5466. if (channel < 0) {
  5467. return;
  5468. }
  5469. if (texture) {
  5470. channel = this._getCorrectTextureChannel(channel, texture);
  5471. }
  5472. this._activeChannel = channel;
  5473. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  5474. }
  5475. /**
  5476. * Sets a texture to the webGL context from a postprocess
  5477. * @param channel defines the channel to use
  5478. * @param postProcess defines the source postprocess
  5479. */
  5480. public setTextureFromPostProcess(channel: number, postProcess: Nullable<PostProcess>): void {
  5481. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  5482. }
  5483. /**
  5484. * Binds the output of the passed in post process to the texture channel specified
  5485. * @param channel The channel the texture should be bound to
  5486. * @param postProcess The post process which's output should be bound
  5487. */
  5488. public setTextureFromPostProcessOutput(channel: number, postProcess: Nullable<PostProcess>): void {
  5489. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  5490. }
  5491. /**
  5492. * Unbind all textures from the webGL context
  5493. */
  5494. public unbindAllTextures(): void {
  5495. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  5496. this._activeChannel = channel;
  5497. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5498. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5499. if (this.webGLVersion > 1) {
  5500. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5501. }
  5502. }
  5503. }
  5504. /**
  5505. * Sets a texture to the according uniform.
  5506. * @param channel The texture channel
  5507. * @param uniform The uniform to set
  5508. * @param texture The texture to apply
  5509. */
  5510. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  5511. if (channel < 0) {
  5512. return;
  5513. }
  5514. if (uniform) {
  5515. this._boundUniforms[channel] = uniform;
  5516. }
  5517. this._setTexture(channel, texture);
  5518. }
  5519. /**
  5520. * Sets a depth stencil texture from a render target to the according uniform.
  5521. * @param channel The texture channel
  5522. * @param uniform The uniform to set
  5523. * @param texture The render target texture containing the depth stencil texture to apply
  5524. */
  5525. public setDepthStencilTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<RenderTargetTexture>): void {
  5526. if (channel < 0) {
  5527. return;
  5528. }
  5529. if (uniform) {
  5530. this._boundUniforms[channel] = uniform;
  5531. }
  5532. if (!texture || !texture.depthStencilTexture) {
  5533. this._setTexture(channel, null);
  5534. }
  5535. else {
  5536. this._setTexture(channel, texture, false, true);
  5537. }
  5538. }
  5539. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  5540. let uniform = this._boundUniforms[sourceSlot];
  5541. if (uniform._currentState === destination) {
  5542. return;
  5543. }
  5544. this._gl.uniform1i(uniform, destination);
  5545. uniform._currentState = destination;
  5546. }
  5547. private _getTextureWrapMode(mode: number): number {
  5548. switch (mode) {
  5549. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  5550. return this._gl.REPEAT;
  5551. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  5552. return this._gl.CLAMP_TO_EDGE;
  5553. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  5554. return this._gl.MIRRORED_REPEAT;
  5555. }
  5556. return this._gl.REPEAT;
  5557. }
  5558. private _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  5559. // Not ready?
  5560. if (!texture) {
  5561. if (this._boundTexturesCache[channel] != null) {
  5562. this._activeChannel = channel;
  5563. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  5564. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  5565. if (this.webGLVersion > 1) {
  5566. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  5567. }
  5568. }
  5569. return false;
  5570. }
  5571. // Video
  5572. if ((<VideoTexture>texture).video) {
  5573. this._activeChannel = channel;
  5574. (<VideoTexture>texture).update();
  5575. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  5576. texture.delayLoad();
  5577. return false;
  5578. }
  5579. let internalTexture: InternalTexture;
  5580. if (depthStencilTexture) {
  5581. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  5582. }
  5583. else if (texture.isReady()) {
  5584. internalTexture = <InternalTexture>texture.getInternalTexture();
  5585. }
  5586. else if (texture.isCube) {
  5587. internalTexture = this.emptyCubeTexture;
  5588. }
  5589. else if (texture.is3D) {
  5590. internalTexture = this.emptyTexture3D;
  5591. }
  5592. else {
  5593. internalTexture = this.emptyTexture;
  5594. }
  5595. if (!isPartOfTextureArray) {
  5596. channel = this._getCorrectTextureChannel(channel, internalTexture);
  5597. }
  5598. let needToBind = true;
  5599. if (this._boundTexturesCache[channel] === internalTexture) {
  5600. this._moveBoundTextureOnTop(internalTexture);
  5601. if (!isPartOfTextureArray) {
  5602. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  5603. }
  5604. needToBind = false;
  5605. }
  5606. this._activeChannel = channel;
  5607. if (internalTexture && internalTexture.is3D) {
  5608. if (needToBind) {
  5609. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  5610. }
  5611. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5612. internalTexture._cachedWrapU = texture.wrapU;
  5613. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5614. }
  5615. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5616. internalTexture._cachedWrapV = texture.wrapV;
  5617. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5618. }
  5619. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  5620. internalTexture._cachedWrapR = texture.wrapR;
  5621. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  5622. }
  5623. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  5624. }
  5625. else if (internalTexture && internalTexture.isCube) {
  5626. if (needToBind) {
  5627. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  5628. }
  5629. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5630. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5631. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5632. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5633. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  5634. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5635. }
  5636. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5637. } else {
  5638. if (needToBind) {
  5639. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  5640. }
  5641. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  5642. internalTexture._cachedWrapU = texture.wrapU;
  5643. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  5644. }
  5645. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  5646. internalTexture._cachedWrapV = texture.wrapV;
  5647. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  5648. }
  5649. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5650. }
  5651. return true;
  5652. }
  5653. /**
  5654. * Sets an array of texture to the webGL context
  5655. * @param channel defines the channel where the texture array must be set
  5656. * @param uniform defines the associated uniform location
  5657. * @param textures defines the array of textures to bind
  5658. */
  5659. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  5660. if (channel < 0 || !uniform) {
  5661. return;
  5662. }
  5663. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  5664. this._textureUnits = new Int32Array(textures.length);
  5665. }
  5666. for (let i = 0; i < textures.length; i++) {
  5667. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  5668. }
  5669. this._gl.uniform1iv(uniform, this._textureUnits);
  5670. for (var index = 0; index < textures.length; index++) {
  5671. this._setTexture(this._textureUnits[index], textures[index], true);
  5672. }
  5673. }
  5674. /** @hidden */
  5675. public _setAnisotropicLevel(target: number, texture: BaseTexture) {
  5676. var internalTexture = texture.getInternalTexture();
  5677. if (!internalTexture) {
  5678. return;
  5679. }
  5680. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5681. var value = texture.anisotropicFilteringLevel;
  5682. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  5683. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  5684. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  5685. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  5686. }
  5687. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  5688. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  5689. internalTexture._cachedAnisotropicFilteringLevel = value;
  5690. }
  5691. }
  5692. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  5693. this._bindTextureDirectly(target, texture, true, true);
  5694. this._gl.texParameterf(target, parameter, value);
  5695. }
  5696. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  5697. if (texture) {
  5698. this._bindTextureDirectly(target, texture, true, true);
  5699. }
  5700. this._gl.texParameteri(target, parameter, value);
  5701. }
  5702. /**
  5703. * Reads pixels from the current frame buffer. Please note that this function can be slow
  5704. * @param x defines the x coordinate of the rectangle where pixels must be read
  5705. * @param y defines the y coordinate of the rectangle where pixels must be read
  5706. * @param width defines the width of the rectangle where pixels must be read
  5707. * @param height defines the height of the rectangle where pixels must be read
  5708. * @returns a Uint8Array containing RGBA colors
  5709. */
  5710. public readPixels(x: number, y: number, width: number, height: number): Uint8Array {
  5711. var data = new Uint8Array(height * width * 4);
  5712. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5713. return data;
  5714. }
  5715. /**
  5716. * Add an externaly attached data from its key.
  5717. * This method call will fail and return false, if such key already exists.
  5718. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  5719. * @param key the unique key that identifies the data
  5720. * @param data the data object to associate to the key for this Engine instance
  5721. * @return true if no such key were already present and the data was added successfully, false otherwise
  5722. */
  5723. public addExternalData<T>(key: string, data: T): boolean {
  5724. if (!this._externalData) {
  5725. this._externalData = new StringDictionary<Object>();
  5726. }
  5727. return this._externalData.add(key, data);
  5728. }
  5729. /**
  5730. * Get an externaly attached data from its key
  5731. * @param key the unique key that identifies the data
  5732. * @return the associated data, if present (can be null), or undefined if not present
  5733. */
  5734. public getExternalData<T>(key: string): T {
  5735. if (!this._externalData) {
  5736. this._externalData = new StringDictionary<Object>();
  5737. }
  5738. return <T>this._externalData.get(key);
  5739. }
  5740. /**
  5741. * Get an externaly attached data from its key, create it using a factory if it's not already present
  5742. * @param key the unique key that identifies the data
  5743. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  5744. * @return the associated data, can be null if the factory returned null.
  5745. */
  5746. public getOrAddExternalDataWithFactory<T>(key: string, factory: (k: string) => T): T {
  5747. if (!this._externalData) {
  5748. this._externalData = new StringDictionary<Object>();
  5749. }
  5750. return <T>this._externalData.getOrAddWithFactory(key, factory);
  5751. }
  5752. /**
  5753. * Remove an externaly attached data from the Engine instance
  5754. * @param key the unique key that identifies the data
  5755. * @return true if the data was successfully removed, false if it doesn't exist
  5756. */
  5757. public removeExternalData(key: string): boolean {
  5758. if (!this._externalData) {
  5759. this._externalData = new StringDictionary<Object>();
  5760. }
  5761. return this._externalData.remove(key);
  5762. }
  5763. /**
  5764. * Unbind all vertex attributes from the webGL context
  5765. */
  5766. public unbindAllAttributes() {
  5767. if (this._mustWipeVertexAttributes) {
  5768. this._mustWipeVertexAttributes = false;
  5769. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  5770. this._gl.disableVertexAttribArray(i);
  5771. this._vertexAttribArraysEnabled[i] = false;
  5772. this._currentBufferPointers[i].active = false;
  5773. }
  5774. return;
  5775. }
  5776. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  5777. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  5778. continue;
  5779. }
  5780. this._gl.disableVertexAttribArray(i);
  5781. this._vertexAttribArraysEnabled[i] = false;
  5782. this._currentBufferPointers[i].active = false;
  5783. }
  5784. }
  5785. /**
  5786. * 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
  5787. */
  5788. public releaseEffects() {
  5789. for (var name in this._compiledEffects) {
  5790. this._deleteProgram(this._compiledEffects[name]._program);
  5791. }
  5792. this._compiledEffects = {};
  5793. }
  5794. /**
  5795. * Dispose and release all associated resources
  5796. */
  5797. public dispose(): void {
  5798. this.hideLoadingUI();
  5799. this.stopRenderLoop();
  5800. this.onNewSceneAddedObservable.clear();
  5801. // Release postProcesses
  5802. while (this.postProcesses.length) {
  5803. this.postProcesses[0].dispose();
  5804. }
  5805. // Empty texture
  5806. if (this._emptyTexture) {
  5807. this._releaseTexture(this._emptyTexture);
  5808. this._emptyTexture = null;
  5809. }
  5810. if (this._emptyCubeTexture) {
  5811. this._releaseTexture(this._emptyCubeTexture);
  5812. this._emptyCubeTexture = null;
  5813. }
  5814. // Rescale PP
  5815. if (this._rescalePostProcess) {
  5816. this._rescalePostProcess.dispose();
  5817. }
  5818. // Release scenes
  5819. while (this.scenes.length) {
  5820. this.scenes[0].dispose();
  5821. }
  5822. // Release audio engine
  5823. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  5824. Engine.audioEngine.dispose();
  5825. }
  5826. // Release effects
  5827. this.releaseEffects();
  5828. // Unbind
  5829. this.unbindAllAttributes();
  5830. this._boundUniforms = [];
  5831. if (this._dummyFramebuffer) {
  5832. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  5833. }
  5834. //WebVR
  5835. this.disableVR();
  5836. // Events
  5837. if (Tools.IsWindowObjectExist()) {
  5838. window.removeEventListener("blur", this._onBlur);
  5839. window.removeEventListener("focus", this._onFocus);
  5840. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  5841. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  5842. if (this._renderingCanvas) {
  5843. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  5844. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  5845. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  5846. if (!this._doNotHandleContextLost) {
  5847. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  5848. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  5849. }
  5850. }
  5851. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5852. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5853. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5854. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5855. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5856. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5857. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5858. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5859. if (this._onVrDisplayConnect) {
  5860. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  5861. if (this._onVrDisplayDisconnect) {
  5862. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  5863. }
  5864. if (this._onVrDisplayPresentChange) {
  5865. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  5866. }
  5867. this._onVrDisplayConnect = null;
  5868. this._onVrDisplayDisconnect = null;
  5869. }
  5870. }
  5871. // Remove from Instances
  5872. var index = Engine.Instances.indexOf(this);
  5873. if (index >= 0) {
  5874. Engine.Instances.splice(index, 1);
  5875. }
  5876. this._workingCanvas = null;
  5877. this._workingContext = null;
  5878. this._currentBufferPointers = [];
  5879. this._renderingCanvas = null;
  5880. this._currentProgram = null;
  5881. this._bindedRenderFunction = null;
  5882. this.onResizeObservable.clear();
  5883. this.onCanvasBlurObservable.clear();
  5884. this.onCanvasFocusObservable.clear();
  5885. this.onCanvasPointerOutObservable.clear();
  5886. this.onBeginFrameObservable.clear();
  5887. this.onEndFrameObservable.clear();
  5888. Effect.ResetCache();
  5889. // Abort active requests
  5890. for (let request of this._activeRequests) {
  5891. request.abort();
  5892. }
  5893. }
  5894. // Loading screen
  5895. /**
  5896. * Display the loading screen
  5897. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5898. */
  5899. public displayLoadingUI(): void {
  5900. if (!Tools.IsWindowObjectExist()) {
  5901. return;
  5902. }
  5903. const loadingScreen = this.loadingScreen;
  5904. if (loadingScreen) {
  5905. loadingScreen.displayLoadingUI();
  5906. }
  5907. }
  5908. /**
  5909. * Hide the loading screen
  5910. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5911. */
  5912. public hideLoadingUI(): void {
  5913. if (!Tools.IsWindowObjectExist()) {
  5914. return;
  5915. }
  5916. const loadingScreen = this.loadingScreen;
  5917. if (loadingScreen) {
  5918. loadingScreen.hideLoadingUI();
  5919. }
  5920. }
  5921. /**
  5922. * Gets the current loading screen object
  5923. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5924. */
  5925. public get loadingScreen(): ILoadingScreen {
  5926. if (!this._loadingScreen && DefaultLoadingScreen && this._renderingCanvas) {
  5927. this._loadingScreen = new DefaultLoadingScreen(this._renderingCanvas);
  5928. }
  5929. return this._loadingScreen;
  5930. }
  5931. /**
  5932. * Sets the current loading screen object
  5933. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5934. */
  5935. public set loadingScreen(loadingScreen: ILoadingScreen) {
  5936. this._loadingScreen = loadingScreen;
  5937. }
  5938. /**
  5939. * Sets the current loading screen text
  5940. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5941. */
  5942. public set loadingUIText(text: string) {
  5943. this.loadingScreen.loadingUIText = text;
  5944. }
  5945. /**
  5946. * Sets the current loading screen background color
  5947. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  5948. */
  5949. public set loadingUIBackgroundColor(color: string) {
  5950. this.loadingScreen.loadingUIBackgroundColor = color;
  5951. }
  5952. /**
  5953. * Attach a new callback raised when context lost event is fired
  5954. * @param callback defines the callback to call
  5955. */
  5956. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5957. if (this._renderingCanvas) {
  5958. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  5959. }
  5960. }
  5961. /**
  5962. * Attach a new callback raised when context restored event is fired
  5963. * @param callback defines the callback to call
  5964. */
  5965. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  5966. if (this._renderingCanvas) {
  5967. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  5968. }
  5969. }
  5970. /**
  5971. * Gets the source code of the vertex shader associated with a specific webGL program
  5972. * @param program defines the program to use
  5973. * @returns a string containing the source code of the vertex shader associated with the program
  5974. */
  5975. public getVertexShaderSource(program: WebGLProgram): Nullable<string> {
  5976. var shaders = this._gl.getAttachedShaders(program);
  5977. if (!shaders) {
  5978. return null;
  5979. }
  5980. return this._gl.getShaderSource(shaders[0]);
  5981. }
  5982. /**
  5983. * Gets the source code of the fragment shader associated with a specific webGL program
  5984. * @param program defines the program to use
  5985. * @returns a string containing the source code of the fragment shader associated with the program
  5986. */
  5987. public getFragmentShaderSource(program: WebGLProgram): Nullable<string> {
  5988. var shaders = this._gl.getAttachedShaders(program);
  5989. if (!shaders) {
  5990. return null;
  5991. }
  5992. return this._gl.getShaderSource(shaders[1]);
  5993. }
  5994. /**
  5995. * Get the current error code of the webGL context
  5996. * @returns the error code
  5997. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  5998. */
  5999. public getError(): number {
  6000. return this._gl.getError();
  6001. }
  6002. // FPS
  6003. /**
  6004. * Gets the current framerate
  6005. * @returns a number representing the framerate
  6006. */
  6007. public getFps(): number {
  6008. return this._fps;
  6009. }
  6010. /**
  6011. * Gets the time spent between current and previous frame
  6012. * @returns a number representing the delta time in ms
  6013. */
  6014. public getDeltaTime(): number {
  6015. return this._deltaTime;
  6016. }
  6017. private _measureFps(): void {
  6018. this._performanceMonitor.sampleFrame();
  6019. this._fps = this._performanceMonitor.averageFPS;
  6020. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  6021. }
  6022. /** @hidden */
  6023. public _readTexturePixels(texture: InternalTexture, width: number, height: number, faceIndex = -1, level = 0, buffer: Nullable<ArrayBufferView> = null): ArrayBufferView {
  6024. let gl = this._gl;
  6025. if (!this._dummyFramebuffer) {
  6026. let dummy = gl.createFramebuffer();
  6027. if (!dummy) {
  6028. throw new Error("Unable to create dummy framebuffer");
  6029. }
  6030. this._dummyFramebuffer = dummy;
  6031. }
  6032. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  6033. if (faceIndex > -1) {
  6034. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  6035. } else {
  6036. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  6037. }
  6038. let readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  6039. switch (readType) {
  6040. case gl.UNSIGNED_BYTE:
  6041. if (!buffer) {
  6042. buffer = new Uint8Array(4 * width * height);
  6043. }
  6044. readType = gl.UNSIGNED_BYTE;
  6045. break;
  6046. default:
  6047. if (!buffer) {
  6048. buffer = new Float32Array(4 * width * height);
  6049. }
  6050. readType = gl.FLOAT;
  6051. break;
  6052. }
  6053. gl.readPixels(0, 0, width, height, gl.RGBA, readType, <DataView>buffer);
  6054. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  6055. return buffer;
  6056. }
  6057. private _canRenderToFloatFramebuffer(): boolean {
  6058. if (this._webGLVersion > 1) {
  6059. return this._caps.colorBufferFloat;
  6060. }
  6061. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  6062. }
  6063. private _canRenderToHalfFloatFramebuffer(): boolean {
  6064. if (this._webGLVersion > 1) {
  6065. return this._caps.colorBufferFloat;
  6066. }
  6067. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  6068. }
  6069. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  6070. private _canRenderToFramebuffer(type: number): boolean {
  6071. let gl = this._gl;
  6072. //clear existing errors
  6073. while (gl.getError() !== gl.NO_ERROR) { }
  6074. let successful = true;
  6075. let texture = gl.createTexture();
  6076. gl.bindTexture(gl.TEXTURE_2D, texture);
  6077. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  6078. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6080. let fb = gl.createFramebuffer();
  6081. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  6082. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6083. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  6084. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  6085. successful = successful && (gl.getError() === gl.NO_ERROR);
  6086. //try render by clearing frame buffer's color buffer
  6087. if (successful) {
  6088. gl.clear(gl.COLOR_BUFFER_BIT);
  6089. successful = successful && (gl.getError() === gl.NO_ERROR);
  6090. }
  6091. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  6092. if (successful) {
  6093. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  6094. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6095. let readFormat = gl.RGBA;
  6096. let readType = gl.UNSIGNED_BYTE;
  6097. let buffer = new Uint8Array(4);
  6098. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  6099. successful = successful && (gl.getError() === gl.NO_ERROR);
  6100. }
  6101. //clean up
  6102. gl.deleteTexture(texture);
  6103. gl.deleteFramebuffer(fb);
  6104. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6105. //clear accumulated errors
  6106. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  6107. return successful;
  6108. }
  6109. /** @hidden */
  6110. public _getWebGLTextureType(type: number): number {
  6111. if (this._webGLVersion === 1) {
  6112. switch (type) {
  6113. case Engine.TEXTURETYPE_FLOAT:
  6114. return this._gl.FLOAT;
  6115. case Engine.TEXTURETYPE_HALF_FLOAT:
  6116. return this._gl.HALF_FLOAT_OES;
  6117. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  6118. return this._gl.UNSIGNED_BYTE;
  6119. }
  6120. return this._gl.UNSIGNED_BYTE;
  6121. }
  6122. switch (type) {
  6123. case Engine.TEXTURETYPE_BYTE:
  6124. return this._gl.BYTE;
  6125. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  6126. return this._gl.UNSIGNED_BYTE;
  6127. case Engine.TEXTURETYPE_SHORT:
  6128. return this._gl.SHORT;
  6129. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  6130. return this._gl.UNSIGNED_SHORT;
  6131. case Engine.TEXTURETYPE_INT:
  6132. return this._gl.INT;
  6133. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  6134. return this._gl.UNSIGNED_INT;
  6135. case Engine.TEXTURETYPE_FLOAT:
  6136. return this._gl.FLOAT;
  6137. case Engine.TEXTURETYPE_HALF_FLOAT:
  6138. return this._gl.HALF_FLOAT;
  6139. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  6140. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  6141. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  6142. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  6143. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  6144. return this._gl.UNSIGNED_SHORT_5_6_5;
  6145. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  6146. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  6147. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  6148. return this._gl.UNSIGNED_INT_24_8;
  6149. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  6150. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  6151. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  6152. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  6153. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  6154. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  6155. }
  6156. return this._gl.UNSIGNED_BYTE;
  6157. }
  6158. private _getInternalFormat(format: number): number {
  6159. var internalFormat = this._gl.RGBA;
  6160. switch (format) {
  6161. case Engine.TEXTUREFORMAT_ALPHA:
  6162. internalFormat = this._gl.ALPHA;
  6163. break;
  6164. case Engine.TEXTUREFORMAT_LUMINANCE:
  6165. internalFormat = this._gl.LUMINANCE;
  6166. break;
  6167. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6168. internalFormat = this._gl.LUMINANCE_ALPHA;
  6169. break;
  6170. case Engine.TEXTUREFORMAT_RED:
  6171. internalFormat = this._gl.RED;
  6172. break;
  6173. case Engine.TEXTUREFORMAT_RG:
  6174. internalFormat = this._gl.RG;
  6175. break;
  6176. case Engine.TEXTUREFORMAT_RGB:
  6177. internalFormat = this._gl.RGB;
  6178. break;
  6179. case Engine.TEXTUREFORMAT_RGBA:
  6180. internalFormat = this._gl.RGBA;
  6181. break;
  6182. }
  6183. if (this._webGLVersion > 1) {
  6184. switch (format) {
  6185. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6186. internalFormat = this._gl.RED_INTEGER;
  6187. break;
  6188. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6189. internalFormat = this._gl.RG_INTEGER;
  6190. break;
  6191. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6192. internalFormat = this._gl.RGB_INTEGER;
  6193. break;
  6194. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6195. internalFormat = this._gl.RGBA_INTEGER;
  6196. break;
  6197. }
  6198. }
  6199. return internalFormat;
  6200. }
  6201. /** @hidden */
  6202. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  6203. if (this._webGLVersion === 1) {
  6204. if (format !== undefined) {
  6205. switch (format) {
  6206. case Engine.TEXTUREFORMAT_ALPHA:
  6207. return this._gl.ALPHA;
  6208. case Engine.TEXTUREFORMAT_LUMINANCE:
  6209. return this._gl.LUMINANCE;
  6210. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6211. return this._gl.LUMINANCE_ALPHA;
  6212. }
  6213. }
  6214. return this._gl.RGBA;
  6215. }
  6216. switch (type) {
  6217. case Engine.TEXTURETYPE_BYTE:
  6218. switch (format) {
  6219. case Engine.TEXTUREFORMAT_RED:
  6220. return this._gl.R8_SNORM;
  6221. case Engine.TEXTUREFORMAT_RG:
  6222. return this._gl.RG8_SNORM;
  6223. case Engine.TEXTUREFORMAT_RGB:
  6224. return this._gl.RGB8_SNORM;
  6225. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6226. return this._gl.R8I;
  6227. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6228. return this._gl.RG8I;
  6229. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6230. return this._gl.RGB8I;
  6231. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6232. return this._gl.RGBA8I;
  6233. default:
  6234. return this._gl.RGBA8_SNORM;
  6235. }
  6236. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  6237. switch (format) {
  6238. case Engine.TEXTUREFORMAT_RED:
  6239. return this._gl.R8;
  6240. case Engine.TEXTUREFORMAT_RG:
  6241. return this._gl.RG8;
  6242. case Engine.TEXTUREFORMAT_RGB:
  6243. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  6244. case Engine.TEXTUREFORMAT_RGBA:
  6245. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  6246. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6247. return this._gl.R8UI;
  6248. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6249. return this._gl.RG8UI;
  6250. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6251. return this._gl.RGB8UI;
  6252. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6253. return this._gl.RGBA8UI;
  6254. default:
  6255. return this._gl.RGBA8;
  6256. }
  6257. case Engine.TEXTURETYPE_SHORT:
  6258. switch (format) {
  6259. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6260. return this._gl.R16I;
  6261. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6262. return this._gl.RG16I;
  6263. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6264. return this._gl.RGB16I;
  6265. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6266. return this._gl.RGBA16I;
  6267. default:
  6268. return this._gl.RGBA16I;
  6269. }
  6270. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  6271. switch (format) {
  6272. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6273. return this._gl.R16UI;
  6274. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6275. return this._gl.RG16UI;
  6276. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6277. return this._gl.RGB16UI;
  6278. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6279. return this._gl.RGBA16UI;
  6280. default:
  6281. return this._gl.RGBA16UI;
  6282. }
  6283. case Engine.TEXTURETYPE_INT:
  6284. switch (format) {
  6285. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6286. return this._gl.R32I;
  6287. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6288. return this._gl.RG32I;
  6289. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6290. return this._gl.RGB32I;
  6291. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6292. return this._gl.RGBA32I;
  6293. default:
  6294. return this._gl.RGBA32I;
  6295. }
  6296. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  6297. switch (format) {
  6298. case Engine.TEXTUREFORMAT_RED_INTEGER:
  6299. return this._gl.R32UI;
  6300. case Engine.TEXTUREFORMAT_RG_INTEGER:
  6301. return this._gl.RG32UI;
  6302. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  6303. return this._gl.RGB32UI;
  6304. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6305. return this._gl.RGBA32UI;
  6306. default:
  6307. return this._gl.RGBA32UI;
  6308. }
  6309. case Engine.TEXTURETYPE_FLOAT:
  6310. switch (format) {
  6311. case Engine.TEXTUREFORMAT_RED:
  6312. return this._gl.R32F; // By default. Other possibility is R16F.
  6313. case Engine.TEXTUREFORMAT_RG:
  6314. return this._gl.RG32F; // By default. Other possibility is RG16F.
  6315. case Engine.TEXTUREFORMAT_RGB:
  6316. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  6317. case Engine.TEXTUREFORMAT_RGBA:
  6318. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  6319. default:
  6320. return this._gl.RGBA32F;
  6321. }
  6322. case Engine.TEXTURETYPE_HALF_FLOAT:
  6323. switch (format) {
  6324. case Engine.TEXTUREFORMAT_RED:
  6325. return this._gl.R16F;
  6326. case Engine.TEXTUREFORMAT_RG:
  6327. return this._gl.RG16F;
  6328. case Engine.TEXTUREFORMAT_RGB:
  6329. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  6330. case Engine.TEXTUREFORMAT_RGBA:
  6331. return this._gl.RGBA16F;
  6332. default:
  6333. return this._gl.RGBA16F;
  6334. }
  6335. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  6336. return this._gl.RGB565;
  6337. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  6338. return this._gl.R11F_G11F_B10F;
  6339. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  6340. return this._gl.RGB9_E5;
  6341. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  6342. return this._gl.RGBA4;
  6343. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  6344. return this._gl.RGB5_A1;
  6345. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  6346. switch (format) {
  6347. case Engine.TEXTUREFORMAT_RGBA:
  6348. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  6349. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  6350. return this._gl.RGB10_A2UI;
  6351. default:
  6352. return this._gl.RGB10_A2;
  6353. }
  6354. }
  6355. return this._gl.RGBA8;
  6356. }
  6357. /** @hidden */
  6358. public _getRGBAMultiSampleBufferFormat(type: number): number {
  6359. if (type === Engine.TEXTURETYPE_FLOAT) {
  6360. return this._gl.RGBA32F;
  6361. }
  6362. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6363. return this._gl.RGBA16F;
  6364. }
  6365. return this._gl.RGBA8;
  6366. }
  6367. /** @hidden */
  6368. 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 {
  6369. let request = Tools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  6370. this._activeRequests.push(request);
  6371. request.onCompleteObservable.add((request) => {
  6372. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  6373. });
  6374. return request;
  6375. }
  6376. /** @hidden */
  6377. public _loadFileAsync(url: string, offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean): Promise<string | ArrayBuffer> {
  6378. return new Promise((resolve, reject) => {
  6379. this._loadFile(url, (data) => {
  6380. resolve(data);
  6381. }, undefined, offlineProvider, useArrayBuffer, (request, exception) => {
  6382. reject(exception);
  6383. });
  6384. });
  6385. }
  6386. 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 {
  6387. var onload = (data: string | ArrayBuffer) => {
  6388. loadedFiles[index] = data;
  6389. (<any>loadedFiles)._internalCount++;
  6390. if ((<any>loadedFiles)._internalCount === 6) {
  6391. onfinish(loadedFiles);
  6392. }
  6393. };
  6394. const onerror = (request?: XMLHttpRequest, exception?: any) => {
  6395. if (onErrorCallBack && request) {
  6396. onErrorCallBack(request.status + " " + request.statusText, exception);
  6397. }
  6398. };
  6399. this._loadFile(url, onload, undefined, undefined, true, onerror);
  6400. }
  6401. private _cascadeLoadFiles(scene: Nullable<Scene>, onfinish: (images: (string | ArrayBuffer)[]) => void, files: string[], onError: Nullable<(message?: string, exception?: any) => void> = null): void {
  6402. var loadedFiles: (string | ArrayBuffer)[] = [];
  6403. (<any>loadedFiles)._internalCount = 0;
  6404. for (let index = 0; index < 6; index++) {
  6405. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  6406. }
  6407. }
  6408. // Statics
  6409. /**
  6410. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  6411. * @returns true if the engine can be created
  6412. * @ignorenaming
  6413. */
  6414. public static isSupported(): boolean {
  6415. try {
  6416. var tempcanvas = document.createElement("canvas");
  6417. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6418. return gl != null && !!window.WebGLRenderingContext;
  6419. } catch (e) {
  6420. return false;
  6421. }
  6422. }
  6423. }
  6424. }