thinEngine.ts 185 KB

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