thinEngine.ts 175 KB

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