thinEngine.ts 174 KB

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