babylon.engine.ts 231 KB

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