babylon.engine.ts 225 KB

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