thinEngine.ts 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324
  1. import { EngineStore } from './engineStore';
  2. import { IInternalTextureLoader } from '../Materials/Textures/internalTextureLoader';
  3. import { Effect, IEffectCreationOptions } from '../Materials/effect';
  4. import { _DevTools } from '../Misc/devTools';
  5. import { IShaderProcessor } from './Processors/iShaderProcessor';
  6. import { UniformBuffer } from '../Materials/uniformBuffer';
  7. import { Nullable, DataArray, IndicesArray } from '../types';
  8. import { EngineCapabilities } from './engineCapabilities';
  9. import { Observable } from '../Misc/observable';
  10. import { DepthCullingState } from '../States/depthCullingState';
  11. import { StencilState } from '../States/stencilState';
  12. import { AlphaState } from '../States/alphaCullingState';
  13. import { Constants } from './constants';
  14. import { InternalTexture, InternalTextureSource } from '../Materials/Textures/internalTexture';
  15. import { IViewportLike, IColor4Like } from '../Maths/math.like';
  16. import { DataBuffer } from '../Meshes/dataBuffer';
  17. import { IFileRequest } from '../Misc/fileRequest';
  18. import { Logger } from '../Misc/logger';
  19. import { DomManagement } from '../Misc/domManagement';
  20. import { WebGL2ShaderProcessor } from './WebGL/webGL2ShaderProcessors';
  21. import { WebGLDataBuffer } from '../Meshes/WebGL/webGLDataBuffer';
  22. import { IPipelineContext } from './IPipelineContext';
  23. import { WebGLPipelineContext } from './WebGL/webGLPipelineContext';
  24. import { VertexBuffer } from '../Meshes/buffer';
  25. import { InstancingAttributeInfo } from './instancingAttributeInfo';
  26. import { FileTools } from '../Misc/fileTools';
  27. import { BaseTexture } from '../Materials/Textures/baseTexture';
  28. import { IOfflineProvider } from '../Offline/IOfflineProvider';
  29. import { IEffectFallbacks } from '../Materials/iEffectFallbacks';
  30. import { IWebRequest } from '../Misc/interfaces/iWebRequest';
  31. import { CanvasGenerator } from '../Misc/canvasGenerator';
  32. declare type Observer<T> = import("../Misc/observable").Observer<T>;
  33. declare type VideoTexture = import("../Materials/Textures/videoTexture").VideoTexture;
  34. declare type RenderTargetTexture = import("../Materials/Textures/renderTargetTexture").RenderTargetTexture;
  35. declare type Texture = import("../Materials/Textures/texture").Texture;
  36. /**
  37. * Defines the interface used by objects working like Scene
  38. * @hidden
  39. */
  40. interface ISceneLike {
  41. _addPendingData(data: any): void;
  42. _removePendingData(data: any): void;
  43. offlineProvider: IOfflineProvider;
  44. }
  45. /**
  46. * Keeps track of all the buffer info used in engine.
  47. */
  48. class BufferPointer {
  49. public active: boolean;
  50. public index: number;
  51. public size: number;
  52. public type: number;
  53. public normalized: boolean;
  54. public stride: number;
  55. public offset: number;
  56. public buffer: WebGLBuffer;
  57. }
  58. /** Interface defining initialization parameters for Engine class */
  59. export interface EngineOptions extends WebGLContextAttributes {
  60. /**
  61. * Defines if the engine should no exceed a specified device ratio
  62. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  63. */
  64. limitDeviceRatio?: number;
  65. /**
  66. * Defines if webvr should be enabled automatically
  67. * @see http://doc.babylonjs.com/how_to/webvr_camera
  68. */
  69. autoEnableWebVR?: boolean;
  70. /**
  71. * Defines if webgl2 should be turned off even if supported
  72. * @see http://doc.babylonjs.com/features/webgl2
  73. */
  74. disableWebGL2Support?: boolean;
  75. /**
  76. * Defines if webaudio should be initialized as well
  77. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  78. */
  79. audioEngine?: boolean;
  80. /**
  81. * Defines if animations should run using a deterministic lock step
  82. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  83. */
  84. deterministicLockstep?: boolean;
  85. /** Defines the maximum steps to use with deterministic lock step mode */
  86. lockstepMaxSteps?: number;
  87. /** Defines the seconds between each deterministic lock step */
  88. timeStep?: number;
  89. /**
  90. * Defines that engine should ignore context lost events
  91. * If this event happens when this parameter is true, you will have to reload the page to restore rendering
  92. */
  93. doNotHandleContextLost?: boolean;
  94. /**
  95. * Defines that engine should ignore modifying touch action attribute and style
  96. * If not handle, you might need to set it up on your side for expected touch devices behavior.
  97. */
  98. doNotHandleTouchAction?: boolean;
  99. /**
  100. * Defines that engine should compile shaders with high precision floats (if supported). True by default
  101. */
  102. useHighPrecisionFloats?: boolean;
  103. }
  104. /**
  105. * The base engine class (root of all engines)
  106. */
  107. export class ThinEngine {
  108. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  109. public static ExceptionList = [
  110. { key: "Chrome\/63\.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  111. { key: "Firefox\/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  112. { key: "Firefox\/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  113. { key: "Chrome\/72.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
  114. { key: "Chrome\/73.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
  115. { key: "Chrome\/74.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
  116. { key: "Mac OS.+Chrome\/71", capture: null, captureConstraint: null, targets: ["vao"] },
  117. { key: "Mac OS.+Chrome\/72", capture: null, captureConstraint: null, targets: ["vao"] }
  118. ];
  119. /** @hidden */
  120. public static _TextureLoaders: IInternalTextureLoader[] = [];
  121. /**
  122. * Returns the current npm package of the sdk
  123. */
  124. // Not mixed with Version for tooling purpose.
  125. public static get NpmPackage(): string {
  126. return "babylonjs@4.1.0-beta.11";
  127. }
  128. /**
  129. * Returns the current version of the framework
  130. */
  131. public static get Version(): string {
  132. return "4.1.0-beta.11";
  133. }
  134. /**
  135. * Returns a string describing the current engine
  136. */
  137. public get description(): string {
  138. let description = "WebGL" + this.webGLVersion;
  139. if (this._caps.parallelShaderCompile) {
  140. description += " - Parallel shader compilation";
  141. }
  142. return description;
  143. }
  144. // Updatable statics so stick with vars here
  145. /**
  146. * Gets or sets the epsilon value used by collision engine
  147. */
  148. public static CollisionsEpsilon = 0.001;
  149. /**
  150. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  151. */
  152. public static get ShadersRepository(): string {
  153. return Effect.ShadersRepository;
  154. }
  155. public static set ShadersRepository(value: string) {
  156. Effect.ShadersRepository = value;
  157. }
  158. /**
  159. * Gets or sets the textures that the engine should not attempt to load as compressed
  160. */
  161. protected _excludedCompressedTextures: string[] = [];
  162. /**
  163. * Filters the compressed texture formats to only include
  164. * files that are not included in the skippable list
  165. *
  166. * @param url the current extension
  167. * @param textureFormatInUse the current compressed texture format
  168. * @returns "format" string
  169. */
  170. public excludedCompressedTextureFormats(url: Nullable<string>, textureFormatInUse: Nullable<string>): Nullable<string> {
  171. const skipCompression = (): boolean => {
  172. return this._excludedCompressedTextures.some((entry) => {
  173. const strRegExPattern: string = '\\b' + entry + '\\b';
  174. return (url && (url === entry || url.match(new RegExp(strRegExPattern, 'g'))));
  175. });
  176. };
  177. return skipCompression() ? null : textureFormatInUse;
  178. }
  179. // Public members
  180. /** @hidden */
  181. public _shaderProcessor: IShaderProcessor;
  182. /**
  183. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  184. */
  185. public forcePOTTextures = false;
  186. /**
  187. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  188. */
  189. public isFullscreen = false;
  190. /**
  191. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  192. */
  193. public cullBackFaces = true;
  194. /**
  195. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  196. */
  197. public renderEvenInBackground = true;
  198. /**
  199. * Gets or sets a boolean indicating that cache can be kept between frames
  200. */
  201. public preventCacheWipeBetweenFrames = false;
  202. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  203. public validateShaderPrograms = false;
  204. /**
  205. * Gets or sets a boolean indicating if depth buffer should be reverse, going from far to near.
  206. * This can provide greater z depth for distant objects.
  207. */
  208. public useReverseDepthBuffer = false;
  209. // Uniform buffers list
  210. /**
  211. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  212. */
  213. public disableUniformBuffers = false;
  214. /** @hidden */
  215. public _uniformBuffers = new Array<UniformBuffer>();
  216. /**
  217. * Gets a boolean indicating that the engine supports uniform buffers
  218. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  219. */
  220. public get supportsUniformBuffers(): boolean {
  221. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  222. }
  223. // Private Members
  224. /** @hidden */
  225. public _gl: WebGLRenderingContext;
  226. protected _renderingCanvas: Nullable<HTMLCanvasElement>;
  227. protected _windowIsBackground = false;
  228. protected _webGLVersion = 1.0;
  229. protected _creationOptions: EngineOptions;
  230. protected _highPrecisionShadersAllowed = true;
  231. /** @hidden */
  232. public get _shouldUseHighPrecisionShader(): boolean {
  233. return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed);
  234. }
  235. /**
  236. * Gets a boolean indicating that only power of 2 textures are supported
  237. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  238. */
  239. public get needPOTTextures(): boolean {
  240. return this._webGLVersion < 2 || this.forcePOTTextures;
  241. }
  242. /** @hidden */
  243. public _badOS = false;
  244. /** @hidden */
  245. public _badDesktopOS = false;
  246. private _hardwareScalingLevel: number;
  247. /** @hidden */
  248. public _caps: EngineCapabilities;
  249. private _isStencilEnable: boolean;
  250. private _glVersion: string;
  251. private _glRenderer: string;
  252. private _glVendor: string;
  253. /** @hidden */
  254. public _videoTextureSupported: boolean;
  255. protected _renderingQueueLaunched = false;
  256. protected _activeRenderLoops = new Array<() => void>();
  257. // Lost context
  258. /**
  259. * Observable signaled when a context lost event is raised
  260. */
  261. public onContextLostObservable = new Observable<ThinEngine>();
  262. /**
  263. * Observable signaled when a context restored event is raised
  264. */
  265. public onContextRestoredObservable = new Observable<ThinEngine>();
  266. private _onContextLost: (evt: Event) => void;
  267. private _onContextRestored: (evt: Event) => void;
  268. protected _contextWasLost = false;
  269. /** @hidden */
  270. public _doNotHandleContextLost = false;
  271. /**
  272. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  273. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  274. */
  275. public get doNotHandleContextLost(): boolean {
  276. return this._doNotHandleContextLost;
  277. }
  278. public set doNotHandleContextLost(value: boolean) {
  279. this._doNotHandleContextLost = value;
  280. }
  281. /**
  282. * Gets or sets a boolean indicating that vertex array object must be disabled even if they are supported
  283. */
  284. public disableVertexArrayObjects = false;
  285. // States
  286. /** @hidden */
  287. protected _colorWrite = true;
  288. /** @hidden */
  289. protected _colorWriteChanged = true;
  290. /** @hidden */
  291. protected _depthCullingState = new DepthCullingState();
  292. /** @hidden */
  293. protected _stencilState = new StencilState();
  294. /** @hidden */
  295. public _alphaState = new AlphaState();
  296. /** @hidden */
  297. public _alphaMode = Constants.ALPHA_ADD;
  298. /** @hidden */
  299. public _alphaEquation = Constants.ALPHA_DISABLE;
  300. // Cache
  301. /** @hidden */
  302. public _internalTexturesCache = new Array<InternalTexture>();
  303. /** @hidden */
  304. protected _activeChannel = 0;
  305. private _currentTextureChannel = -1;
  306. /** @hidden */
  307. protected _boundTexturesCache: { [key: string]: Nullable<InternalTexture> } = {};
  308. /** @hidden */
  309. protected _currentEffect: Nullable<Effect>;
  310. /** @hidden */
  311. protected _currentProgram: Nullable<WebGLProgram>;
  312. private _compiledEffects: { [key: string]: Effect } = {};
  313. private _vertexAttribArraysEnabled: boolean[] = [];
  314. /** @hidden */
  315. protected _cachedViewport: Nullable<IViewportLike>;
  316. private _cachedVertexArrayObject: Nullable<WebGLVertexArrayObject>;
  317. /** @hidden */
  318. protected _cachedVertexBuffers: any;
  319. /** @hidden */
  320. protected _cachedIndexBuffer: Nullable<DataBuffer>;
  321. /** @hidden */
  322. protected _cachedEffectForVertexBuffers: Nullable<Effect>;
  323. /** @hidden */
  324. public _currentRenderTarget: Nullable<InternalTexture>;
  325. private _uintIndicesCurrentlySet = false;
  326. protected _currentBoundBuffer = new Array<Nullable<WebGLBuffer>>();
  327. /** @hidden */
  328. protected _currentFramebuffer: Nullable<WebGLFramebuffer> = null;
  329. private _currentBufferPointers = new Array<BufferPointer>();
  330. private _currentInstanceLocations = new Array<number>();
  331. private _currentInstanceBuffers = new Array<DataBuffer>();
  332. private _textureUnits: Int32Array;
  333. /** @hidden */
  334. public _workingCanvas: Nullable<HTMLCanvasElement | OffscreenCanvas>;
  335. /** @hidden */
  336. public _workingContext: Nullable<CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D>;
  337. /** @hidden */
  338. public _boundRenderFunction: any;
  339. private _vaoRecordInProgress = false;
  340. private _mustWipeVertexAttributes = false;
  341. private _emptyTexture: Nullable<InternalTexture>;
  342. private _emptyCubeTexture: Nullable<InternalTexture>;
  343. private _emptyTexture3D: Nullable<InternalTexture>;
  344. private _emptyTexture2DArray: Nullable<InternalTexture>;
  345. /** @hidden */
  346. public _frameHandler: number;
  347. private _nextFreeTextureSlots = new Array<number>();
  348. private _maxSimultaneousTextures = 0;
  349. private _activeRequests = new Array<IFileRequest>();
  350. // Hardware supported Compressed Textures
  351. protected _texturesSupported = new Array<string>();
  352. /** @hidden */
  353. public _textureFormatInUse: Nullable<string>;
  354. protected get _supportsHardwareTextureRescaling() {
  355. return false;
  356. }
  357. /**
  358. * Gets the list of texture formats supported
  359. */
  360. public get texturesSupported(): Array<string> {
  361. return this._texturesSupported;
  362. }
  363. /**
  364. * Gets the list of texture formats in use
  365. */
  366. public get textureFormatInUse(): Nullable<string> {
  367. return this._textureFormatInUse;
  368. }
  369. /**
  370. * Gets the current viewport
  371. */
  372. public get currentViewport(): Nullable<IViewportLike> {
  373. return this._cachedViewport;
  374. }
  375. /**
  376. * Gets the default empty texture
  377. */
  378. public get emptyTexture(): InternalTexture {
  379. if (!this._emptyTexture) {
  380. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  381. }
  382. return this._emptyTexture;
  383. }
  384. /**
  385. * Gets the default empty 3D texture
  386. */
  387. public get emptyTexture3D(): InternalTexture {
  388. if (!this._emptyTexture3D) {
  389. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  390. }
  391. return this._emptyTexture3D;
  392. }
  393. /**
  394. * Gets the default empty 2D array texture
  395. */
  396. public get emptyTexture2DArray(): InternalTexture {
  397. if (!this._emptyTexture2DArray) {
  398. this._emptyTexture2DArray = this.createRawTexture2DArray(new Uint8Array(4), 1, 1, 1, Constants.TEXTUREFORMAT_RGBA, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  399. }
  400. return this._emptyTexture2DArray;
  401. }
  402. /**
  403. * Gets the default empty cube texture
  404. */
  405. public get emptyCubeTexture(): InternalTexture {
  406. if (!this._emptyCubeTexture) {
  407. var faceData = new Uint8Array(4);
  408. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  409. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Constants.TEXTUREFORMAT_RGBA, Constants.TEXTURETYPE_UNSIGNED_INT, false, false, Constants.TEXTURE_NEAREST_SAMPLINGMODE);
  410. }
  411. return this._emptyCubeTexture;
  412. }
  413. /**
  414. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  415. */
  416. public readonly premultipliedAlpha: boolean = true;
  417. /**
  418. * Observable event triggered before each texture is initialized
  419. */
  420. public onBeforeTextureInitObservable = new Observable<Texture>();
  421. /**
  422. * Creates a new engine
  423. * @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
  424. * @param antialias defines enable antialiasing (default: false)
  425. * @param options defines further options to be sent to the getContext() function
  426. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  427. */
  428. constructor(canvasOrContext: Nullable<HTMLCanvasElement | WebGLRenderingContext | WebGL2RenderingContext>, antialias?: boolean, options?: EngineOptions, adaptToDeviceRatio: boolean = false) {
  429. let canvas: Nullable<HTMLCanvasElement> = null;
  430. if (!canvasOrContext) {
  431. return;
  432. }
  433. options = options || {};
  434. if ((<HTMLCanvasElement>canvasOrContext).getContext) {
  435. canvas = <HTMLCanvasElement>canvasOrContext;
  436. this._renderingCanvas = canvas;
  437. if (antialias != null) {
  438. options.antialias = antialias;
  439. }
  440. if (options.deterministicLockstep === undefined) {
  441. options.deterministicLockstep = false;
  442. }
  443. if (options.lockstepMaxSteps === undefined) {
  444. options.lockstepMaxSteps = 4;
  445. }
  446. if (options.timeStep === undefined) {
  447. options.timeStep = 1 / 60;
  448. }
  449. if (options.preserveDrawingBuffer === undefined) {
  450. options.preserveDrawingBuffer = false;
  451. }
  452. if (options.audioEngine === undefined) {
  453. options.audioEngine = true;
  454. }
  455. if (options.stencil === undefined) {
  456. options.stencil = true;
  457. }
  458. if (options.premultipliedAlpha === false) {
  459. this.premultipliedAlpha = false;
  460. }
  461. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  462. // Exceptions
  463. if (navigator && navigator.userAgent) {
  464. let ua = navigator.userAgent;
  465. for (var exception of ThinEngine.ExceptionList) {
  466. let key = exception.key;
  467. let targets = exception.targets;
  468. let check = new RegExp(key);
  469. if (check.test(ua)) {
  470. if (exception.capture && exception.captureConstraint) {
  471. let capture = exception.capture;
  472. let constraint = exception.captureConstraint;
  473. let regex = new RegExp(capture);
  474. let matches = regex.exec(ua);
  475. if (matches && matches.length > 0) {
  476. let capturedValue = parseInt(matches[matches.length - 1]);
  477. if (capturedValue >= constraint) {
  478. continue;
  479. }
  480. }
  481. }
  482. for (var target of targets) {
  483. switch (target) {
  484. case "uniformBuffer":
  485. this.disableUniformBuffers = true;
  486. break;
  487. case "vao":
  488. this.disableVertexArrayObjects = true;
  489. break;
  490. }
  491. }
  492. }
  493. }
  494. }
  495. // Context lost
  496. if (!this._doNotHandleContextLost) {
  497. this._onContextLost = (evt: Event) => {
  498. evt.preventDefault();
  499. this._contextWasLost = true;
  500. Logger.Warn("WebGL context lost.");
  501. this.onContextLostObservable.notifyObservers(this);
  502. };
  503. this._onContextRestored = () => {
  504. // Adding a timeout to avoid race condition at browser level
  505. setTimeout(() => {
  506. // Rebuild gl context
  507. this._initGLContext();
  508. // Rebuild effects
  509. this._rebuildEffects();
  510. // Rebuild textures
  511. this._rebuildInternalTextures();
  512. // Rebuild buffers
  513. this._rebuildBuffers();
  514. // Cache
  515. this.wipeCaches(true);
  516. Logger.Warn("WebGL context successfully restored.");
  517. this.onContextRestoredObservable.notifyObservers(this);
  518. this._contextWasLost = false;
  519. }, 0);
  520. };
  521. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  522. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  523. options.powerPreference = "high-performance";
  524. }
  525. // GL
  526. if (!options.disableWebGL2Support) {
  527. try {
  528. this._gl = <any>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  529. if (this._gl) {
  530. this._webGLVersion = 2.0;
  531. // Prevent weird browsers to lie :-)
  532. if (!this._gl.deleteQuery) {
  533. this._webGLVersion = 1.0;
  534. }
  535. }
  536. } catch (e) {
  537. // Do nothing
  538. }
  539. }
  540. if (!this._gl) {
  541. if (!canvas) {
  542. throw new Error("The provided canvas is null or undefined.");
  543. }
  544. try {
  545. this._gl = <WebGLRenderingContext>(canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  546. } catch (e) {
  547. throw new Error("WebGL not supported");
  548. }
  549. }
  550. if (!this._gl) {
  551. throw new Error("WebGL not supported");
  552. }
  553. } else {
  554. this._gl = <WebGLRenderingContext>canvasOrContext;
  555. this._renderingCanvas = this._gl.canvas as HTMLCanvasElement;
  556. if (this._gl.renderbufferStorageMultisample) {
  557. this._webGLVersion = 2.0;
  558. }
  559. const attributes = this._gl.getContextAttributes();
  560. if (attributes) {
  561. options.stencil = attributes.stencil;
  562. }
  563. }
  564. // Ensures a consistent color space unpacking of textures cross browser.
  565. this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
  566. if (options.useHighPrecisionFloats !== undefined) {
  567. this._highPrecisionShadersAllowed = options.useHighPrecisionFloats;
  568. }
  569. // Viewport
  570. const devicePixelRatio = DomManagement.IsWindowObjectExist() ? (window.devicePixelRatio || 1.0) : 1.0;
  571. var limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
  572. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0;
  573. this.resize();
  574. this._isStencilEnable = options.stencil ? true : false;
  575. this._initGLContext();
  576. // Prepare buffer pointers
  577. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  578. this._currentBufferPointers[i] = new BufferPointer();
  579. }
  580. // Shader processor
  581. if (this.webGLVersion > 1) {
  582. this._shaderProcessor = new WebGL2ShaderProcessor();
  583. }
  584. // Detect if we are running on a faulty buggy OS.
  585. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  586. // Detect if we are running on a faulty buggy desktop OS.
  587. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  588. this._creationOptions = options;
  589. console.log(`Babylon.js v${ThinEngine.Version} - ${this.description}`);
  590. }
  591. private _rebuildInternalTextures(): void {
  592. let currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  593. for (var internalTexture of currentState) {
  594. internalTexture._rebuild();
  595. }
  596. }
  597. private _rebuildEffects(): void {
  598. for (var key in this._compiledEffects) {
  599. let effect = <Effect>this._compiledEffects[key];
  600. effect._prepareEffect();
  601. }
  602. Effect.ResetCache();
  603. }
  604. /**
  605. * Gets a boolean indicating if all created effects are ready
  606. * @returns true if all effects are ready
  607. */
  608. public areAllEffectsReady(): boolean {
  609. for (var key in this._compiledEffects) {
  610. let effect = <Effect>this._compiledEffects[key];
  611. if (!effect.isReady()) {
  612. return false;
  613. }
  614. }
  615. return true;
  616. }
  617. protected _rebuildBuffers(): void {
  618. // Uniforms
  619. for (var uniformBuffer of this._uniformBuffers) {
  620. uniformBuffer._rebuild();
  621. }
  622. }
  623. private _initGLContext(): void {
  624. // Caps
  625. this._caps = {
  626. maxTexturesImageUnits: this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),
  627. maxCombinedTexturesImageUnits: this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),
  628. maxVertexTextureImageUnits: this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
  629. maxTextureSize: this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),
  630. maxSamples: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_SAMPLES) : 1,
  631. maxCubemapTextureSize: this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),
  632. maxRenderTextureSize: this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),
  633. maxVertexAttribs: this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),
  634. maxVaryingVectors: this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),
  635. maxFragmentUniformVectors: this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),
  636. maxVertexUniformVectors: this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),
  637. parallelShaderCompile: this._gl.getExtension('KHR_parallel_shader_compile'),
  638. standardDerivatives: this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null),
  639. maxAnisotropy: 1,
  640. astc: this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc'),
  641. s3tc: this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'),
  642. pvrtc: this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'),
  643. etc1: this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'),
  644. etc2: this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  645. this._gl.getExtension('WEBGL_compressed_texture_es3_0'), // also a requirement of OpenGL ES 3
  646. textureAnisotropicFilterExtension: this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic'),
  647. uintIndices: this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null,
  648. fragmentDepthSupported: this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null,
  649. highPrecisionShaderSupported: false,
  650. timerQuery: this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query"),
  651. canUseTimestampForTimerQuery: false,
  652. drawBuffersExtension: false,
  653. maxMSAASamples: 1,
  654. colorBufferFloat: this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float'),
  655. textureFloat: (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false,
  656. textureHalfFloat: (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false,
  657. textureHalfFloatRender: false,
  658. textureFloatLinearFiltering: false,
  659. textureFloatRender: false,
  660. textureHalfFloatLinearFiltering: false,
  661. vertexArrayObject: false,
  662. instancedArrays: false,
  663. textureLOD: (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false,
  664. blendMinMax: false,
  665. multiview: this._gl.getExtension('OVR_multiview2'),
  666. oculusMultiview: this._gl.getExtension('OCULUS_multiview'),
  667. depthTextureExtension: false
  668. };
  669. // Infos
  670. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  671. var rendererInfo: any = this._gl.getExtension("WEBGL_debug_renderer_info");
  672. if (rendererInfo != null) {
  673. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  674. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  675. }
  676. if (!this._glVendor) {
  677. this._glVendor = "Unknown vendor";
  678. }
  679. if (!this._glRenderer) {
  680. this._glRenderer = "Unknown renderer";
  681. }
  682. // Constants
  683. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  684. if (this._gl.RGBA16F !== 0x881A) {
  685. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  686. }
  687. if (this._gl.RGBA32F !== 0x8814) {
  688. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  689. }
  690. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  691. this._gl.DEPTH24_STENCIL8 = 35056;
  692. }
  693. // Extensions
  694. if (this._caps.timerQuery) {
  695. if (this._webGLVersion === 1) {
  696. this._gl.getQuery = (<any>this._caps.timerQuery).getQueryEXT.bind(this._caps.timerQuery);
  697. }
  698. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  699. }
  700. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  701. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  702. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  703. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  704. // Checks if some of the format renders first to allow the use of webgl inspector.
  705. if (this._webGLVersion > 1) {
  706. this._gl.HALF_FLOAT_OES = 0x140B;
  707. }
  708. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  709. // Draw buffers
  710. if (this._webGLVersion > 1) {
  711. this._caps.drawBuffersExtension = true;
  712. this._caps.maxMSAASamples = this._gl.getParameter(this._gl.MAX_SAMPLES);
  713. } else {
  714. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  715. if (drawBuffersExtension !== null) {
  716. this._caps.drawBuffersExtension = true;
  717. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  718. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  719. for (var i = 0; i < 16; i++) {
  720. (<any>this._gl)["COLOR_ATTACHMENT" + i + "_WEBGL"] = (<any>drawBuffersExtension)["COLOR_ATTACHMENT" + i + "_WEBGL"];
  721. }
  722. }
  723. }
  724. // Depth Texture
  725. if (this._webGLVersion > 1) {
  726. this._caps.depthTextureExtension = true;
  727. } else {
  728. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  729. if (depthTextureExtension != null) {
  730. this._caps.depthTextureExtension = true;
  731. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  732. }
  733. }
  734. // Vertex array object
  735. if (this.disableVertexArrayObjects) {
  736. this._caps.vertexArrayObject = false;
  737. } else if (this._webGLVersion > 1) {
  738. this._caps.vertexArrayObject = true;
  739. } else {
  740. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  741. if (vertexArrayObjectExtension != null) {
  742. this._caps.vertexArrayObject = true;
  743. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  744. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  745. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  746. }
  747. }
  748. // Instances count
  749. if (this._webGLVersion > 1) {
  750. this._caps.instancedArrays = true;
  751. } else {
  752. var instanceExtension = <ANGLE_instanced_arrays>this._gl.getExtension('ANGLE_instanced_arrays');
  753. if (instanceExtension != null) {
  754. this._caps.instancedArrays = true;
  755. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  756. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  757. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  758. } else {
  759. this._caps.instancedArrays = false;
  760. }
  761. }
  762. // Intelligently add supported compressed formats in order to check for.
  763. // Check for ASTC support first as it is most powerful and to be very cross platform.
  764. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  765. // Likely no hardware which supports both PVR & DXT, so order matters little.
  766. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  767. if (this._caps.astc) { this.texturesSupported.push('-astc.ktx'); }
  768. if (this._caps.s3tc) { this.texturesSupported.push('-dxt.ktx'); }
  769. if (this._caps.pvrtc) { this.texturesSupported.push('-pvrtc.ktx'); }
  770. if (this._caps.etc2) { this.texturesSupported.push('-etc2.ktx'); }
  771. if (this._caps.etc1) { this.texturesSupported.push('-etc1.ktx'); }
  772. if (this._gl.getShaderPrecisionFormat) {
  773. var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
  774. var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  775. if (vertex_highp && fragment_highp) {
  776. this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
  777. }
  778. }
  779. if (this._webGLVersion > 1) {
  780. this._caps.blendMinMax = true;
  781. }
  782. else {
  783. const blendMinMaxExtension = this._gl.getExtension('EXT_blend_minmax');
  784. if (blendMinMaxExtension != null) {
  785. this._caps.blendMinMax = true;
  786. this._gl.MAX = blendMinMaxExtension.MAX_EXT;
  787. this._gl.MIN = blendMinMaxExtension.MIN_EXT;
  788. }
  789. }
  790. // Depth buffer
  791. this._depthCullingState.depthTest = true;
  792. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  793. this._depthCullingState.depthMask = true;
  794. // Texture maps
  795. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  796. for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  797. this._nextFreeTextureSlots.push(slot);
  798. }
  799. }
  800. /**
  801. * Gets version of the current webGL context
  802. */
  803. public get webGLVersion(): number {
  804. return this._webGLVersion;
  805. }
  806. /**
  807. * Gets a string idenfifying the name of the class
  808. * @returns "Engine" string
  809. */
  810. public getClassName(): string {
  811. return "ThinEngine";
  812. }
  813. /**
  814. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  815. */
  816. public get isStencilEnable(): boolean {
  817. return this._isStencilEnable;
  818. }
  819. /** @hidden */
  820. public _prepareWorkingCanvas(): void {
  821. if (this._workingCanvas) {
  822. return;
  823. }
  824. this._workingCanvas = CanvasGenerator.CreateCanvas(1, 1);
  825. let context = this._workingCanvas.getContext("2d");
  826. if (context) {
  827. this._workingContext = context;
  828. }
  829. }
  830. /**
  831. * Reset the texture cache to empty state
  832. */
  833. public resetTextureCache() {
  834. for (var key in this._boundTexturesCache) {
  835. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  836. continue;
  837. }
  838. this._boundTexturesCache[key] = null;
  839. }
  840. this._currentTextureChannel = -1;
  841. }
  842. /**
  843. * Gets an object containing information about the current webGL context
  844. * @returns an object containing the vender, the renderer and the version of the current webGL context
  845. */
  846. public getGlInfo() {
  847. return {
  848. vendor: this._glVendor,
  849. renderer: this._glRenderer,
  850. version: this._glVersion
  851. };
  852. }
  853. /**
  854. * Defines the hardware scaling level.
  855. * By default the hardware scaling level is computed from the window device ratio.
  856. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  857. * @param level defines the level to use
  858. */
  859. public setHardwareScalingLevel(level: number): void {
  860. this._hardwareScalingLevel = level;
  861. this.resize();
  862. }
  863. /**
  864. * Gets the current hardware scaling level.
  865. * By default the hardware scaling level is computed from the window device ratio.
  866. * if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
  867. * @returns a number indicating the current hardware scaling level
  868. */
  869. public getHardwareScalingLevel(): number {
  870. return this._hardwareScalingLevel;
  871. }
  872. /**
  873. * Gets the list of loaded textures
  874. * @returns an array containing all loaded textures
  875. */
  876. public getLoadedTexturesCache(): InternalTexture[] {
  877. return this._internalTexturesCache;
  878. }
  879. /**
  880. * Gets the object containing all engine capabilities
  881. * @returns the EngineCapabilities object
  882. */
  883. public getCaps(): EngineCapabilities {
  884. return this._caps;
  885. }
  886. /**
  887. * stop executing a render loop function and remove it from the execution array
  888. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  889. */
  890. public stopRenderLoop(renderFunction?: () => void): void {
  891. if (!renderFunction) {
  892. this._activeRenderLoops = [];
  893. return;
  894. }
  895. var index = this._activeRenderLoops.indexOf(renderFunction);
  896. if (index >= 0) {
  897. this._activeRenderLoops.splice(index, 1);
  898. }
  899. }
  900. /** @hidden */
  901. public _renderLoop(): void {
  902. if (!this._contextWasLost) {
  903. var shouldRender = true;
  904. if (!this.renderEvenInBackground && this._windowIsBackground) {
  905. shouldRender = false;
  906. }
  907. if (shouldRender) {
  908. // Start new frame
  909. this.beginFrame();
  910. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  911. var renderFunction = this._activeRenderLoops[index];
  912. renderFunction();
  913. }
  914. // Present
  915. this.endFrame();
  916. }
  917. }
  918. if (this._activeRenderLoops.length > 0) {
  919. this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
  920. } else {
  921. this._renderingQueueLaunched = false;
  922. }
  923. }
  924. /**
  925. * Gets the HTML canvas attached with the current webGL context
  926. * @returns a HTML canvas
  927. */
  928. public getRenderingCanvas(): Nullable<HTMLCanvasElement> {
  929. return this._renderingCanvas;
  930. }
  931. /**
  932. * Gets host window
  933. * @returns the host window object
  934. */
  935. public getHostWindow(): Nullable<Window> {
  936. if (!DomManagement.IsWindowObjectExist()) {
  937. return null;
  938. }
  939. if (this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView) {
  940. return this._renderingCanvas.ownerDocument.defaultView;
  941. }
  942. return window;
  943. }
  944. /**
  945. * Gets the current render width
  946. * @param useScreen defines if screen size must be used (or the current render target if any)
  947. * @returns a number defining the current render width
  948. */
  949. public getRenderWidth(useScreen = false): number {
  950. if (!useScreen && this._currentRenderTarget) {
  951. return this._currentRenderTarget.width;
  952. }
  953. return this._gl.drawingBufferWidth;
  954. }
  955. /**
  956. * Gets the current render height
  957. * @param useScreen defines if screen size must be used (or the current render target if any)
  958. * @returns a number defining the current render height
  959. */
  960. public getRenderHeight(useScreen = false): number {
  961. if (!useScreen && this._currentRenderTarget) {
  962. return this._currentRenderTarget.height;
  963. }
  964. return this._gl.drawingBufferHeight;
  965. }
  966. /**
  967. * Can be used to override the current requestAnimationFrame requester.
  968. * @hidden
  969. */
  970. protected _queueNewFrame(bindedRenderFunction: any, requester?: any): number {
  971. return ThinEngine.QueueNewFrame(bindedRenderFunction, requester);
  972. }
  973. /**
  974. * Register and execute a render loop. The engine can have more than one render function
  975. * @param renderFunction defines the function to continuously execute
  976. */
  977. public runRenderLoop(renderFunction: () => void): void {
  978. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  979. return;
  980. }
  981. this._activeRenderLoops.push(renderFunction);
  982. if (!this._renderingQueueLaunched) {
  983. this._renderingQueueLaunched = true;
  984. this._boundRenderFunction = this._renderLoop.bind(this);
  985. this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
  986. }
  987. }
  988. /**
  989. * Clear the current render buffer or the current render target (if any is set up)
  990. * @param color defines the color to use
  991. * @param backBuffer defines if the back buffer must be cleared
  992. * @param depth defines if the depth buffer must be cleared
  993. * @param stencil defines if the stencil buffer must be cleared
  994. */
  995. public clear(color: Nullable<IColor4Like>, backBuffer: boolean, depth: boolean, stencil: boolean = false): void {
  996. this.applyStates();
  997. var mode = 0;
  998. if (backBuffer && color) {
  999. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  1000. mode |= this._gl.COLOR_BUFFER_BIT;
  1001. }
  1002. if (depth) {
  1003. if (this.useReverseDepthBuffer) {
  1004. this._depthCullingState.depthFunc = this._gl.GREATER;
  1005. this._gl.clearDepth(0.0);
  1006. } else {
  1007. this._gl.clearDepth(1.0);
  1008. }
  1009. mode |= this._gl.DEPTH_BUFFER_BIT;
  1010. }
  1011. if (stencil) {
  1012. this._gl.clearStencil(0);
  1013. mode |= this._gl.STENCIL_BUFFER_BIT;
  1014. }
  1015. this._gl.clear(mode);
  1016. }
  1017. private _viewportCached = { x: 0, y: 0, z: 0, w: 0 };
  1018. /** @hidden */
  1019. public _viewport(x: number, y: number, width: number, height: number): void {
  1020. if (x !== this._viewportCached.x ||
  1021. y !== this._viewportCached.y ||
  1022. width !== this._viewportCached.z ||
  1023. height !== this._viewportCached.w) {
  1024. this._viewportCached.x = x;
  1025. this._viewportCached.y = y;
  1026. this._viewportCached.z = width;
  1027. this._viewportCached.w = height;
  1028. this._gl.viewport(x, y, width, height);
  1029. }
  1030. }
  1031. /**
  1032. * Set the WebGL's viewport
  1033. * @param viewport defines the viewport element to be used
  1034. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  1035. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  1036. */
  1037. public setViewport(viewport: IViewportLike, requiredWidth?: number, requiredHeight?: number): void {
  1038. var width = requiredWidth || this.getRenderWidth();
  1039. var height = requiredHeight || this.getRenderHeight();
  1040. var x = viewport.x || 0;
  1041. var y = viewport.y || 0;
  1042. this._cachedViewport = viewport;
  1043. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  1044. }
  1045. /**
  1046. * Begin a new frame
  1047. */
  1048. public beginFrame(): void {
  1049. }
  1050. /**
  1051. * Enf the current frame
  1052. */
  1053. public endFrame(): void {
  1054. // Force a flush in case we are using a bad OS.
  1055. if (this._badOS) {
  1056. this.flushFramebuffer();
  1057. }
  1058. }
  1059. /**
  1060. * Resize the view according to the canvas' size
  1061. */
  1062. public resize(): void {
  1063. let width: number;
  1064. let height: number;
  1065. if (DomManagement.IsWindowObjectExist()) {
  1066. width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  1067. height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  1068. } else {
  1069. width = this._renderingCanvas ? this._renderingCanvas.width : 100;
  1070. height = this._renderingCanvas ? this._renderingCanvas.height : 100;
  1071. }
  1072. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  1073. }
  1074. /**
  1075. * Force a specific size of the canvas
  1076. * @param width defines the new canvas' width
  1077. * @param height defines the new canvas' height
  1078. */
  1079. public setSize(width: number, height: number): void {
  1080. if (!this._renderingCanvas) {
  1081. return;
  1082. }
  1083. width = width | 0;
  1084. height = height | 0;
  1085. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  1086. return;
  1087. }
  1088. this._renderingCanvas.width = width;
  1089. this._renderingCanvas.height = height;
  1090. }
  1091. /**
  1092. * Binds the frame buffer to the specified texture.
  1093. * @param texture The texture to render to or null for the default canvas
  1094. * @param faceIndex The face of the texture to render to in case of cube texture
  1095. * @param requiredWidth The width of the target to render to
  1096. * @param requiredHeight The height of the target to render to
  1097. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  1098. * @param depthStencilTexture The depth stencil texture to use to render
  1099. * @param lodLevel defines le lod level to bind to the frame buffer
  1100. */
  1101. public bindFramebuffer(texture: InternalTexture, faceIndex?: number, requiredWidth?: number, requiredHeight?: number, forceFullscreenViewport?: boolean, depthStencilTexture?: InternalTexture, lodLevel = 0): void {
  1102. if (this._currentRenderTarget) {
  1103. this.unBindFramebuffer(this._currentRenderTarget);
  1104. }
  1105. this._currentRenderTarget = texture;
  1106. this._bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  1107. var gl = this._gl;
  1108. if (texture.isCube) {
  1109. if (faceIndex === undefined) {
  1110. faceIndex = 0;
  1111. }
  1112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  1113. if (depthStencilTexture) {
  1114. if (depthStencilTexture._generateStencilBuffer) {
  1115. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1116. }
  1117. else {
  1118. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  1119. }
  1120. }
  1121. }
  1122. if (this._cachedViewport && !forceFullscreenViewport) {
  1123. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  1124. } else {
  1125. if (!requiredWidth) {
  1126. requiredWidth = texture.width;
  1127. if (lodLevel) {
  1128. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  1129. }
  1130. }
  1131. if (!requiredHeight) {
  1132. requiredHeight = texture.height;
  1133. if (lodLevel) {
  1134. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  1135. }
  1136. }
  1137. this._viewport(0, 0, requiredWidth, requiredHeight);
  1138. }
  1139. this.wipeCaches();
  1140. }
  1141. /** @hidden */
  1142. public _bindUnboundFramebuffer(framebuffer: Nullable<WebGLFramebuffer>) {
  1143. if (this._currentFramebuffer !== framebuffer) {
  1144. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  1145. this._currentFramebuffer = framebuffer;
  1146. }
  1147. }
  1148. /**
  1149. * Unbind the current render target texture from the webGL context
  1150. * @param texture defines the render target texture to unbind
  1151. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  1152. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  1153. */
  1154. public unBindFramebuffer(texture: InternalTexture, disableGenerateMipMaps = false, onBeforeUnbind?: () => void): void {
  1155. this._currentRenderTarget = null;
  1156. // If MSAA, we need to bitblt back to main texture
  1157. var gl = this._gl;
  1158. if (texture._MSAAFramebuffer) {
  1159. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  1160. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  1161. gl.blitFramebuffer(0, 0, texture.width, texture.height,
  1162. 0, 0, texture.width, texture.height,
  1163. gl.COLOR_BUFFER_BIT, gl.NEAREST);
  1164. }
  1165. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  1166. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  1167. gl.generateMipmap(gl.TEXTURE_2D);
  1168. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  1169. }
  1170. if (onBeforeUnbind) {
  1171. if (texture._MSAAFramebuffer) {
  1172. // Bind the correct framebuffer
  1173. this._bindUnboundFramebuffer(texture._framebuffer);
  1174. }
  1175. onBeforeUnbind();
  1176. }
  1177. this._bindUnboundFramebuffer(null);
  1178. }
  1179. /**
  1180. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  1181. */
  1182. public flushFramebuffer(): void {
  1183. this._gl.flush();
  1184. }
  1185. /**
  1186. * Unbind the current render target and bind the default framebuffer
  1187. */
  1188. public restoreDefaultFramebuffer(): void {
  1189. if (this._currentRenderTarget) {
  1190. this.unBindFramebuffer(this._currentRenderTarget);
  1191. } else {
  1192. this._bindUnboundFramebuffer(null);
  1193. }
  1194. if (this._cachedViewport) {
  1195. this.setViewport(this._cachedViewport);
  1196. }
  1197. this.wipeCaches();
  1198. }
  1199. // VBOs
  1200. /** @hidden */
  1201. protected _resetVertexBufferBinding(): void {
  1202. this.bindArrayBuffer(null);
  1203. this._cachedVertexBuffers = null;
  1204. }
  1205. /**
  1206. * Creates a vertex buffer
  1207. * @param data the data for the vertex buffer
  1208. * @returns the new WebGL static buffer
  1209. */
  1210. public createVertexBuffer(data: DataArray): DataBuffer {
  1211. return this._createVertexBuffer(data, this._gl.STATIC_DRAW);
  1212. }
  1213. private _createVertexBuffer(data: DataArray, usage: number): DataBuffer {
  1214. var vbo = this._gl.createBuffer();
  1215. if (!vbo) {
  1216. throw new Error("Unable to create vertex buffer");
  1217. }
  1218. let dataBuffer = new WebGLDataBuffer(vbo);
  1219. this.bindArrayBuffer(dataBuffer);
  1220. if (data instanceof Array) {
  1221. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  1222. } else {
  1223. this._gl.bufferData(this._gl.ARRAY_BUFFER, <ArrayBuffer>data, this._gl.STATIC_DRAW);
  1224. }
  1225. this._resetVertexBufferBinding();
  1226. dataBuffer.references = 1;
  1227. return dataBuffer;
  1228. }
  1229. /**
  1230. * Creates a dynamic vertex buffer
  1231. * @param data the data for the dynamic vertex buffer
  1232. * @returns the new WebGL dynamic buffer
  1233. */
  1234. public createDynamicVertexBuffer(data: DataArray): DataBuffer {
  1235. return this._createVertexBuffer(data, this._gl.DYNAMIC_DRAW);
  1236. }
  1237. protected _resetIndexBufferBinding(): void {
  1238. this.bindIndexBuffer(null);
  1239. this._cachedIndexBuffer = null;
  1240. }
  1241. /**
  1242. * Creates a new index buffer
  1243. * @param indices defines the content of the index buffer
  1244. * @param updatable defines if the index buffer must be updatable
  1245. * @returns a new webGL buffer
  1246. */
  1247. public createIndexBuffer(indices: IndicesArray, updatable?: boolean): DataBuffer {
  1248. var vbo = this._gl.createBuffer();
  1249. let dataBuffer = new WebGLDataBuffer(vbo!);
  1250. if (!vbo) {
  1251. throw new Error("Unable to create index buffer");
  1252. }
  1253. this.bindIndexBuffer(dataBuffer);
  1254. const data = this._normalizeIndexData(indices);
  1255. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, data, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  1256. this._resetIndexBufferBinding();
  1257. dataBuffer.references = 1;
  1258. dataBuffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
  1259. return dataBuffer;
  1260. }
  1261. protected _normalizeIndexData(indices: IndicesArray): Uint16Array | Uint32Array {
  1262. if (indices instanceof Uint16Array) {
  1263. return indices;
  1264. }
  1265. // Check 32 bit support
  1266. if (this._caps.uintIndices) {
  1267. if (indices instanceof Uint32Array) {
  1268. return indices;
  1269. } else {
  1270. // number[] or Int32Array, check if 32 bit is necessary
  1271. for (var index = 0; index < indices.length; index++) {
  1272. if (indices[index] >= 65535) {
  1273. return new Uint32Array(indices);
  1274. }
  1275. }
  1276. return new Uint16Array(indices);
  1277. }
  1278. }
  1279. // No 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  1280. return new Uint16Array(indices);
  1281. }
  1282. /**
  1283. * Bind a webGL buffer to the webGL context
  1284. * @param buffer defines the buffer to bind
  1285. */
  1286. public bindArrayBuffer(buffer: Nullable<DataBuffer>): void {
  1287. if (!this._vaoRecordInProgress) {
  1288. this._unbindVertexArrayObject();
  1289. }
  1290. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  1291. }
  1292. /**
  1293. * Bind a specific block at a given index in a specific shader program
  1294. * @param pipelineContext defines the pipeline context to use
  1295. * @param blockName defines the block name
  1296. * @param index defines the index where to bind the block
  1297. */
  1298. public bindUniformBlock(pipelineContext: IPipelineContext, blockName: string, index: number): void {
  1299. let program = (pipelineContext as WebGLPipelineContext).program!;
  1300. var uniformLocation = this._gl.getUniformBlockIndex(program, blockName);
  1301. this._gl.uniformBlockBinding(program, uniformLocation, index);
  1302. }
  1303. protected bindIndexBuffer(buffer: Nullable<DataBuffer>): void {
  1304. if (!this._vaoRecordInProgress) {
  1305. this._unbindVertexArrayObject();
  1306. }
  1307. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  1308. }
  1309. private bindBuffer(buffer: Nullable<DataBuffer>, target: number): void {
  1310. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  1311. this._gl.bindBuffer(target, buffer ? buffer.underlyingResource : null);
  1312. this._currentBoundBuffer[target] = buffer;
  1313. }
  1314. }
  1315. /**
  1316. * update the bound buffer with the given data
  1317. * @param data defines the data to update
  1318. */
  1319. public updateArrayBuffer(data: Float32Array): void {
  1320. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1321. }
  1322. private _vertexAttribPointer(buffer: DataBuffer, indx: number, size: number, type: number, normalized: boolean, stride: number, offset: number): void {
  1323. var pointer = this._currentBufferPointers[indx];
  1324. var changed = false;
  1325. if (!pointer.active) {
  1326. changed = true;
  1327. pointer.active = true;
  1328. pointer.index = indx;
  1329. pointer.size = size;
  1330. pointer.type = type;
  1331. pointer.normalized = normalized;
  1332. pointer.stride = stride;
  1333. pointer.offset = offset;
  1334. pointer.buffer = buffer;
  1335. } else {
  1336. if (pointer.buffer !== buffer) { pointer.buffer = buffer; changed = true; }
  1337. if (pointer.size !== size) { pointer.size = size; changed = true; }
  1338. if (pointer.type !== type) { pointer.type = type; changed = true; }
  1339. if (pointer.normalized !== normalized) { pointer.normalized = normalized; changed = true; }
  1340. if (pointer.stride !== stride) { pointer.stride = stride; changed = true; }
  1341. if (pointer.offset !== offset) { pointer.offset = offset; changed = true; }
  1342. }
  1343. if (changed || this._vaoRecordInProgress) {
  1344. this.bindArrayBuffer(buffer);
  1345. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  1346. }
  1347. }
  1348. private _bindIndexBufferWithCache(indexBuffer: Nullable<DataBuffer>): void {
  1349. if (indexBuffer == null) {
  1350. return;
  1351. }
  1352. if (this._cachedIndexBuffer !== indexBuffer) {
  1353. this._cachedIndexBuffer = indexBuffer;
  1354. this.bindIndexBuffer(indexBuffer);
  1355. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  1356. }
  1357. }
  1358. private _bindVertexBuffersAttributes(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, effect: Effect): void {
  1359. var attributes = effect.getAttributesNames();
  1360. if (!this._vaoRecordInProgress) {
  1361. this._unbindVertexArrayObject();
  1362. }
  1363. this.unbindAllAttributes();
  1364. for (var index = 0; index < attributes.length; index++) {
  1365. var order = effect.getAttributeLocation(index);
  1366. if (order >= 0) {
  1367. var vertexBuffer = vertexBuffers[attributes[index]];
  1368. if (!vertexBuffer) {
  1369. continue;
  1370. }
  1371. this._gl.enableVertexAttribArray(order);
  1372. if (!this._vaoRecordInProgress) {
  1373. this._vertexAttribArraysEnabled[order] = true;
  1374. }
  1375. var buffer = vertexBuffer.getBuffer();
  1376. if (buffer) {
  1377. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  1378. if (vertexBuffer.getIsInstanced()) {
  1379. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1380. if (!this._vaoRecordInProgress) {
  1381. this._currentInstanceLocations.push(order);
  1382. this._currentInstanceBuffers.push(buffer);
  1383. }
  1384. }
  1385. }
  1386. }
  1387. }
  1388. }
  1389. /**
  1390. * Records a vertex array object
  1391. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  1392. * @param vertexBuffers defines the list of vertex buffers to store
  1393. * @param indexBuffer defines the index buffer to store
  1394. * @param effect defines the effect to store
  1395. * @returns the new vertex array object
  1396. */
  1397. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<DataBuffer>, effect: Effect): WebGLVertexArrayObject {
  1398. var vao = this._gl.createVertexArray();
  1399. this._vaoRecordInProgress = true;
  1400. this._gl.bindVertexArray(vao);
  1401. this._mustWipeVertexAttributes = true;
  1402. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1403. this.bindIndexBuffer(indexBuffer);
  1404. this._vaoRecordInProgress = false;
  1405. this._gl.bindVertexArray(null);
  1406. return vao;
  1407. }
  1408. /**
  1409. * Bind a specific vertex array object
  1410. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  1411. * @param vertexArrayObject defines the vertex array object to bind
  1412. * @param indexBuffer defines the index buffer to bind
  1413. */
  1414. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<DataBuffer>): void {
  1415. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1416. this._cachedVertexArrayObject = vertexArrayObject;
  1417. this._gl.bindVertexArray(vertexArrayObject);
  1418. this._cachedVertexBuffers = null;
  1419. this._cachedIndexBuffer = null;
  1420. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1421. this._mustWipeVertexAttributes = true;
  1422. }
  1423. }
  1424. /**
  1425. * Bind webGl buffers directly to the webGL context
  1426. * @param vertexBuffer defines the vertex buffer to bind
  1427. * @param indexBuffer defines the index buffer to bind
  1428. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  1429. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  1430. * @param effect defines the effect associated with the vertex buffer
  1431. */
  1432. public bindBuffersDirectly(vertexBuffer: DataBuffer, indexBuffer: DataBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1433. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1434. this._cachedVertexBuffers = vertexBuffer;
  1435. this._cachedEffectForVertexBuffers = effect;
  1436. let attributesCount = effect.getAttributesCount();
  1437. this._unbindVertexArrayObject();
  1438. this.unbindAllAttributes();
  1439. var offset = 0;
  1440. for (var index = 0; index < attributesCount; index++) {
  1441. if (index < vertexDeclaration.length) {
  1442. var order = effect.getAttributeLocation(index);
  1443. if (order >= 0) {
  1444. this._gl.enableVertexAttribArray(order);
  1445. this._vertexAttribArraysEnabled[order] = true;
  1446. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1447. }
  1448. offset += vertexDeclaration[index] * 4;
  1449. }
  1450. }
  1451. }
  1452. this._bindIndexBufferWithCache(indexBuffer);
  1453. }
  1454. private _unbindVertexArrayObject(): void {
  1455. if (!this._cachedVertexArrayObject) {
  1456. return;
  1457. }
  1458. this._cachedVertexArrayObject = null;
  1459. this._gl.bindVertexArray(null);
  1460. }
  1461. /**
  1462. * Bind a list of vertex buffers to the webGL context
  1463. * @param vertexBuffers defines the list of vertex buffers to bind
  1464. * @param indexBuffer defines the index buffer to bind
  1465. * @param effect defines the effect associated with the vertex buffers
  1466. */
  1467. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<DataBuffer>, effect: Effect): void {
  1468. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1469. this._cachedVertexBuffers = vertexBuffers;
  1470. this._cachedEffectForVertexBuffers = effect;
  1471. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  1472. }
  1473. this._bindIndexBufferWithCache(indexBuffer);
  1474. }
  1475. /**
  1476. * Unbind all instance attributes
  1477. */
  1478. public unbindInstanceAttributes() {
  1479. var boundBuffer;
  1480. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1481. var instancesBuffer = this._currentInstanceBuffers[i];
  1482. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  1483. boundBuffer = instancesBuffer;
  1484. this.bindArrayBuffer(instancesBuffer);
  1485. }
  1486. var offsetLocation = this._currentInstanceLocations[i];
  1487. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1488. }
  1489. this._currentInstanceBuffers.length = 0;
  1490. this._currentInstanceLocations.length = 0;
  1491. }
  1492. /**
  1493. * Release and free the memory of a vertex array object
  1494. * @param vao defines the vertex array object to delete
  1495. */
  1496. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1497. this._gl.deleteVertexArray(vao);
  1498. }
  1499. /** @hidden */
  1500. public _releaseBuffer(buffer: DataBuffer): boolean {
  1501. buffer.references--;
  1502. if (buffer.references === 0) {
  1503. this._deleteBuffer(buffer);
  1504. return true;
  1505. }
  1506. return false;
  1507. }
  1508. protected _deleteBuffer(buffer: DataBuffer): void {
  1509. this._gl.deleteBuffer(buffer.underlyingResource);
  1510. }
  1511. /**
  1512. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  1513. * @param instancesBuffer defines the webGL buffer to update and bind
  1514. * @param data defines the data to store in the buffer
  1515. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  1516. */
  1517. public updateAndBindInstancesBuffer(instancesBuffer: DataBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1518. this.bindArrayBuffer(instancesBuffer);
  1519. if (data) {
  1520. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1521. }
  1522. if ((<any>offsetLocations[0]).index !== undefined) {
  1523. this.bindInstancesBuffer(instancesBuffer, offsetLocations as any, true);
  1524. } else {
  1525. for (let index = 0; index < 4; index++) {
  1526. let offsetLocation = <number>offsetLocations[index];
  1527. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1528. this._gl.enableVertexAttribArray(offsetLocation);
  1529. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1530. }
  1531. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1532. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1533. this._currentInstanceLocations.push(offsetLocation);
  1534. this._currentInstanceBuffers.push(instancesBuffer);
  1535. }
  1536. }
  1537. }
  1538. /**
  1539. * Bind the content of a webGL buffer used with instanciation
  1540. * @param instancesBuffer defines the webGL buffer to bind
  1541. * @param attributesInfo defines the offsets or attributes information used to determine where data must be stored in the buffer
  1542. * @param computeStride defines Wether to compute the strides from the info or use the default 0
  1543. */
  1544. public bindInstancesBuffer(instancesBuffer: DataBuffer, attributesInfo: InstancingAttributeInfo[], computeStride = true): void {
  1545. this.bindArrayBuffer(instancesBuffer);
  1546. let stride = 0;
  1547. if (computeStride) {
  1548. for (let i = 0; i < attributesInfo.length; i++) {
  1549. let ai = attributesInfo[i];
  1550. stride += ai.attributeSize * 4;
  1551. }
  1552. }
  1553. for (let i = 0; i < attributesInfo.length; i++) {
  1554. let ai = attributesInfo[i];
  1555. if (ai.index === undefined) {
  1556. ai.index = this._currentEffect!.getAttributeLocationByName(ai.attributeName);
  1557. }
  1558. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1559. this._gl.enableVertexAttribArray(ai.index);
  1560. this._vertexAttribArraysEnabled[ai.index] = true;
  1561. }
  1562. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attributeType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1563. this._gl.vertexAttribDivisor(ai.index, ai.divisor === undefined ? 1 : ai.divisor);
  1564. this._currentInstanceLocations.push(ai.index);
  1565. this._currentInstanceBuffers.push(instancesBuffer);
  1566. }
  1567. }
  1568. /**
  1569. * Disable the instance attribute corresponding to the name in parameter
  1570. * @param name defines the name of the attribute to disable
  1571. */
  1572. public disableInstanceAttributeByName(name: string) {
  1573. if (!this._currentEffect) {
  1574. return;
  1575. }
  1576. const attributeLocation = this._currentEffect.getAttributeLocationByName(name);
  1577. this.disableInstanceAttribute(attributeLocation);
  1578. }
  1579. /**
  1580. * Disable the instance attribute corresponding to the location in parameter
  1581. * @param attributeLocation defines the attribute location of the attribute to disable
  1582. */
  1583. public disableInstanceAttribute(attributeLocation: number) {
  1584. let shouldClean = false;
  1585. let index: number;
  1586. while ((index = this._currentInstanceLocations.indexOf(attributeLocation)) !== -1) {
  1587. this._currentInstanceLocations.splice(index, 1);
  1588. this._currentInstanceBuffers.splice(index, 1);
  1589. shouldClean = true;
  1590. index = this._currentInstanceLocations.indexOf(attributeLocation);
  1591. }
  1592. if (shouldClean) {
  1593. this._gl.vertexAttribDivisor(attributeLocation, 0);
  1594. this.disableAttributeByIndex(attributeLocation);
  1595. }
  1596. }
  1597. /**
  1598. * Disable the attribute corresponding to the location in parameter
  1599. * @param attributeLocation defines the attribute location of the attribute to disable
  1600. */
  1601. public disableAttributeByIndex(attributeLocation: number) {
  1602. this._gl.disableVertexAttribArray(attributeLocation);
  1603. this._vertexAttribArraysEnabled[attributeLocation] = false;
  1604. this._currentBufferPointers[attributeLocation].active = false;
  1605. }
  1606. /**
  1607. * Send a draw order
  1608. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  1609. * @param indexStart defines the starting index
  1610. * @param indexCount defines the number of index to draw
  1611. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1612. */
  1613. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1614. this.drawElementsType(useTriangles ? Constants.MATERIAL_TriangleFillMode : Constants.MATERIAL_WireFrameFillMode, indexStart, indexCount, instancesCount);
  1615. }
  1616. /**
  1617. * Draw a list of points
  1618. * @param verticesStart defines the index of first vertex to draw
  1619. * @param verticesCount defines the count of vertices to draw
  1620. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1621. */
  1622. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1623. this.drawArraysType(Constants.MATERIAL_PointFillMode, verticesStart, verticesCount, instancesCount);
  1624. }
  1625. /**
  1626. * Draw a list of unindexed primitives
  1627. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  1628. * @param verticesStart defines the index of first vertex to draw
  1629. * @param verticesCount defines the count of vertices to draw
  1630. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1631. */
  1632. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1633. this.drawArraysType(useTriangles ? Constants.MATERIAL_TriangleFillMode : Constants.MATERIAL_WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  1634. }
  1635. /**
  1636. * Draw a list of indexed primitives
  1637. * @param fillMode defines the primitive to use
  1638. * @param indexStart defines the starting index
  1639. * @param indexCount defines the number of index to draw
  1640. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1641. */
  1642. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  1643. // Apply states
  1644. this.applyStates();
  1645. this._reportDrawCall();
  1646. // Render
  1647. const drawMode = this._drawMode(fillMode);
  1648. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1649. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1650. if (instancesCount) {
  1651. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  1652. } else {
  1653. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  1654. }
  1655. }
  1656. /**
  1657. * Draw a list of unindexed primitives
  1658. * @param fillMode defines the primitive to use
  1659. * @param verticesStart defines the index of first vertex to draw
  1660. * @param verticesCount defines the count of vertices to draw
  1661. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1662. */
  1663. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1664. // Apply states
  1665. this.applyStates();
  1666. this._reportDrawCall();
  1667. const drawMode = this._drawMode(fillMode);
  1668. if (instancesCount) {
  1669. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  1670. } else {
  1671. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  1672. }
  1673. }
  1674. private _drawMode(fillMode: number): number {
  1675. switch (fillMode) {
  1676. // Triangle views
  1677. case Constants.MATERIAL_TriangleFillMode:
  1678. return this._gl.TRIANGLES;
  1679. case Constants.MATERIAL_PointFillMode:
  1680. return this._gl.POINTS;
  1681. case Constants.MATERIAL_WireFrameFillMode:
  1682. return this._gl.LINES;
  1683. // Draw modes
  1684. case Constants.MATERIAL_PointListDrawMode:
  1685. return this._gl.POINTS;
  1686. case Constants.MATERIAL_LineListDrawMode:
  1687. return this._gl.LINES;
  1688. case Constants.MATERIAL_LineLoopDrawMode:
  1689. return this._gl.LINE_LOOP;
  1690. case Constants.MATERIAL_LineStripDrawMode:
  1691. return this._gl.LINE_STRIP;
  1692. case Constants.MATERIAL_TriangleStripDrawMode:
  1693. return this._gl.TRIANGLE_STRIP;
  1694. case Constants.MATERIAL_TriangleFanDrawMode:
  1695. return this._gl.TRIANGLE_FAN;
  1696. default:
  1697. return this._gl.TRIANGLES;
  1698. }
  1699. }
  1700. /** @hidden */
  1701. protected _reportDrawCall() {
  1702. // Will be implemented by children
  1703. }
  1704. // Shaders
  1705. /** @hidden */
  1706. public _releaseEffect(effect: Effect): void {
  1707. if (this._compiledEffects[effect._key]) {
  1708. delete this._compiledEffects[effect._key];
  1709. this._deletePipelineContext(effect.getPipelineContext() as WebGLPipelineContext);
  1710. }
  1711. }
  1712. /** @hidden */
  1713. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  1714. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1715. if (webGLPipelineContext && webGLPipelineContext.program) {
  1716. webGLPipelineContext.program.__SPECTOR_rebuildProgram = null;
  1717. this._gl.deleteProgram(webGLPipelineContext.program);
  1718. }
  1719. }
  1720. /**
  1721. * Create a new effect (used to store vertex/fragment shaders)
  1722. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  1723. * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object
  1724. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  1725. * @param samplers defines an array of string used to represent textures
  1726. * @param defines defines the string containing the defines to use to compile the shaders
  1727. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  1728. * @param onCompiled defines a function to call when the effect creation is successful
  1729. * @param onError defines a function to call when the effect creation has failed
  1730. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  1731. * @returns the new Effect
  1732. */
  1733. public createEffect(baseName: any, attributesNamesOrOptions: string[] | IEffectCreationOptions, uniformsNamesOrEngine: string[] | ThinEngine, samplers?: string[], defines?: string,
  1734. fallbacks?: IEffectFallbacks,
  1735. onCompiled?: Nullable<(effect: Effect) => void>, onError?: Nullable<(effect: Effect, errors: string) => void>, indexParameters?: any): Effect {
  1736. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  1737. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  1738. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<IEffectCreationOptions>attributesNamesOrOptions).defines);
  1739. if (this._compiledEffects[name]) {
  1740. var compiledEffect = <Effect>this._compiledEffects[name];
  1741. if (onCompiled && compiledEffect.isReady()) {
  1742. onCompiled(compiledEffect);
  1743. }
  1744. return compiledEffect;
  1745. }
  1746. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  1747. effect._key = name;
  1748. this._compiledEffects[name] = effect;
  1749. return effect;
  1750. }
  1751. protected static _ConcatenateShader(source: string, defines: Nullable<string>, shaderVersion: string = ""): string {
  1752. return shaderVersion + (defines ? defines + "\n" : "") + source;
  1753. }
  1754. private _compileShader(source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader {
  1755. return this._compileRawShader(ThinEngine._ConcatenateShader(source, defines, shaderVersion), type);
  1756. }
  1757. private _compileRawShader(source: string, type: string): WebGLShader {
  1758. var gl = this._gl;
  1759. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  1760. if (!shader) {
  1761. throw new Error("Something went wrong while compile the shader.");
  1762. }
  1763. gl.shaderSource(shader, source);
  1764. gl.compileShader(shader);
  1765. return shader;
  1766. }
  1767. /**
  1768. * Directly creates a webGL program
  1769. * @param pipelineContext defines the pipeline context to attach to
  1770. * @param vertexCode defines the vertex shader code to use
  1771. * @param fragmentCode defines the fragment shader code to use
  1772. * @param context defines the webGL context to use (if not set, the current one will be used)
  1773. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  1774. * @returns the new webGL program
  1775. */
  1776. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1777. context = context || this._gl;
  1778. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  1779. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  1780. return this._createShaderProgram(pipelineContext as WebGLPipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
  1781. }
  1782. /**
  1783. * Creates a webGL program
  1784. * @param pipelineContext defines the pipeline context to attach to
  1785. * @param vertexCode defines the vertex shader code to use
  1786. * @param fragmentCode defines the fragment shader code to use
  1787. * @param defines defines the string containing the defines to use to compile the shaders
  1788. * @param context defines the webGL context to use (if not set, the current one will be used)
  1789. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  1790. * @returns the new webGL program
  1791. */
  1792. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1793. context = context || this._gl;
  1794. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  1795. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  1796. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  1797. return this._createShaderProgram(pipelineContext as WebGLPipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
  1798. }
  1799. /**
  1800. * Creates a new pipeline context
  1801. * @returns the new pipeline
  1802. */
  1803. public createPipelineContext(): IPipelineContext {
  1804. var pipelineContext = new WebGLPipelineContext();
  1805. pipelineContext.engine = this;
  1806. if (this._caps.parallelShaderCompile) {
  1807. pipelineContext.isParallelCompiled = true;
  1808. }
  1809. return pipelineContext;
  1810. }
  1811. protected _createShaderProgram(pipelineContext: WebGLPipelineContext, vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1812. var shaderProgram = context.createProgram();
  1813. pipelineContext.program = shaderProgram;
  1814. if (!shaderProgram) {
  1815. throw new Error("Unable to create program");
  1816. }
  1817. context.attachShader(shaderProgram, vertexShader);
  1818. context.attachShader(shaderProgram, fragmentShader);
  1819. context.linkProgram(shaderProgram);
  1820. pipelineContext.context = context;
  1821. pipelineContext.vertexShader = vertexShader;
  1822. pipelineContext.fragmentShader = fragmentShader;
  1823. if (!pipelineContext.isParallelCompiled) {
  1824. this._finalizePipelineContext(pipelineContext);
  1825. }
  1826. return shaderProgram;
  1827. }
  1828. protected _finalizePipelineContext(pipelineContext: WebGLPipelineContext) {
  1829. const context = pipelineContext.context!;
  1830. const vertexShader = pipelineContext.vertexShader!;
  1831. const fragmentShader = pipelineContext.fragmentShader!;
  1832. const program = pipelineContext.program!;
  1833. var linked = context.getProgramParameter(program, context.LINK_STATUS);
  1834. if (!linked) { // Get more info
  1835. // Vertex
  1836. if (!this._gl.getShaderParameter(vertexShader, this._gl.COMPILE_STATUS)) {
  1837. const log = this._gl.getShaderInfoLog(vertexShader);
  1838. if (log) {
  1839. pipelineContext.vertexCompilationError = log;
  1840. throw new Error("VERTEX SHADER " + log);
  1841. }
  1842. }
  1843. // Fragment
  1844. if (!this._gl.getShaderParameter(fragmentShader, this._gl.COMPILE_STATUS)) {
  1845. const log = this._gl.getShaderInfoLog(fragmentShader);
  1846. if (log) {
  1847. pipelineContext.fragmentCompilationError = log;
  1848. throw new Error("FRAGMENT SHADER " + log);
  1849. }
  1850. }
  1851. var error = context.getProgramInfoLog(program);
  1852. if (error) {
  1853. pipelineContext.programLinkError = error;
  1854. throw new Error(error);
  1855. }
  1856. }
  1857. if (this.validateShaderPrograms) {
  1858. context.validateProgram(program);
  1859. var validated = context.getProgramParameter(program, context.VALIDATE_STATUS);
  1860. if (!validated) {
  1861. var error = context.getProgramInfoLog(program);
  1862. if (error) {
  1863. pipelineContext.programValidationError = error;
  1864. throw new Error(error);
  1865. }
  1866. }
  1867. }
  1868. context.deleteShader(vertexShader);
  1869. context.deleteShader(fragmentShader);
  1870. pipelineContext.vertexShader = undefined;
  1871. pipelineContext.fragmentShader = undefined;
  1872. if (pipelineContext.onCompiled) {
  1873. pipelineContext.onCompiled();
  1874. pipelineContext.onCompiled = undefined;
  1875. }
  1876. }
  1877. /** @hidden */
  1878. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean,
  1879. rebuildRebind: any,
  1880. defines: Nullable<string>,
  1881. transformFeedbackVaryings: Nullable<string[]>) {
  1882. let webGLRenderingState = pipelineContext as WebGLPipelineContext;
  1883. if (createAsRaw) {
  1884. webGLRenderingState.program = this.createRawShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings);
  1885. }
  1886. else {
  1887. webGLRenderingState.program = this.createShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings);
  1888. }
  1889. webGLRenderingState.program.__SPECTOR_rebuildProgram = rebuildRebind;
  1890. }
  1891. /** @hidden */
  1892. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  1893. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1894. if (this._gl.getProgramParameter(webGLPipelineContext.program!, this._caps.parallelShaderCompile!.COMPLETION_STATUS_KHR)) {
  1895. this._finalizePipelineContext(webGLPipelineContext);
  1896. return true;
  1897. }
  1898. return false;
  1899. }
  1900. /** @hidden */
  1901. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  1902. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1903. if (!webGLPipelineContext.isParallelCompiled) {
  1904. action();
  1905. return;
  1906. }
  1907. let oldHandler = webGLPipelineContext.onCompiled;
  1908. if (oldHandler) {
  1909. webGLPipelineContext.onCompiled = () => {
  1910. oldHandler!();
  1911. action();
  1912. };
  1913. } else {
  1914. webGLPipelineContext.onCompiled = action;
  1915. }
  1916. }
  1917. /**
  1918. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  1919. * @param pipelineContext defines the pipeline context to use
  1920. * @param uniformsNames defines the list of uniform names
  1921. * @returns an array of webGL uniform locations
  1922. */
  1923. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  1924. var results = new Array<Nullable<WebGLUniformLocation>>();
  1925. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1926. for (var index = 0; index < uniformsNames.length; index++) {
  1927. results.push(this._gl.getUniformLocation(webGLPipelineContext.program!, uniformsNames[index]));
  1928. }
  1929. return results;
  1930. }
  1931. /**
  1932. * Gets the lsit of active attributes for a given webGL program
  1933. * @param pipelineContext defines the pipeline context to use
  1934. * @param attributesNames defines the list of attribute names to get
  1935. * @returns an array of indices indicating the offset of each attribute
  1936. */
  1937. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  1938. var results = [];
  1939. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1940. for (var index = 0; index < attributesNames.length; index++) {
  1941. try {
  1942. results.push(this._gl.getAttribLocation(webGLPipelineContext.program!, attributesNames[index]));
  1943. } catch (e) {
  1944. results.push(-1);
  1945. }
  1946. }
  1947. return results;
  1948. }
  1949. /**
  1950. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  1951. * @param effect defines the effect to activate
  1952. */
  1953. public enableEffect(effect: Nullable<Effect>): void {
  1954. if (!effect || effect === this._currentEffect) {
  1955. return;
  1956. }
  1957. // Use program
  1958. this.bindSamplers(effect);
  1959. this._currentEffect = effect;
  1960. if (effect.onBind) {
  1961. effect.onBind(effect);
  1962. }
  1963. if (effect._onBindObservable) {
  1964. effect._onBindObservable.notifyObservers(effect);
  1965. }
  1966. }
  1967. /**
  1968. * Set the value of an uniform to a number (int)
  1969. * @param uniform defines the webGL uniform location where to store the value
  1970. * @param value defines the int number to store
  1971. */
  1972. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  1973. if (!uniform) {
  1974. return;
  1975. }
  1976. this._gl.uniform1i(uniform, value);
  1977. }
  1978. /**
  1979. * Set the value of an uniform to an array of int32
  1980. * @param uniform defines the webGL uniform location where to store the value
  1981. * @param array defines the array of int32 to store
  1982. */
  1983. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  1984. if (!uniform) {
  1985. return;
  1986. }
  1987. this._gl.uniform1iv(uniform, array);
  1988. }
  1989. /**
  1990. * Set the value of an uniform to an array of int32 (stored as vec2)
  1991. * @param uniform defines the webGL uniform location where to store the value
  1992. * @param array defines the array of int32 to store
  1993. */
  1994. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  1995. if (!uniform || array.length % 2 !== 0) {
  1996. return;
  1997. }
  1998. this._gl.uniform2iv(uniform, array);
  1999. }
  2000. /**
  2001. * Set the value of an uniform to an array of int32 (stored as vec3)
  2002. * @param uniform defines the webGL uniform location where to store the value
  2003. * @param array defines the array of int32 to store
  2004. */
  2005. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2006. if (!uniform || array.length % 3 !== 0) {
  2007. return;
  2008. }
  2009. this._gl.uniform3iv(uniform, array);
  2010. }
  2011. /**
  2012. * Set the value of an uniform to an array of int32 (stored as vec4)
  2013. * @param uniform defines the webGL uniform location where to store the value
  2014. * @param array defines the array of int32 to store
  2015. */
  2016. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): void {
  2017. if (!uniform || array.length % 4 !== 0) {
  2018. return;
  2019. }
  2020. this._gl.uniform4iv(uniform, array);
  2021. }
  2022. /**
  2023. * Set the value of an uniform to an array of number
  2024. * @param uniform defines the webGL uniform location where to store the value
  2025. * @param array defines the array of number to store
  2026. */
  2027. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): void {
  2028. if (!uniform) {
  2029. return;
  2030. }
  2031. this._gl.uniform1fv(uniform, array);
  2032. }
  2033. /**
  2034. * Set the value of an uniform to an array of number (stored as vec2)
  2035. * @param uniform defines the webGL uniform location where to store the value
  2036. * @param array defines the array of number to store
  2037. */
  2038. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): void {
  2039. if (!uniform || array.length % 2 !== 0) {
  2040. return;
  2041. }
  2042. this._gl.uniform2fv(uniform, <any>array);
  2043. }
  2044. /**
  2045. * Set the value of an uniform to an array of number (stored as vec3)
  2046. * @param uniform defines the webGL uniform location where to store the value
  2047. * @param array defines the array of number to store
  2048. */
  2049. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): void {
  2050. if (!uniform || array.length % 3 !== 0) {
  2051. return;
  2052. }
  2053. this._gl.uniform3fv(uniform, <any>array);
  2054. }
  2055. /**
  2056. * Set the value of an uniform to an array of number (stored as vec4)
  2057. * @param uniform defines the webGL uniform location where to store the value
  2058. * @param array defines the array of number to store
  2059. */
  2060. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): void {
  2061. if (!uniform || array.length % 4 !== 0) {
  2062. return;
  2063. }
  2064. this._gl.uniform4fv(uniform, <any>array);
  2065. }
  2066. /**
  2067. * Set the value of an uniform to an array of float32 (stored as matrices)
  2068. * @param uniform defines the webGL uniform location where to store the value
  2069. * @param matrices defines the array of float32 to store
  2070. */
  2071. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): void {
  2072. if (!uniform) {
  2073. return;
  2074. }
  2075. this._gl.uniformMatrix4fv(uniform, false, matrices);
  2076. }
  2077. /**
  2078. * Set the value of an uniform to a matrix (3x3)
  2079. * @param uniform defines the webGL uniform location where to store the value
  2080. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  2081. */
  2082. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2083. if (!uniform) {
  2084. return;
  2085. }
  2086. this._gl.uniformMatrix3fv(uniform, false, matrix);
  2087. }
  2088. /**
  2089. * Set the value of an uniform to a matrix (2x2)
  2090. * @param uniform defines the webGL uniform location where to store the value
  2091. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  2092. */
  2093. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): void {
  2094. if (!uniform) {
  2095. return;
  2096. }
  2097. this._gl.uniformMatrix2fv(uniform, false, matrix);
  2098. }
  2099. /**
  2100. * Set the value of an uniform to a number (float)
  2101. * @param uniform defines the webGL uniform location where to store the value
  2102. * @param value defines the float number to store
  2103. */
  2104. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): void {
  2105. if (!uniform) {
  2106. return;
  2107. }
  2108. this._gl.uniform1f(uniform, value);
  2109. }
  2110. /**
  2111. * Set the value of an uniform to a vec2
  2112. * @param uniform defines the webGL uniform location where to store the value
  2113. * @param x defines the 1st component of the value
  2114. * @param y defines the 2nd component of the value
  2115. */
  2116. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): void {
  2117. if (!uniform) {
  2118. return;
  2119. }
  2120. this._gl.uniform2f(uniform, x, y);
  2121. }
  2122. /**
  2123. * Set the value of an uniform to a vec3
  2124. * @param uniform defines the webGL uniform location where to store the value
  2125. * @param x defines the 1st component of the value
  2126. * @param y defines the 2nd component of the value
  2127. * @param z defines the 3rd component of the value
  2128. */
  2129. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): void {
  2130. if (!uniform) {
  2131. return;
  2132. }
  2133. this._gl.uniform3f(uniform, x, y, z);
  2134. }
  2135. /**
  2136. * Set the value of an uniform to a vec4
  2137. * @param uniform defines the webGL uniform location where to store the value
  2138. * @param x defines the 1st component of the value
  2139. * @param y defines the 2nd component of the value
  2140. * @param z defines the 3rd component of the value
  2141. * @param w defines the 4th component of the value
  2142. */
  2143. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): void {
  2144. if (!uniform) {
  2145. return;
  2146. }
  2147. this._gl.uniform4f(uniform, x, y, z, w);
  2148. }
  2149. // States
  2150. /**
  2151. * Apply all cached states (depth, culling, stencil and alpha)
  2152. */
  2153. public applyStates() {
  2154. this._depthCullingState.apply(this._gl);
  2155. this._stencilState.apply(this._gl);
  2156. this._alphaState.apply(this._gl);
  2157. if (this._colorWriteChanged) {
  2158. this._colorWriteChanged = false;
  2159. const enable = this._colorWrite;
  2160. this._gl.colorMask(enable, enable, enable, enable);
  2161. }
  2162. }
  2163. /**
  2164. * Enable or disable color writing
  2165. * @param enable defines the state to set
  2166. */
  2167. public setColorWrite(enable: boolean): void {
  2168. if (enable !== this._colorWrite) {
  2169. this._colorWriteChanged = true;
  2170. this._colorWrite = enable;
  2171. }
  2172. }
  2173. /**
  2174. * Gets a boolean indicating if color writing is enabled
  2175. * @returns the current color writing state
  2176. */
  2177. public getColorWrite(): boolean {
  2178. return this._colorWrite;
  2179. }
  2180. /**
  2181. * Gets the depth culling state manager
  2182. */
  2183. public get depthCullingState(): DepthCullingState {
  2184. return this._depthCullingState;
  2185. }
  2186. /**
  2187. * Gets the alpha state manager
  2188. */
  2189. public get alphaState(): AlphaState {
  2190. return this._alphaState;
  2191. }
  2192. /**
  2193. * Gets the stencil state manager
  2194. */
  2195. public get stencilState(): StencilState {
  2196. return this._stencilState;
  2197. }
  2198. // Textures
  2199. /**
  2200. * Clears the list of texture accessible through engine.
  2201. * This can help preventing texture load conflict due to name collision.
  2202. */
  2203. public clearInternalTexturesCache() {
  2204. this._internalTexturesCache = [];
  2205. }
  2206. /**
  2207. * Force the entire cache to be cleared
  2208. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  2209. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  2210. */
  2211. public wipeCaches(bruteForce?: boolean): void {
  2212. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  2213. return;
  2214. }
  2215. this._currentEffect = null;
  2216. this._viewportCached.x = 0;
  2217. this._viewportCached.y = 0;
  2218. this._viewportCached.z = 0;
  2219. this._viewportCached.w = 0;
  2220. // Done before in case we clean the attributes
  2221. this._unbindVertexArrayObject();
  2222. if (bruteForce) {
  2223. this._currentProgram = null;
  2224. this.resetTextureCache();
  2225. this._stencilState.reset();
  2226. this._depthCullingState.reset();
  2227. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2228. this._alphaState.reset();
  2229. this._alphaMode = Constants.ALPHA_ADD;
  2230. this._alphaEquation = Constants.ALPHA_DISABLE;
  2231. this._colorWrite = true;
  2232. this._colorWriteChanged = true;
  2233. this._unpackFlipYCached = null;
  2234. this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
  2235. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2236. this._mustWipeVertexAttributes = true;
  2237. this.unbindAllAttributes();
  2238. }
  2239. this._resetVertexBufferBinding();
  2240. this._cachedIndexBuffer = null;
  2241. this._cachedEffectForVertexBuffers = null;
  2242. this.bindIndexBuffer(null);
  2243. }
  2244. /** @hidden */
  2245. public _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  2246. var gl = this._gl;
  2247. var magFilter = gl.NEAREST;
  2248. var minFilter = gl.NEAREST;
  2249. switch (samplingMode) {
  2250. case Constants.TEXTURE_BILINEAR_SAMPLINGMODE:
  2251. magFilter = gl.LINEAR;
  2252. if (generateMipMaps) {
  2253. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2254. } else {
  2255. minFilter = gl.LINEAR;
  2256. }
  2257. break;
  2258. case Constants.TEXTURE_TRILINEAR_SAMPLINGMODE:
  2259. magFilter = gl.LINEAR;
  2260. if (generateMipMaps) {
  2261. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2262. } else {
  2263. minFilter = gl.LINEAR;
  2264. }
  2265. break;
  2266. case Constants.TEXTURE_NEAREST_SAMPLINGMODE:
  2267. magFilter = gl.NEAREST;
  2268. if (generateMipMaps) {
  2269. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2270. } else {
  2271. minFilter = gl.NEAREST;
  2272. }
  2273. break;
  2274. case Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  2275. magFilter = gl.NEAREST;
  2276. if (generateMipMaps) {
  2277. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  2278. } else {
  2279. minFilter = gl.NEAREST;
  2280. }
  2281. break;
  2282. case Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  2283. magFilter = gl.NEAREST;
  2284. if (generateMipMaps) {
  2285. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2286. } else {
  2287. minFilter = gl.LINEAR;
  2288. }
  2289. break;
  2290. case Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  2291. magFilter = gl.NEAREST;
  2292. if (generateMipMaps) {
  2293. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2294. } else {
  2295. minFilter = gl.LINEAR;
  2296. }
  2297. break;
  2298. case Constants.TEXTURE_NEAREST_LINEAR:
  2299. magFilter = gl.NEAREST;
  2300. minFilter = gl.LINEAR;
  2301. break;
  2302. case Constants.TEXTURE_NEAREST_NEAREST:
  2303. magFilter = gl.NEAREST;
  2304. minFilter = gl.NEAREST;
  2305. break;
  2306. case Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  2307. magFilter = gl.LINEAR;
  2308. if (generateMipMaps) {
  2309. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  2310. } else {
  2311. minFilter = gl.NEAREST;
  2312. }
  2313. break;
  2314. case Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  2315. magFilter = gl.LINEAR;
  2316. if (generateMipMaps) {
  2317. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2318. } else {
  2319. minFilter = gl.NEAREST;
  2320. }
  2321. break;
  2322. case Constants.TEXTURE_LINEAR_LINEAR:
  2323. magFilter = gl.LINEAR;
  2324. minFilter = gl.LINEAR;
  2325. break;
  2326. case Constants.TEXTURE_LINEAR_NEAREST:
  2327. magFilter = gl.LINEAR;
  2328. minFilter = gl.NEAREST;
  2329. break;
  2330. }
  2331. return {
  2332. min: minFilter,
  2333. mag: magFilter
  2334. };
  2335. }
  2336. /** @hidden */
  2337. public _createTexture(): WebGLTexture {
  2338. let texture = this._gl.createTexture();
  2339. if (!texture) {
  2340. throw new Error("Unable to create texture");
  2341. }
  2342. return texture;
  2343. }
  2344. /**
  2345. * Usually called from Texture.ts.
  2346. * Passed information to create a WebGLTexture
  2347. * @param urlArg defines a value which contains one of the following:
  2348. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  2349. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2350. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2351. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  2352. * @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
  2353. * @param scene needed for loading to the correct scene
  2354. * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
  2355. * @param onLoad optional callback to be called upon successful completion
  2356. * @param onError optional callback to be called upon failure
  2357. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  2358. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  2359. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  2360. * @param forcedExtension defines the extension to use to pick the right loader
  2361. * @param excludeLoaders array of texture loaders that should be excluded when picking a loader for the texture (default: empty array)
  2362. * @param mimeType defines an optional mime type
  2363. * @returns a InternalTexture for assignment back into BABYLON.Texture
  2364. */
  2365. public createTexture(urlArg: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<ISceneLike>, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  2366. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  2367. buffer: Nullable<string | ArrayBuffer | ArrayBufferView | HTMLImageElement | Blob | ImageBitmap> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  2368. forcedExtension: Nullable<string> = null, excludeLoaders: Array<IInternalTextureLoader> = [], mimeType?: string): InternalTexture {
  2369. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  2370. var fromData = url.substr(0, 5) === "data:";
  2371. var fromBlob = url.substr(0, 5) === "blob:";
  2372. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  2373. let texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Url);
  2374. // establish the file extension, if possible
  2375. var lastDot = url.lastIndexOf('.');
  2376. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  2377. const filteredFormat: Nullable<string> = this.excludedCompressedTextureFormats(url, this._textureFormatInUse);
  2378. let loader: Nullable<IInternalTextureLoader> = null;
  2379. for (let availableLoader of ThinEngine._TextureLoaders) {
  2380. if (excludeLoaders.indexOf(availableLoader) === -1 && availableLoader.canLoad(extension, filteredFormat, fallback, isBase64, buffer ? true : false)) {
  2381. loader = availableLoader;
  2382. break;
  2383. }
  2384. }
  2385. if (loader) {
  2386. url = loader.transformUrl(url, filteredFormat);
  2387. }
  2388. if (scene) {
  2389. scene._addPendingData(texture);
  2390. }
  2391. texture.url = url;
  2392. texture.generateMipMaps = !noMipmap;
  2393. texture.samplingMode = samplingMode;
  2394. texture.invertY = invertY;
  2395. if (!this._doNotHandleContextLost) {
  2396. // Keep a link to the buffer only if we plan to handle context lost
  2397. texture._buffer = buffer;
  2398. }
  2399. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  2400. if (onLoad && !fallback) {
  2401. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  2402. }
  2403. if (!fallback) { this._internalTexturesCache.push(texture); }
  2404. let onInternalError = (message?: string, exception?: any) => {
  2405. if (scene) {
  2406. scene._removePendingData(texture);
  2407. }
  2408. let customFallback = false;
  2409. if (loader) {
  2410. const fallbackUrl = loader.getFallbackTextureUrl(url, this._textureFormatInUse);
  2411. if (fallbackUrl) {
  2412. // Add Back
  2413. customFallback = true;
  2414. excludeLoaders.push(loader);
  2415. this.createTexture(urlArg, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture, undefined, undefined, excludeLoaders);
  2416. return;
  2417. }
  2418. }
  2419. if (!customFallback) {
  2420. if (onLoadObserver) {
  2421. texture.onLoadedObservable.remove(onLoadObserver);
  2422. }
  2423. if (EngineStore.UseFallbackTexture) {
  2424. this.createTexture(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture);
  2425. return;
  2426. }
  2427. }
  2428. if (onError) {
  2429. onError(message || "Unknown error", exception);
  2430. }
  2431. };
  2432. // processing for non-image formats
  2433. if (loader) {
  2434. var callback = (data: string | ArrayBuffer) => {
  2435. loader!.loadData(data as ArrayBuffer, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void, loadFailed) => {
  2436. if (loadFailed) {
  2437. onInternalError("TextureLoader failed to load data");
  2438. } else {
  2439. this._prepareWebGLTexture(texture, scene, width, height, texture.invertY, !loadMipmap, isCompressed, () => {
  2440. done();
  2441. return false;
  2442. }, samplingMode);
  2443. }
  2444. });
  2445. };
  2446. if (!buffer) {
  2447. this._loadFile(url, callback, undefined, scene ? scene.offlineProvider : undefined, true, (request?: IWebRequest, exception?: any) => {
  2448. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  2449. });
  2450. } else {
  2451. //callback(buffer as ArrayBuffer);
  2452. if (buffer instanceof ArrayBuffer) {
  2453. callback(buffer);
  2454. }
  2455. else {
  2456. if (onError) {
  2457. onError("Unable to load: only ArrayBuffer supported here", null);
  2458. }
  2459. }
  2460. }
  2461. } else {
  2462. var onload = (img: HTMLImageElement | ImageBitmap) => {
  2463. if (fromBlob && !this._doNotHandleContextLost) {
  2464. // We need to store the image if we need to rebuild the texture
  2465. // in case of a webgl context lost
  2466. texture._buffer = img;
  2467. }
  2468. this._prepareWebGLTexture(texture, scene, img.width, img.height, texture.invertY, noMipmap, false, (potWidth, potHeight, continuationCallback) => {
  2469. let gl = this._gl;
  2470. var isPot = (img.width === potWidth && img.height === potHeight);
  2471. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2472. if (isPot) {
  2473. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2474. return false;
  2475. }
  2476. let maxTextureSize = this._caps.maxTextureSize;
  2477. if (img.width > maxTextureSize || img.height > maxTextureSize || !this._supportsHardwareTextureRescaling) {
  2478. this._prepareWorkingCanvas();
  2479. if (!this._workingCanvas || !this._workingContext) {
  2480. return false;
  2481. }
  2482. this._workingCanvas.width = potWidth;
  2483. this._workingCanvas.height = potHeight;
  2484. this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  2485. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  2486. texture.width = potWidth;
  2487. texture.height = potHeight;
  2488. return false;
  2489. } else {
  2490. // Using shaders when possible to rescale because canvas.drawImage is lossy
  2491. let source = new InternalTexture(this, InternalTextureSource.Temp);
  2492. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  2493. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  2494. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2495. this._releaseTexture(source);
  2496. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2497. continuationCallback();
  2498. });
  2499. }
  2500. return true;
  2501. }, samplingMode);
  2502. };
  2503. if (!fromData || isBase64) {
  2504. if (buffer && ((<HTMLImageElement>buffer).decoding || (<ImageBitmap>buffer).close)) {
  2505. onload(<HTMLImageElement>buffer);
  2506. } else {
  2507. FileTools.LoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType);
  2508. }
  2509. }
  2510. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer) || buffer instanceof Blob) {
  2511. FileTools.LoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType);
  2512. }
  2513. else if (buffer) {
  2514. onload(<HTMLImageElement>buffer);
  2515. }
  2516. }
  2517. return texture;
  2518. }
  2519. /**
  2520. * @hidden
  2521. */
  2522. public _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<any>, internalFormat: number, onComplete: () => void): void {
  2523. }
  2524. /**
  2525. * Creates a raw texture
  2526. * @param data defines the data to store in the texture
  2527. * @param width defines the width of the texture
  2528. * @param height defines the height of the texture
  2529. * @param format defines the format of the data
  2530. * @param generateMipMaps defines if the engine should generate the mip levels
  2531. * @param invertY defines if data must be stored with Y axis inverted
  2532. * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
  2533. * @param compression defines the compression used (null by default)
  2534. * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
  2535. * @returns the raw texture inside an InternalTexture
  2536. */
  2537. public createRawTexture(data: Nullable<ArrayBufferView>, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, type: number = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  2538. throw _DevTools.WarnImport("Engine.RawTexture");
  2539. }
  2540. /**
  2541. * Creates a new raw cube texture
  2542. * @param data defines the array of data to use to create each face
  2543. * @param size defines the size of the textures
  2544. * @param format defines the format of the data
  2545. * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT)
  2546. * @param generateMipMaps defines if the engine should generate the mip levels
  2547. * @param invertY defines if data must be stored with Y axis inverted
  2548. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2549. * @param compression defines the compression used (null by default)
  2550. * @returns the cube texture as an InternalTexture
  2551. */
  2552. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  2553. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  2554. compression: Nullable<string> = null): InternalTexture {
  2555. throw _DevTools.WarnImport("Engine.RawTexture");
  2556. }
  2557. /**
  2558. * Creates a new raw 3D texture
  2559. * @param data defines the data used to create the texture
  2560. * @param width defines the width of the texture
  2561. * @param height defines the height of the texture
  2562. * @param depth defines the depth of the texture
  2563. * @param format defines the format of the texture
  2564. * @param generateMipMaps defines if the engine must generate mip levels
  2565. * @param invertY defines if data must be stored with Y axis inverted
  2566. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2567. * @param compression defines the compressed used (can be null)
  2568. * @param textureType defines the compressed used (can be null)
  2569. * @returns a new raw 3D texture (stored in an InternalTexture)
  2570. */
  2571. public createRawTexture3D(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, textureType = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  2572. throw _DevTools.WarnImport("Engine.RawTexture");
  2573. }
  2574. /**
  2575. * Creates a new raw 2D array texture
  2576. * @param data defines the data used to create the texture
  2577. * @param width defines the width of the texture
  2578. * @param height defines the height of the texture
  2579. * @param depth defines the number of layers of the texture
  2580. * @param format defines the format of the texture
  2581. * @param generateMipMaps defines if the engine must generate mip levels
  2582. * @param invertY defines if data must be stored with Y axis inverted
  2583. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2584. * @param compression defines the compressed used (can be null)
  2585. * @param textureType defines the compressed used (can be null)
  2586. * @returns a new raw 2D array texture (stored in an InternalTexture)
  2587. */
  2588. public createRawTexture2DArray(data: Nullable<ArrayBufferView>, width: number, height: number, depth: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression: Nullable<string> = null, textureType = Constants.TEXTURETYPE_UNSIGNED_INT): InternalTexture {
  2589. throw _DevTools.WarnImport("Engine.RawTexture");
  2590. }
  2591. private _unpackFlipYCached: Nullable<boolean> = null;
  2592. /**
  2593. * In case you are sharing the context with other applications, it might
  2594. * be interested to not cache the unpack flip y state to ensure a consistent
  2595. * value would be set.
  2596. */
  2597. public enableUnpackFlipYCached = true;
  2598. /** @hidden */
  2599. public _unpackFlipY(value: boolean): void {
  2600. if (this._unpackFlipYCached !== value) {
  2601. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  2602. if (this.enableUnpackFlipYCached) {
  2603. this._unpackFlipYCached = value;
  2604. }
  2605. }
  2606. }
  2607. /** @hidden */
  2608. public _getUnpackAlignement(): number {
  2609. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  2610. }
  2611. private _getTextureTarget(texture: InternalTexture): number {
  2612. if (texture.isCube) {
  2613. return this._gl.TEXTURE_CUBE_MAP;
  2614. } else if (texture.is3D) {
  2615. return this._gl.TEXTURE_3D;
  2616. } else if (texture.is2DArray) {
  2617. return this._gl.TEXTURE_2D_ARRAY;
  2618. }
  2619. return this._gl.TEXTURE_2D;
  2620. }
  2621. /**
  2622. * Update the sampling mode of a given texture
  2623. * @param samplingMode defines the required sampling mode
  2624. * @param texture defines the texture to update
  2625. * @param generateMipMaps defines whether to generate mipmaps for the texture
  2626. */
  2627. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture, generateMipMaps: boolean = false): void {
  2628. const target = this._getTextureTarget(texture);
  2629. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps || generateMipMaps);
  2630. this._setTextureParameterInteger(target, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  2631. this._setTextureParameterInteger(target, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2632. if (generateMipMaps) {
  2633. texture.generateMipMaps = true;
  2634. this._gl.generateMipmap(target);
  2635. }
  2636. this._bindTextureDirectly(target, null);
  2637. texture.samplingMode = samplingMode;
  2638. }
  2639. /**
  2640. * Update the sampling mode of a given texture
  2641. * @param texture defines the texture to update
  2642. * @param wrapU defines the texture wrap mode of the u coordinates
  2643. * @param wrapV defines the texture wrap mode of the v coordinates
  2644. * @param wrapR defines the texture wrap mode of the r coordinates
  2645. */
  2646. public updateTextureWrappingMode(texture: InternalTexture, wrapU: Nullable<number>, wrapV: Nullable<number> = null, wrapR: Nullable<number> = null): void {
  2647. const target = this._getTextureTarget(texture);
  2648. if (wrapU) {
  2649. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(wrapU));
  2650. texture._cachedWrapU = wrapU;
  2651. }
  2652. if (wrapV) {
  2653. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(wrapV));
  2654. texture._cachedWrapV = wrapV;
  2655. }
  2656. if (wrapR) {
  2657. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(wrapR));
  2658. texture._cachedWrapR = wrapR;
  2659. }
  2660. this._bindTextureDirectly(target, null);
  2661. }
  2662. /** @hidden */
  2663. public _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number): void {
  2664. var width = (<{ width: number, height: number }>size).width || <number>size;
  2665. var height = (<{ width: number, height: number }>size).height || <number>size;
  2666. internalTexture.baseWidth = width;
  2667. internalTexture.baseHeight = height;
  2668. internalTexture.width = width;
  2669. internalTexture.height = height;
  2670. internalTexture.isReady = true;
  2671. internalTexture.samples = 1;
  2672. internalTexture.generateMipMaps = false;
  2673. internalTexture._generateDepthBuffer = true;
  2674. internalTexture._generateStencilBuffer = generateStencil;
  2675. internalTexture.samplingMode = bilinearFiltering ? Constants.TEXTURE_BILINEAR_SAMPLINGMODE : Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  2676. internalTexture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  2677. internalTexture._comparisonFunction = comparisonFunction;
  2678. var gl = this._gl;
  2679. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  2680. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  2681. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  2682. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  2683. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2684. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2685. if (comparisonFunction === 0) {
  2686. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Constants.LEQUAL);
  2687. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  2688. }
  2689. else {
  2690. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  2691. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  2692. }
  2693. }
  2694. /** @hidden */
  2695. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  2696. var gl = this._gl;
  2697. var target = gl.TEXTURE_2D;
  2698. if (texture.isCube) {
  2699. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  2700. }
  2701. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  2702. }
  2703. /** @hidden */
  2704. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0, babylonInternalFormat?: number, useTextureWidthAndHeight = false): void {
  2705. var gl = this._gl;
  2706. var textureType = this._getWebGLTextureType(texture.type);
  2707. var format = this._getInternalFormat(texture.format);
  2708. var internalFormat = babylonInternalFormat === undefined ? this._getRGBABufferInternalSizedFormat(texture.type, format) : this._getInternalFormat(babylonInternalFormat);
  2709. this._unpackFlipY(texture.invertY);
  2710. var target = gl.TEXTURE_2D;
  2711. if (texture.isCube) {
  2712. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  2713. }
  2714. const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);
  2715. const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);
  2716. const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  2717. const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  2718. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  2719. }
  2720. /** @hidden */
  2721. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  2722. var gl = this._gl;
  2723. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  2724. this._bindTextureDirectly(bindTarget, texture, true);
  2725. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  2726. this._bindTextureDirectly(bindTarget, null, true);
  2727. }
  2728. protected _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<ISceneLike>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  2729. var gl = this._gl;
  2730. if (!gl) {
  2731. return;
  2732. }
  2733. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  2734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2735. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2736. if (!noMipmap && !isCompressed) {
  2737. gl.generateMipmap(gl.TEXTURE_2D);
  2738. }
  2739. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  2740. // this.resetTextureCache();
  2741. if (scene) {
  2742. scene._removePendingData(texture);
  2743. }
  2744. texture.onLoadedObservable.notifyObservers(texture);
  2745. texture.onLoadedObservable.clear();
  2746. }
  2747. private _prepareWebGLTexture(texture: InternalTexture, scene: Nullable<ISceneLike>, width: number, height: number, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  2748. processFunction: (width: number, height: number, continuationCallback: () => void) => boolean, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE): void {
  2749. var maxTextureSize = this.getCaps().maxTextureSize;
  2750. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(width, maxTextureSize) : width);
  2751. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(height, maxTextureSize) : height);
  2752. var gl = this._gl;
  2753. if (!gl) {
  2754. return;
  2755. }
  2756. if (!texture._webGLTexture) {
  2757. // this.resetTextureCache();
  2758. if (scene) {
  2759. scene._removePendingData(texture);
  2760. }
  2761. return;
  2762. }
  2763. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2764. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  2765. texture.baseWidth = width;
  2766. texture.baseHeight = height;
  2767. texture.width = potWidth;
  2768. texture.height = potHeight;
  2769. texture.isReady = true;
  2770. if (processFunction(potWidth, potHeight, () => {
  2771. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  2772. })) {
  2773. // Returning as texture needs extra async steps
  2774. return;
  2775. }
  2776. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  2777. }
  2778. /** @hidden */
  2779. public _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  2780. var gl = this._gl;
  2781. // Create the depth/stencil buffer
  2782. if (generateStencilBuffer && generateDepthBuffer) {
  2783. return this._getDepthStencilBuffer(width, height, samples, gl.DEPTH_STENCIL, gl.DEPTH24_STENCIL8, gl.DEPTH_STENCIL_ATTACHMENT);
  2784. }
  2785. if (generateDepthBuffer) {
  2786. return this._getDepthStencilBuffer(width, height, samples, gl.DEPTH_COMPONENT16, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT);
  2787. }
  2788. if (generateStencilBuffer) {
  2789. return this._getDepthStencilBuffer(width, height, samples, gl.STENCIL_INDEX8, gl.STENCIL_INDEX8, gl.STENCIL_ATTACHMENT);
  2790. }
  2791. return null;
  2792. }
  2793. private _getDepthStencilBuffer = (width: number, height: number, samples: number, internalFormat: number, msInternalFormat: number, attachment: number) => {
  2794. var gl = this._gl;
  2795. const depthStencilBuffer = gl.createRenderbuffer();
  2796. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  2797. if (samples > 1) {
  2798. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, msInternalFormat, width, height);
  2799. } else {
  2800. gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, width, height);
  2801. }
  2802. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, depthStencilBuffer);
  2803. return depthStencilBuffer;
  2804. }
  2805. /** @hidden */
  2806. public _releaseFramebufferObjects(texture: InternalTexture): void {
  2807. var gl = this._gl;
  2808. if (texture._framebuffer) {
  2809. gl.deleteFramebuffer(texture._framebuffer);
  2810. texture._framebuffer = null;
  2811. }
  2812. if (texture._depthStencilBuffer) {
  2813. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  2814. texture._depthStencilBuffer = null;
  2815. }
  2816. if (texture._MSAAFramebuffer) {
  2817. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  2818. texture._MSAAFramebuffer = null;
  2819. }
  2820. if (texture._MSAARenderBuffer) {
  2821. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  2822. texture._MSAARenderBuffer = null;
  2823. }
  2824. }
  2825. /** @hidden */
  2826. public _releaseTexture(texture: InternalTexture): void {
  2827. this._releaseFramebufferObjects(texture);
  2828. this._deleteTexture(texture._webGLTexture);
  2829. // Unbind channels
  2830. this.unbindAllTextures();
  2831. var index = this._internalTexturesCache.indexOf(texture);
  2832. if (index !== -1) {
  2833. this._internalTexturesCache.splice(index, 1);
  2834. }
  2835. // Integrated fixed lod samplers.
  2836. if (texture._lodTextureHigh) {
  2837. texture._lodTextureHigh.dispose();
  2838. }
  2839. if (texture._lodTextureMid) {
  2840. texture._lodTextureMid.dispose();
  2841. }
  2842. if (texture._lodTextureLow) {
  2843. texture._lodTextureLow.dispose();
  2844. }
  2845. // Integrated irradiance map.
  2846. if (texture._irradianceTexture) {
  2847. texture._irradianceTexture.dispose();
  2848. }
  2849. }
  2850. protected _deleteTexture(texture: Nullable<WebGLTexture>): void {
  2851. this._gl.deleteTexture(texture);
  2852. }
  2853. protected _setProgram(program: WebGLProgram): void {
  2854. if (this._currentProgram !== program) {
  2855. this._gl.useProgram(program);
  2856. this._currentProgram = program;
  2857. }
  2858. }
  2859. protected _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  2860. /**
  2861. * Binds an effect to the webGL context
  2862. * @param effect defines the effect to bind
  2863. */
  2864. public bindSamplers(effect: Effect): void {
  2865. let webGLPipelineContext = effect.getPipelineContext() as WebGLPipelineContext;
  2866. this._setProgram(webGLPipelineContext.program!);
  2867. var samplers = effect.getSamplers();
  2868. for (var index = 0; index < samplers.length; index++) {
  2869. var uniform = effect.getUniform(samplers[index]);
  2870. if (uniform) {
  2871. this._boundUniforms[index] = uniform;
  2872. }
  2873. }
  2874. this._currentEffect = null;
  2875. }
  2876. private _activateCurrentTexture() {
  2877. if (this._currentTextureChannel !== this._activeChannel) {
  2878. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  2879. this._currentTextureChannel = this._activeChannel;
  2880. }
  2881. }
  2882. /** @hidden */
  2883. public _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): boolean {
  2884. var wasPreviouslyBound = false;
  2885. let isTextureForRendering = texture && texture._associatedChannel > -1;
  2886. if (forTextureDataUpdate && isTextureForRendering) {
  2887. this._activeChannel = texture!._associatedChannel;
  2888. }
  2889. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  2890. if (currentTextureBound !== texture || force) {
  2891. this._activateCurrentTexture();
  2892. if (texture && texture.isMultiview) {
  2893. this._gl.bindTexture(target, texture ? texture._colorTextureArray : null);
  2894. } else {
  2895. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  2896. }
  2897. this._boundTexturesCache[this._activeChannel] = texture;
  2898. if (texture) {
  2899. texture._associatedChannel = this._activeChannel;
  2900. }
  2901. } else if (forTextureDataUpdate) {
  2902. wasPreviouslyBound = true;
  2903. this._activateCurrentTexture();
  2904. }
  2905. if (isTextureForRendering && !forTextureDataUpdate) {
  2906. this._bindSamplerUniformToChannel(texture!._associatedChannel, this._activeChannel);
  2907. }
  2908. return wasPreviouslyBound;
  2909. }
  2910. /** @hidden */
  2911. public _bindTexture(channel: number, texture: Nullable<InternalTexture>): void {
  2912. if (channel === undefined) {
  2913. return;
  2914. }
  2915. if (texture) {
  2916. texture._associatedChannel = channel;
  2917. }
  2918. this._activeChannel = channel;
  2919. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  2920. }
  2921. /**
  2922. * Unbind all textures from the webGL context
  2923. */
  2924. public unbindAllTextures(): void {
  2925. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  2926. this._activeChannel = channel;
  2927. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2928. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2929. if (this.webGLVersion > 1) {
  2930. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  2931. this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null);
  2932. }
  2933. }
  2934. }
  2935. /**
  2936. * Sets a texture to the according uniform.
  2937. * @param channel The texture channel
  2938. * @param uniform The uniform to set
  2939. * @param texture The texture to apply
  2940. */
  2941. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<BaseTexture>): void {
  2942. if (channel === undefined) {
  2943. return;
  2944. }
  2945. if (uniform) {
  2946. this._boundUniforms[channel] = uniform;
  2947. }
  2948. this._setTexture(channel, texture);
  2949. }
  2950. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  2951. let uniform = this._boundUniforms[sourceSlot];
  2952. if (!uniform || uniform._currentState === destination) {
  2953. return;
  2954. }
  2955. this._gl.uniform1i(uniform, destination);
  2956. uniform._currentState = destination;
  2957. }
  2958. private _getTextureWrapMode(mode: number): number {
  2959. switch (mode) {
  2960. case Constants.TEXTURE_WRAP_ADDRESSMODE:
  2961. return this._gl.REPEAT;
  2962. case Constants.TEXTURE_CLAMP_ADDRESSMODE:
  2963. return this._gl.CLAMP_TO_EDGE;
  2964. case Constants.TEXTURE_MIRROR_ADDRESSMODE:
  2965. return this._gl.MIRRORED_REPEAT;
  2966. }
  2967. return this._gl.REPEAT;
  2968. }
  2969. protected _setTexture(channel: number, texture: Nullable<BaseTexture>, isPartOfTextureArray = false, depthStencilTexture = false): boolean {
  2970. // Not ready?
  2971. if (!texture) {
  2972. if (this._boundTexturesCache[channel] != null) {
  2973. this._activeChannel = channel;
  2974. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  2975. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  2976. if (this.webGLVersion > 1) {
  2977. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  2978. this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null);
  2979. }
  2980. }
  2981. return false;
  2982. }
  2983. // Video
  2984. if ((<VideoTexture>texture).video) {
  2985. this._activeChannel = channel;
  2986. (<VideoTexture>texture).update();
  2987. } else if (texture.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  2988. texture.delayLoad();
  2989. return false;
  2990. }
  2991. let internalTexture: InternalTexture;
  2992. if (depthStencilTexture) {
  2993. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  2994. }
  2995. else if (texture.isReady()) {
  2996. internalTexture = <InternalTexture>texture.getInternalTexture();
  2997. }
  2998. else if (texture.isCube) {
  2999. internalTexture = this.emptyCubeTexture;
  3000. }
  3001. else if (texture.is3D) {
  3002. internalTexture = this.emptyTexture3D;
  3003. }
  3004. else if (texture.is2DArray) {
  3005. internalTexture = this.emptyTexture2DArray;
  3006. }
  3007. else {
  3008. internalTexture = this.emptyTexture;
  3009. }
  3010. if (!isPartOfTextureArray && internalTexture) {
  3011. internalTexture._associatedChannel = channel;
  3012. }
  3013. let needToBind = true;
  3014. if (this._boundTexturesCache[channel] === internalTexture) {
  3015. if (!isPartOfTextureArray) {
  3016. this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel);
  3017. }
  3018. needToBind = false;
  3019. }
  3020. this._activeChannel = channel;
  3021. if (internalTexture && internalTexture.isMultiview) {
  3022. if (needToBind) {
  3023. this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, internalTexture, isPartOfTextureArray);
  3024. }
  3025. } else if (internalTexture && (internalTexture.is3D || internalTexture.is2DArray)) {
  3026. let is3D = internalTexture.is3D;
  3027. let target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY;
  3028. if (needToBind) {
  3029. this._bindTextureDirectly(target, internalTexture, isPartOfTextureArray);
  3030. }
  3031. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  3032. internalTexture._cachedWrapU = texture.wrapU;
  3033. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  3034. }
  3035. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  3036. internalTexture._cachedWrapV = texture.wrapV;
  3037. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  3038. }
  3039. if (is3D && internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  3040. internalTexture._cachedWrapR = texture.wrapR;
  3041. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  3042. }
  3043. this._setAnisotropicLevel(target, texture);
  3044. } else if (internalTexture && internalTexture.isCube) {
  3045. if (needToBind) {
  3046. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  3047. }
  3048. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3049. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3050. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  3051. var textureWrapMode = (texture.coordinatesMode !== Constants.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Constants.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  3052. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  3053. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  3054. }
  3055. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  3056. } else {
  3057. if (needToBind) {
  3058. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  3059. }
  3060. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  3061. internalTexture._cachedWrapU = texture.wrapU;
  3062. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  3063. }
  3064. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  3065. internalTexture._cachedWrapV = texture.wrapV;
  3066. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  3067. }
  3068. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  3069. }
  3070. return true;
  3071. }
  3072. /**
  3073. * Sets an array of texture to the webGL context
  3074. * @param channel defines the channel where the texture array must be set
  3075. * @param uniform defines the associated uniform location
  3076. * @param textures defines the array of textures to bind
  3077. */
  3078. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: BaseTexture[]): void {
  3079. if (channel === undefined || !uniform) {
  3080. return;
  3081. }
  3082. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  3083. this._textureUnits = new Int32Array(textures.length);
  3084. }
  3085. for (let i = 0; i < textures.length; i++) {
  3086. let texture = textures[i].getInternalTexture();
  3087. if (texture) {
  3088. this._textureUnits[i] = channel + i;
  3089. texture._associatedChannel = channel + i;
  3090. } else {
  3091. this._textureUnits[i] = -1;
  3092. }
  3093. }
  3094. this._gl.uniform1iv(uniform, this._textureUnits);
  3095. for (var index = 0; index < textures.length; index++) {
  3096. this._setTexture(this._textureUnits[index], textures[index], true);
  3097. }
  3098. }
  3099. /** @hidden */
  3100. public _setAnisotropicLevel(target: number, texture: BaseTexture) {
  3101. var internalTexture = texture.getInternalTexture();
  3102. if (!internalTexture) {
  3103. return;
  3104. }
  3105. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3106. var value = texture.anisotropicFilteringLevel;
  3107. if (internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  3108. && internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  3109. && internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR) {
  3110. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  3111. }
  3112. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  3113. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  3114. internalTexture._cachedAnisotropicFilteringLevel = value;
  3115. }
  3116. }
  3117. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  3118. this._bindTextureDirectly(target, texture, true, true);
  3119. this._gl.texParameterf(target, parameter, value);
  3120. }
  3121. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  3122. if (texture) {
  3123. this._bindTextureDirectly(target, texture, true, true);
  3124. }
  3125. this._gl.texParameteri(target, parameter, value);
  3126. }
  3127. /**
  3128. * Unbind all vertex attributes from the webGL context
  3129. */
  3130. public unbindAllAttributes() {
  3131. if (this._mustWipeVertexAttributes) {
  3132. this._mustWipeVertexAttributes = false;
  3133. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  3134. this.disableAttributeByIndex(i);
  3135. }
  3136. return;
  3137. }
  3138. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  3139. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  3140. continue;
  3141. }
  3142. this.disableAttributeByIndex(i);
  3143. }
  3144. }
  3145. /**
  3146. * Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
  3147. */
  3148. public releaseEffects() {
  3149. for (var name in this._compiledEffects) {
  3150. let webGLPipelineContext = this._compiledEffects[name].getPipelineContext() as WebGLPipelineContext;
  3151. this._deletePipelineContext(webGLPipelineContext);
  3152. }
  3153. this._compiledEffects = {};
  3154. }
  3155. /**
  3156. * Dispose and release all associated resources
  3157. */
  3158. public dispose(): void {
  3159. this.stopRenderLoop();
  3160. // Clear observables
  3161. if (this.onBeforeTextureInitObservable) {
  3162. this.onBeforeTextureInitObservable.clear();
  3163. }
  3164. // Empty texture
  3165. if (this._emptyTexture) {
  3166. this._releaseTexture(this._emptyTexture);
  3167. this._emptyTexture = null;
  3168. }
  3169. if (this._emptyCubeTexture) {
  3170. this._releaseTexture(this._emptyCubeTexture);
  3171. this._emptyCubeTexture = null;
  3172. }
  3173. // Release effects
  3174. this.releaseEffects();
  3175. // Unbind
  3176. this.unbindAllAttributes();
  3177. this._boundUniforms = [];
  3178. // Events
  3179. if (DomManagement.IsWindowObjectExist()) {
  3180. if (this._renderingCanvas) {
  3181. if (!this._doNotHandleContextLost) {
  3182. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  3183. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  3184. }
  3185. }
  3186. }
  3187. this._workingCanvas = null;
  3188. this._workingContext = null;
  3189. this._currentBufferPointers = [];
  3190. this._renderingCanvas = null;
  3191. this._currentProgram = null;
  3192. this._boundRenderFunction = null;
  3193. Effect.ResetCache();
  3194. // Abort active requests
  3195. for (let request of this._activeRequests) {
  3196. request.abort();
  3197. }
  3198. }
  3199. /**
  3200. * Attach a new callback raised when context lost event is fired
  3201. * @param callback defines the callback to call
  3202. */
  3203. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3204. if (this._renderingCanvas) {
  3205. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  3206. }
  3207. }
  3208. /**
  3209. * Attach a new callback raised when context restored event is fired
  3210. * @param callback defines the callback to call
  3211. */
  3212. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3213. if (this._renderingCanvas) {
  3214. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  3215. }
  3216. }
  3217. /**
  3218. * Get the current error code of the webGL context
  3219. * @returns the error code
  3220. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  3221. */
  3222. public getError(): number {
  3223. return this._gl.getError();
  3224. }
  3225. private _canRenderToFloatFramebuffer(): boolean {
  3226. if (this._webGLVersion > 1) {
  3227. return this._caps.colorBufferFloat;
  3228. }
  3229. return this._canRenderToFramebuffer(Constants.TEXTURETYPE_FLOAT);
  3230. }
  3231. private _canRenderToHalfFloatFramebuffer(): boolean {
  3232. if (this._webGLVersion > 1) {
  3233. return this._caps.colorBufferFloat;
  3234. }
  3235. return this._canRenderToFramebuffer(Constants.TEXTURETYPE_HALF_FLOAT);
  3236. }
  3237. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  3238. private _canRenderToFramebuffer(type: number): boolean {
  3239. let gl = this._gl;
  3240. //clear existing errors
  3241. while (gl.getError() !== gl.NO_ERROR) { }
  3242. let successful = true;
  3243. let texture = gl.createTexture();
  3244. gl.bindTexture(gl.TEXTURE_2D, texture);
  3245. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3246. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3248. let fb = gl.createFramebuffer();
  3249. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  3250. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3251. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  3252. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  3253. successful = successful && (gl.getError() === gl.NO_ERROR);
  3254. //try render by clearing frame buffer's color buffer
  3255. if (successful) {
  3256. gl.clear(gl.COLOR_BUFFER_BIT);
  3257. successful = successful && (gl.getError() === gl.NO_ERROR);
  3258. }
  3259. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  3260. if (successful) {
  3261. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  3262. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3263. let readFormat = gl.RGBA;
  3264. let readType = gl.UNSIGNED_BYTE;
  3265. let buffer = new Uint8Array(4);
  3266. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  3267. successful = successful && (gl.getError() === gl.NO_ERROR);
  3268. }
  3269. //clean up
  3270. gl.deleteTexture(texture);
  3271. gl.deleteFramebuffer(fb);
  3272. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3273. //clear accumulated errors
  3274. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  3275. return successful;
  3276. }
  3277. /** @hidden */
  3278. public _getWebGLTextureType(type: number): number {
  3279. if (this._webGLVersion === 1) {
  3280. switch (type) {
  3281. case Constants.TEXTURETYPE_FLOAT:
  3282. return this._gl.FLOAT;
  3283. case Constants.TEXTURETYPE_HALF_FLOAT:
  3284. return this._gl.HALF_FLOAT_OES;
  3285. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3286. return this._gl.UNSIGNED_BYTE;
  3287. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3288. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  3289. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3290. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  3291. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3292. return this._gl.UNSIGNED_SHORT_5_6_5;
  3293. }
  3294. return this._gl.UNSIGNED_BYTE;
  3295. }
  3296. switch (type) {
  3297. case Constants.TEXTURETYPE_BYTE:
  3298. return this._gl.BYTE;
  3299. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3300. return this._gl.UNSIGNED_BYTE;
  3301. case Constants.TEXTURETYPE_SHORT:
  3302. return this._gl.SHORT;
  3303. case Constants.TEXTURETYPE_UNSIGNED_SHORT:
  3304. return this._gl.UNSIGNED_SHORT;
  3305. case Constants.TEXTURETYPE_INT:
  3306. return this._gl.INT;
  3307. case Constants.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  3308. return this._gl.UNSIGNED_INT;
  3309. case Constants.TEXTURETYPE_FLOAT:
  3310. return this._gl.FLOAT;
  3311. case Constants.TEXTURETYPE_HALF_FLOAT:
  3312. return this._gl.HALF_FLOAT;
  3313. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3314. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  3315. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3316. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  3317. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3318. return this._gl.UNSIGNED_SHORT_5_6_5;
  3319. case Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  3320. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  3321. case Constants.TEXTURETYPE_UNSIGNED_INT_24_8:
  3322. return this._gl.UNSIGNED_INT_24_8;
  3323. case Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  3324. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  3325. case Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  3326. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  3327. case Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  3328. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  3329. }
  3330. return this._gl.UNSIGNED_BYTE;
  3331. }
  3332. /** @hidden */
  3333. public _getInternalFormat(format: number): number {
  3334. var internalFormat = this._gl.RGBA;
  3335. switch (format) {
  3336. case Constants.TEXTUREFORMAT_ALPHA:
  3337. internalFormat = this._gl.ALPHA;
  3338. break;
  3339. case Constants.TEXTUREFORMAT_LUMINANCE:
  3340. internalFormat = this._gl.LUMINANCE;
  3341. break;
  3342. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3343. internalFormat = this._gl.LUMINANCE_ALPHA;
  3344. break;
  3345. case Constants.TEXTUREFORMAT_RED:
  3346. internalFormat = this._gl.RED;
  3347. break;
  3348. case Constants.TEXTUREFORMAT_RG:
  3349. internalFormat = this._gl.RG;
  3350. break;
  3351. case Constants.TEXTUREFORMAT_RGB:
  3352. internalFormat = this._gl.RGB;
  3353. break;
  3354. case Constants.TEXTUREFORMAT_RGBA:
  3355. internalFormat = this._gl.RGBA;
  3356. break;
  3357. }
  3358. if (this._webGLVersion > 1) {
  3359. switch (format) {
  3360. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3361. internalFormat = this._gl.RED_INTEGER;
  3362. break;
  3363. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3364. internalFormat = this._gl.RG_INTEGER;
  3365. break;
  3366. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3367. internalFormat = this._gl.RGB_INTEGER;
  3368. break;
  3369. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3370. internalFormat = this._gl.RGBA_INTEGER;
  3371. break;
  3372. }
  3373. }
  3374. return internalFormat;
  3375. }
  3376. /** @hidden */
  3377. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  3378. if (this._webGLVersion === 1) {
  3379. if (format !== undefined) {
  3380. switch (format) {
  3381. case Constants.TEXTUREFORMAT_ALPHA:
  3382. return this._gl.ALPHA;
  3383. case Constants.TEXTUREFORMAT_LUMINANCE:
  3384. return this._gl.LUMINANCE;
  3385. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3386. return this._gl.LUMINANCE_ALPHA;
  3387. }
  3388. }
  3389. return this._gl.RGBA;
  3390. }
  3391. switch (type) {
  3392. case Constants.TEXTURETYPE_BYTE:
  3393. switch (format) {
  3394. case Constants.TEXTUREFORMAT_RED:
  3395. return this._gl.R8_SNORM;
  3396. case Constants.TEXTUREFORMAT_RG:
  3397. return this._gl.RG8_SNORM;
  3398. case Constants.TEXTUREFORMAT_RGB:
  3399. return this._gl.RGB8_SNORM;
  3400. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3401. return this._gl.R8I;
  3402. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3403. return this._gl.RG8I;
  3404. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3405. return this._gl.RGB8I;
  3406. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3407. return this._gl.RGBA8I;
  3408. default:
  3409. return this._gl.RGBA8_SNORM;
  3410. }
  3411. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3412. switch (format) {
  3413. case Constants.TEXTUREFORMAT_RED:
  3414. return this._gl.R8;
  3415. case Constants.TEXTUREFORMAT_RG:
  3416. return this._gl.RG8;
  3417. case Constants.TEXTUREFORMAT_RGB:
  3418. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  3419. case Constants.TEXTUREFORMAT_RGBA:
  3420. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  3421. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3422. return this._gl.R8UI;
  3423. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3424. return this._gl.RG8UI;
  3425. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3426. return this._gl.RGB8UI;
  3427. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3428. return this._gl.RGBA8UI;
  3429. case Constants.TEXTUREFORMAT_ALPHA:
  3430. return this._gl.ALPHA;
  3431. case Constants.TEXTUREFORMAT_LUMINANCE:
  3432. return this._gl.LUMINANCE;
  3433. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3434. return this._gl.LUMINANCE_ALPHA;
  3435. default:
  3436. return this._gl.RGBA8;
  3437. }
  3438. case Constants.TEXTURETYPE_SHORT:
  3439. switch (format) {
  3440. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3441. return this._gl.R16I;
  3442. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3443. return this._gl.RG16I;
  3444. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3445. return this._gl.RGB16I;
  3446. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3447. return this._gl.RGBA16I;
  3448. default:
  3449. return this._gl.RGBA16I;
  3450. }
  3451. case Constants.TEXTURETYPE_UNSIGNED_SHORT:
  3452. switch (format) {
  3453. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3454. return this._gl.R16UI;
  3455. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3456. return this._gl.RG16UI;
  3457. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3458. return this._gl.RGB16UI;
  3459. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3460. return this._gl.RGBA16UI;
  3461. default:
  3462. return this._gl.RGBA16UI;
  3463. }
  3464. case Constants.TEXTURETYPE_INT:
  3465. switch (format) {
  3466. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3467. return this._gl.R32I;
  3468. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3469. return this._gl.RG32I;
  3470. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3471. return this._gl.RGB32I;
  3472. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3473. return this._gl.RGBA32I;
  3474. default:
  3475. return this._gl.RGBA32I;
  3476. }
  3477. case Constants.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  3478. switch (format) {
  3479. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3480. return this._gl.R32UI;
  3481. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3482. return this._gl.RG32UI;
  3483. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3484. return this._gl.RGB32UI;
  3485. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3486. return this._gl.RGBA32UI;
  3487. default:
  3488. return this._gl.RGBA32UI;
  3489. }
  3490. case Constants.TEXTURETYPE_FLOAT:
  3491. switch (format) {
  3492. case Constants.TEXTUREFORMAT_RED:
  3493. return this._gl.R32F; // By default. Other possibility is R16F.
  3494. case Constants.TEXTUREFORMAT_RG:
  3495. return this._gl.RG32F; // By default. Other possibility is RG16F.
  3496. case Constants.TEXTUREFORMAT_RGB:
  3497. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  3498. case Constants.TEXTUREFORMAT_RGBA:
  3499. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  3500. default:
  3501. return this._gl.RGBA32F;
  3502. }
  3503. case Constants.TEXTURETYPE_HALF_FLOAT:
  3504. switch (format) {
  3505. case Constants.TEXTUREFORMAT_RED:
  3506. return this._gl.R16F;
  3507. case Constants.TEXTUREFORMAT_RG:
  3508. return this._gl.RG16F;
  3509. case Constants.TEXTUREFORMAT_RGB:
  3510. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  3511. case Constants.TEXTUREFORMAT_RGBA:
  3512. return this._gl.RGBA16F;
  3513. default:
  3514. return this._gl.RGBA16F;
  3515. }
  3516. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3517. return this._gl.RGB565;
  3518. case Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  3519. return this._gl.R11F_G11F_B10F;
  3520. case Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  3521. return this._gl.RGB9_E5;
  3522. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3523. return this._gl.RGBA4;
  3524. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3525. return this._gl.RGB5_A1;
  3526. case Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  3527. switch (format) {
  3528. case Constants.TEXTUREFORMAT_RGBA:
  3529. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  3530. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3531. return this._gl.RGB10_A2UI;
  3532. default:
  3533. return this._gl.RGB10_A2;
  3534. }
  3535. }
  3536. return this._gl.RGBA8;
  3537. }
  3538. /** @hidden */
  3539. public _getRGBAMultiSampleBufferFormat(type: number): number {
  3540. if (type === Constants.TEXTURETYPE_FLOAT) {
  3541. return this._gl.RGBA32F;
  3542. }
  3543. else if (type === Constants.TEXTURETYPE_HALF_FLOAT) {
  3544. return this._gl.RGBA16F;
  3545. }
  3546. return this._gl.RGBA8;
  3547. }
  3548. /** @hidden */
  3549. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void,
  3550. offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: IWebRequest, exception?: any) => void): IFileRequest {
  3551. let request = FileTools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  3552. this._activeRequests.push(request);
  3553. request.onCompleteObservable.add((request) => {
  3554. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  3555. });
  3556. return request;
  3557. }
  3558. /**
  3559. * Reads pixels from the current frame buffer. Please note that this function can be slow
  3560. * @param x defines the x coordinate of the rectangle where pixels must be read
  3561. * @param y defines the y coordinate of the rectangle where pixels must be read
  3562. * @param width defines the width of the rectangle where pixels must be read
  3563. * @param height defines the height of the rectangle where pixels must be read
  3564. * @param hasAlpha defines wether the output should have alpha or not (defaults to true)
  3565. * @returns a Uint8Array containing RGBA colors
  3566. */
  3567. public readPixels(x: number, y: number, width: number, height: number, hasAlpha = true): Uint8Array {
  3568. const numChannels = hasAlpha ? 4 : 3;
  3569. const format = hasAlpha ? this._gl.RGBA : this._gl.RGB;
  3570. const data = new Uint8Array(height * width * numChannels);
  3571. this._gl.readPixels(x, y, width, height, format, this._gl.UNSIGNED_BYTE, data);
  3572. return data;
  3573. }
  3574. // Statics
  3575. /**
  3576. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  3577. * @returns true if the engine can be created
  3578. * @ignorenaming
  3579. */
  3580. public static isSupported(): boolean {
  3581. try {
  3582. var tempcanvas = CanvasGenerator.CreateCanvas(1, 1);
  3583. var gl = tempcanvas.getContext("webgl") || (tempcanvas as any).getContext("experimental-webgl");
  3584. return gl != null && !!window.WebGLRenderingContext;
  3585. } catch (e) {
  3586. return false;
  3587. }
  3588. }
  3589. /**
  3590. * Find the next highest power of two.
  3591. * @param x Number to start search from.
  3592. * @return Next highest power of two.
  3593. */
  3594. public static CeilingPOT(x: number): number {
  3595. x--;
  3596. x |= x >> 1;
  3597. x |= x >> 2;
  3598. x |= x >> 4;
  3599. x |= x >> 8;
  3600. x |= x >> 16;
  3601. x++;
  3602. return x;
  3603. }
  3604. /**
  3605. * Find the next lowest power of two.
  3606. * @param x Number to start search from.
  3607. * @return Next lowest power of two.
  3608. */
  3609. public static FloorPOT(x: number): number {
  3610. x = x | (x >> 1);
  3611. x = x | (x >> 2);
  3612. x = x | (x >> 4);
  3613. x = x | (x >> 8);
  3614. x = x | (x >> 16);
  3615. return x - (x >> 1);
  3616. }
  3617. /**
  3618. * Find the nearest power of two.
  3619. * @param x Number to start search from.
  3620. * @return Next nearest power of two.
  3621. */
  3622. public static NearestPOT(x: number): number {
  3623. var c = ThinEngine.CeilingPOT(x);
  3624. var f = ThinEngine.FloorPOT(x);
  3625. return (c - x) > (x - f) ? f : c;
  3626. }
  3627. /**
  3628. * Get the closest exponent of two
  3629. * @param value defines the value to approximate
  3630. * @param max defines the maximum value to return
  3631. * @param mode defines how to define the closest value
  3632. * @returns closest exponent of two of the given value
  3633. */
  3634. public static GetExponentOfTwo(value: number, max: number, mode = Constants.SCALEMODE_NEAREST): number {
  3635. let pot;
  3636. switch (mode) {
  3637. case Constants.SCALEMODE_FLOOR:
  3638. pot = ThinEngine.FloorPOT(value);
  3639. break;
  3640. case Constants.SCALEMODE_NEAREST:
  3641. pot = ThinEngine.NearestPOT(value);
  3642. break;
  3643. case Constants.SCALEMODE_CEILING:
  3644. default:
  3645. pot = ThinEngine.CeilingPOT(value);
  3646. break;
  3647. }
  3648. return Math.min(pot, max);
  3649. }
  3650. /**
  3651. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  3652. * @param func - the function to be called
  3653. * @param requester - the object that will request the next frame. Falls back to window.
  3654. * @returns frame number
  3655. */
  3656. public static QueueNewFrame(func: () => void, requester?: any): number {
  3657. if (!DomManagement.IsWindowObjectExist()) {
  3658. if (typeof requestAnimationFrame !== "undefined") {
  3659. return requestAnimationFrame(func);
  3660. }
  3661. return setTimeout(func, 16);
  3662. }
  3663. if (!requester) {
  3664. requester = window;
  3665. }
  3666. if (requester.requestAnimationFrame) {
  3667. return requester.requestAnimationFrame(func);
  3668. }
  3669. else if (requester.msRequestAnimationFrame) {
  3670. return requester.msRequestAnimationFrame(func);
  3671. }
  3672. else if (requester.webkitRequestAnimationFrame) {
  3673. return requester.webkitRequestAnimationFrame(func);
  3674. }
  3675. else if (requester.mozRequestAnimationFrame) {
  3676. return requester.mozRequestAnimationFrame(func);
  3677. }
  3678. else if (requester.oRequestAnimationFrame) {
  3679. return requester.oRequestAnimationFrame(func);
  3680. }
  3681. else {
  3682. return window.setTimeout(func, 16);
  3683. }
  3684. }
  3685. /**
  3686. * Gets host document
  3687. * @returns the host document object
  3688. */
  3689. public getHostDocument(): Nullable<Document> {
  3690. if (this._renderingCanvas && this._renderingCanvas.ownerDocument) {
  3691. return this._renderingCanvas.ownerDocument;
  3692. }
  3693. return document;
  3694. }
  3695. }