thinEngine.ts 183 KB

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