thinEngine.ts 190 KB

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