babylon.engine.ts 211 KB

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