thinEngine.ts 177 KB

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