thinEngine.ts 177 KB

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