babylon.engine.ts 242 KB

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