thinEngine.ts 175 KB

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