babylon.engine.ts 194 KB

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