babylon.engine.ts 259 KB

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