thinEngine.ts 166 KB

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