thinEngine.ts 191 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735
  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, overrideVertexBuffers?: { [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: Nullable<VertexBuffer> = null;
  1519. if (overrideVertexBuffers) {
  1520. vertexBuffer = overrideVertexBuffers[ai];
  1521. }
  1522. if (!vertexBuffer) {
  1523. vertexBuffer = vertexBuffers[ai];
  1524. }
  1525. if (!vertexBuffer) {
  1526. continue;
  1527. }
  1528. this._gl.enableVertexAttribArray(order);
  1529. if (!this._vaoRecordInProgress) {
  1530. this._vertexAttribArraysEnabled[order] = true;
  1531. }
  1532. var buffer = vertexBuffer.getBuffer();
  1533. if (buffer) {
  1534. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  1535. if (vertexBuffer.getIsInstanced()) {
  1536. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  1537. if (!this._vaoRecordInProgress) {
  1538. this._currentInstanceLocations.push(order);
  1539. this._currentInstanceBuffers.push(buffer);
  1540. }
  1541. }
  1542. }
  1543. }
  1544. }
  1545. }
  1546. /**
  1547. * Records a vertex array object
  1548. * @see https://doc.babylonjs.com/features/webgl2#vertex-array-objects
  1549. * @param vertexBuffers defines the list of vertex buffers to store
  1550. * @param indexBuffer defines the index buffer to store
  1551. * @param effect defines the effect to store
  1552. * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers
  1553. * @returns the new vertex array object
  1554. */
  1555. public recordVertexArrayObject(vertexBuffers: { [key: string]: VertexBuffer; }, indexBuffer: Nullable<DataBuffer>, effect: Effect, overrideVertexBuffers?: { [kind: string]: Nullable<VertexBuffer>}): WebGLVertexArrayObject {
  1556. var vao = this._gl.createVertexArray();
  1557. this._vaoRecordInProgress = true;
  1558. this._gl.bindVertexArray(vao);
  1559. this._mustWipeVertexAttributes = true;
  1560. this._bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers);
  1561. this.bindIndexBuffer(indexBuffer);
  1562. this._vaoRecordInProgress = false;
  1563. this._gl.bindVertexArray(null);
  1564. return vao;
  1565. }
  1566. /**
  1567. * Bind a specific vertex array object
  1568. * @see https://doc.babylonjs.com/features/webgl2#vertex-array-objects
  1569. * @param vertexArrayObject defines the vertex array object to bind
  1570. * @param indexBuffer defines the index buffer to bind
  1571. */
  1572. public bindVertexArrayObject(vertexArrayObject: WebGLVertexArrayObject, indexBuffer: Nullable<DataBuffer>): void {
  1573. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  1574. this._cachedVertexArrayObject = vertexArrayObject;
  1575. this._gl.bindVertexArray(vertexArrayObject);
  1576. this._cachedVertexBuffers = null;
  1577. this._cachedIndexBuffer = null;
  1578. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  1579. this._mustWipeVertexAttributes = true;
  1580. }
  1581. }
  1582. /**
  1583. * Bind webGl buffers directly to the webGL context
  1584. * @param vertexBuffer defines the vertex buffer to bind
  1585. * @param indexBuffer defines the index buffer to bind
  1586. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  1587. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  1588. * @param effect defines the effect associated with the vertex buffer
  1589. */
  1590. public bindBuffersDirectly(vertexBuffer: DataBuffer, indexBuffer: DataBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void {
  1591. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  1592. this._cachedVertexBuffers = vertexBuffer;
  1593. this._cachedEffectForVertexBuffers = effect;
  1594. let attributesCount = effect.getAttributesCount();
  1595. this._unbindVertexArrayObject();
  1596. this.unbindAllAttributes();
  1597. var offset = 0;
  1598. for (var index = 0; index < attributesCount; index++) {
  1599. if (index < vertexDeclaration.length) {
  1600. var order = effect.getAttributeLocation(index);
  1601. if (order >= 0) {
  1602. this._gl.enableVertexAttribArray(order);
  1603. this._vertexAttribArraysEnabled[order] = true;
  1604. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  1605. }
  1606. offset += vertexDeclaration[index] * 4;
  1607. }
  1608. }
  1609. }
  1610. this._bindIndexBufferWithCache(indexBuffer);
  1611. }
  1612. private _unbindVertexArrayObject(): void {
  1613. if (!this._cachedVertexArrayObject) {
  1614. return;
  1615. }
  1616. this._cachedVertexArrayObject = null;
  1617. this._gl.bindVertexArray(null);
  1618. }
  1619. /**
  1620. * Bind a list of vertex buffers to the webGL context
  1621. * @param vertexBuffers defines the list of vertex buffers to bind
  1622. * @param indexBuffer defines the index buffer to bind
  1623. * @param effect defines the effect associated with the vertex buffers
  1624. * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers
  1625. */
  1626. public bindBuffers(vertexBuffers: { [key: string]: Nullable<VertexBuffer> }, indexBuffer: Nullable<DataBuffer>, effect: Effect, overrideVertexBuffers?: {[kind: string]: Nullable<VertexBuffer>}): void {
  1627. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  1628. this._cachedVertexBuffers = vertexBuffers;
  1629. this._cachedEffectForVertexBuffers = effect;
  1630. this._bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers);
  1631. }
  1632. this._bindIndexBufferWithCache(indexBuffer);
  1633. }
  1634. /**
  1635. * Unbind all instance attributes
  1636. */
  1637. public unbindInstanceAttributes() {
  1638. var boundBuffer;
  1639. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  1640. var instancesBuffer = this._currentInstanceBuffers[i];
  1641. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  1642. boundBuffer = instancesBuffer;
  1643. this.bindArrayBuffer(instancesBuffer);
  1644. }
  1645. var offsetLocation = this._currentInstanceLocations[i];
  1646. this._gl.vertexAttribDivisor(offsetLocation, 0);
  1647. }
  1648. this._currentInstanceBuffers.length = 0;
  1649. this._currentInstanceLocations.length = 0;
  1650. }
  1651. /**
  1652. * Release and free the memory of a vertex array object
  1653. * @param vao defines the vertex array object to delete
  1654. */
  1655. public releaseVertexArrayObject(vao: WebGLVertexArrayObject) {
  1656. this._gl.deleteVertexArray(vao);
  1657. }
  1658. /** @hidden */
  1659. public _releaseBuffer(buffer: DataBuffer): boolean {
  1660. buffer.references--;
  1661. if (buffer.references === 0) {
  1662. this._deleteBuffer(buffer);
  1663. return true;
  1664. }
  1665. return false;
  1666. }
  1667. protected _deleteBuffer(buffer: DataBuffer): void {
  1668. this._gl.deleteBuffer(buffer.underlyingResource);
  1669. }
  1670. /**
  1671. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  1672. * @param instancesBuffer defines the webGL buffer to update and bind
  1673. * @param data defines the data to store in the buffer
  1674. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  1675. */
  1676. public updateAndBindInstancesBuffer(instancesBuffer: DataBuffer, data: Float32Array, offsetLocations: number[] | InstancingAttributeInfo[]): void {
  1677. this.bindArrayBuffer(instancesBuffer);
  1678. if (data) {
  1679. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  1680. }
  1681. if ((<any>offsetLocations[0]).index !== undefined) {
  1682. this.bindInstancesBuffer(instancesBuffer, offsetLocations as any, true);
  1683. } else {
  1684. for (let index = 0; index < 4; index++) {
  1685. let offsetLocation = <number>offsetLocations[index];
  1686. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  1687. this._gl.enableVertexAttribArray(offsetLocation);
  1688. this._vertexAttribArraysEnabled[offsetLocation] = true;
  1689. }
  1690. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  1691. this._gl.vertexAttribDivisor(offsetLocation, 1);
  1692. this._currentInstanceLocations.push(offsetLocation);
  1693. this._currentInstanceBuffers.push(instancesBuffer);
  1694. }
  1695. }
  1696. }
  1697. /**
  1698. * Bind the content of a webGL buffer used with instantiation
  1699. * @param instancesBuffer defines the webGL buffer to bind
  1700. * @param attributesInfo defines the offsets or attributes information used to determine where data must be stored in the buffer
  1701. * @param computeStride defines Whether to compute the strides from the info or use the default 0
  1702. */
  1703. public bindInstancesBuffer(instancesBuffer: DataBuffer, attributesInfo: InstancingAttributeInfo[], computeStride = true): void {
  1704. this.bindArrayBuffer(instancesBuffer);
  1705. let stride = 0;
  1706. if (computeStride) {
  1707. for (let i = 0; i < attributesInfo.length; i++) {
  1708. let ai = attributesInfo[i];
  1709. stride += ai.attributeSize * 4;
  1710. }
  1711. }
  1712. for (let i = 0; i < attributesInfo.length; i++) {
  1713. let ai = attributesInfo[i];
  1714. if (ai.index === undefined) {
  1715. ai.index = this._currentEffect!.getAttributeLocationByName(ai.attributeName);
  1716. }
  1717. if (ai.index < 0) {
  1718. continue;
  1719. }
  1720. if (!this._vertexAttribArraysEnabled[ai.index]) {
  1721. this._gl.enableVertexAttribArray(ai.index);
  1722. this._vertexAttribArraysEnabled[ai.index] = true;
  1723. }
  1724. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attributeType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  1725. this._gl.vertexAttribDivisor(ai.index, ai.divisor === undefined ? 1 : ai.divisor);
  1726. this._currentInstanceLocations.push(ai.index);
  1727. this._currentInstanceBuffers.push(instancesBuffer);
  1728. }
  1729. }
  1730. /**
  1731. * Disable the instance attribute corresponding to the name in parameter
  1732. * @param name defines the name of the attribute to disable
  1733. */
  1734. public disableInstanceAttributeByName(name: string) {
  1735. if (!this._currentEffect) {
  1736. return;
  1737. }
  1738. const attributeLocation = this._currentEffect.getAttributeLocationByName(name);
  1739. this.disableInstanceAttribute(attributeLocation);
  1740. }
  1741. /**
  1742. * Disable the instance attribute corresponding to the location in parameter
  1743. * @param attributeLocation defines the attribute location of the attribute to disable
  1744. */
  1745. public disableInstanceAttribute(attributeLocation: number) {
  1746. let shouldClean = false;
  1747. let index: number;
  1748. while ((index = this._currentInstanceLocations.indexOf(attributeLocation)) !== -1) {
  1749. this._currentInstanceLocations.splice(index, 1);
  1750. this._currentInstanceBuffers.splice(index, 1);
  1751. shouldClean = true;
  1752. index = this._currentInstanceLocations.indexOf(attributeLocation);
  1753. }
  1754. if (shouldClean) {
  1755. this._gl.vertexAttribDivisor(attributeLocation, 0);
  1756. this.disableAttributeByIndex(attributeLocation);
  1757. }
  1758. }
  1759. /**
  1760. * Disable the attribute corresponding to the location in parameter
  1761. * @param attributeLocation defines the attribute location of the attribute to disable
  1762. */
  1763. public disableAttributeByIndex(attributeLocation: number) {
  1764. this._gl.disableVertexAttribArray(attributeLocation);
  1765. this._vertexAttribArraysEnabled[attributeLocation] = false;
  1766. this._currentBufferPointers[attributeLocation].active = false;
  1767. }
  1768. /**
  1769. * Send a draw order
  1770. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  1771. * @param indexStart defines the starting index
  1772. * @param indexCount defines the number of index to draw
  1773. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1774. */
  1775. public draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void {
  1776. this.drawElementsType(useTriangles ? Constants.MATERIAL_TriangleFillMode : Constants.MATERIAL_WireFrameFillMode, indexStart, indexCount, instancesCount);
  1777. }
  1778. /**
  1779. * Draw a list of points
  1780. * @param verticesStart defines the index of first vertex to draw
  1781. * @param verticesCount defines the count of vertices to draw
  1782. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1783. */
  1784. public drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1785. this.drawArraysType(Constants.MATERIAL_PointFillMode, verticesStart, verticesCount, instancesCount);
  1786. }
  1787. /**
  1788. * Draw a list of unindexed primitives
  1789. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  1790. * @param verticesStart defines the index of first vertex to draw
  1791. * @param verticesCount defines the count of vertices to draw
  1792. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1793. */
  1794. public drawUnIndexed(useTriangles: boolean, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1795. this.drawArraysType(useTriangles ? Constants.MATERIAL_TriangleFillMode : Constants.MATERIAL_WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  1796. }
  1797. /**
  1798. * Draw a list of indexed primitives
  1799. * @param fillMode defines the primitive to use
  1800. * @param indexStart defines the starting index
  1801. * @param indexCount defines the number of index to draw
  1802. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1803. */
  1804. public drawElementsType(fillMode: number, indexStart: number, indexCount: number, instancesCount?: number): void {
  1805. // Apply states
  1806. this.applyStates();
  1807. this._reportDrawCall();
  1808. // Render
  1809. const drawMode = this._drawMode(fillMode);
  1810. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  1811. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  1812. if (instancesCount) {
  1813. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  1814. } else {
  1815. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  1816. }
  1817. }
  1818. /**
  1819. * Draw a list of unindexed primitives
  1820. * @param fillMode defines the primitive to use
  1821. * @param verticesStart defines the index of first vertex to draw
  1822. * @param verticesCount defines the count of vertices to draw
  1823. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  1824. */
  1825. public drawArraysType(fillMode: number, verticesStart: number, verticesCount: number, instancesCount?: number): void {
  1826. // Apply states
  1827. this.applyStates();
  1828. this._reportDrawCall();
  1829. const drawMode = this._drawMode(fillMode);
  1830. if (instancesCount) {
  1831. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  1832. } else {
  1833. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  1834. }
  1835. }
  1836. private _drawMode(fillMode: number): number {
  1837. switch (fillMode) {
  1838. // Triangle views
  1839. case Constants.MATERIAL_TriangleFillMode:
  1840. return this._gl.TRIANGLES;
  1841. case Constants.MATERIAL_PointFillMode:
  1842. return this._gl.POINTS;
  1843. case Constants.MATERIAL_WireFrameFillMode:
  1844. return this._gl.LINES;
  1845. // Draw modes
  1846. case Constants.MATERIAL_PointListDrawMode:
  1847. return this._gl.POINTS;
  1848. case Constants.MATERIAL_LineListDrawMode:
  1849. return this._gl.LINES;
  1850. case Constants.MATERIAL_LineLoopDrawMode:
  1851. return this._gl.LINE_LOOP;
  1852. case Constants.MATERIAL_LineStripDrawMode:
  1853. return this._gl.LINE_STRIP;
  1854. case Constants.MATERIAL_TriangleStripDrawMode:
  1855. return this._gl.TRIANGLE_STRIP;
  1856. case Constants.MATERIAL_TriangleFanDrawMode:
  1857. return this._gl.TRIANGLE_FAN;
  1858. default:
  1859. return this._gl.TRIANGLES;
  1860. }
  1861. }
  1862. /** @hidden */
  1863. protected _reportDrawCall() {
  1864. // Will be implemented by children
  1865. }
  1866. // Shaders
  1867. /** @hidden */
  1868. public _releaseEffect(effect: Effect): void {
  1869. if (this._compiledEffects[effect._key]) {
  1870. delete this._compiledEffects[effect._key];
  1871. this._deletePipelineContext(effect.getPipelineContext() as WebGLPipelineContext);
  1872. }
  1873. }
  1874. /** @hidden */
  1875. public _deletePipelineContext(pipelineContext: IPipelineContext): void {
  1876. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  1877. if (webGLPipelineContext && webGLPipelineContext.program) {
  1878. webGLPipelineContext.program.__SPECTOR_rebuildProgram = null;
  1879. this._gl.deleteProgram(webGLPipelineContext.program);
  1880. }
  1881. }
  1882. /**
  1883. * Create a new effect (used to store vertex/fragment shaders)
  1884. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  1885. * @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object
  1886. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  1887. * @param samplers defines an array of string used to represent textures
  1888. * @param defines defines the string containing the defines to use to compile the shaders
  1889. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  1890. * @param onCompiled defines a function to call when the effect creation is successful
  1891. * @param onError defines a function to call when the effect creation has failed
  1892. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  1893. * @returns the new Effect
  1894. */
  1895. public createEffect(baseName: any, attributesNamesOrOptions: string[] | IEffectCreationOptions, uniformsNamesOrEngine: string[] | ThinEngine, samplers?: string[], defines?: string,
  1896. fallbacks?: IEffectFallbacks,
  1897. onCompiled?: Nullable<(effect: Effect) => void>, onError?: Nullable<(effect: Effect, errors: string) => void>, indexParameters?: any): Effect {
  1898. var vertex = baseName.vertexElement || baseName.vertex || baseName.vertexToken || baseName.vertexSource || baseName;
  1899. var fragment = baseName.fragmentElement || baseName.fragment || baseName.fragmentToken || baseName.fragmentSource || baseName;
  1900. var name = vertex + "+" + fragment + "@" + (defines ? defines : (<IEffectCreationOptions>attributesNamesOrOptions).defines);
  1901. if (this._compiledEffects[name]) {
  1902. var compiledEffect = <Effect>this._compiledEffects[name];
  1903. if (onCompiled && compiledEffect.isReady()) {
  1904. onCompiled(compiledEffect);
  1905. }
  1906. return compiledEffect;
  1907. }
  1908. var effect = new Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name);
  1909. this._compiledEffects[name] = effect;
  1910. return effect;
  1911. }
  1912. protected static _ConcatenateShader(source: string, defines: Nullable<string>, shaderVersion: string = ""): string {
  1913. return shaderVersion + (defines ? defines + "\n" : "") + source;
  1914. }
  1915. private _compileShader(source: string, type: string, defines: Nullable<string>, shaderVersion: string): WebGLShader {
  1916. return this._compileRawShader(ThinEngine._ConcatenateShader(source, defines, shaderVersion), type);
  1917. }
  1918. private _compileRawShader(source: string, type: string): WebGLShader {
  1919. var gl = this._gl;
  1920. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  1921. if (!shader) {
  1922. throw new Error("Something went wrong while compile the shader.");
  1923. }
  1924. gl.shaderSource(shader, source);
  1925. gl.compileShader(shader);
  1926. return shader;
  1927. }
  1928. /** @hidden */
  1929. public _getShaderSource(shader: WebGLShader): Nullable<string> {
  1930. return this._gl.getShaderSource(shader);
  1931. }
  1932. /**
  1933. * Directly creates a webGL program
  1934. * @param pipelineContext defines the pipeline context to attach to
  1935. * @param vertexCode defines the vertex shader code to use
  1936. * @param fragmentCode defines the fragment shader code to use
  1937. * @param context defines the webGL context to use (if not set, the current one will be used)
  1938. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  1939. * @returns the new webGL program
  1940. */
  1941. public createRawShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1942. context = context || this._gl;
  1943. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  1944. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  1945. return this._createShaderProgram(pipelineContext as WebGLPipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
  1946. }
  1947. /**
  1948. * Creates a webGL program
  1949. * @param pipelineContext defines the pipeline context to attach to
  1950. * @param vertexCode defines the vertex shader code to use
  1951. * @param fragmentCode defines the fragment shader code to use
  1952. * @param defines defines the string containing the defines to use to compile the shaders
  1953. * @param context defines the webGL context to use (if not set, the current one will be used)
  1954. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  1955. * @returns the new webGL program
  1956. */
  1957. public createShaderProgram(pipelineContext: IPipelineContext, vertexCode: string, fragmentCode: string, defines: Nullable<string>, context?: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1958. context = context || this._gl;
  1959. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  1960. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  1961. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  1962. return this._createShaderProgram(pipelineContext as WebGLPipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
  1963. }
  1964. /**
  1965. * Creates a new pipeline context
  1966. * @param shaderProcessingContext defines the shader processing context used during the processing if available
  1967. * @returns the new pipeline
  1968. */
  1969. public createPipelineContext(shaderProcessingContext: Nullable<ShaderProcessingContext>): IPipelineContext {
  1970. var pipelineContext = new WebGLPipelineContext();
  1971. pipelineContext.engine = this;
  1972. if (this._caps.parallelShaderCompile) {
  1973. pipelineContext.isParallelCompiled = true;
  1974. }
  1975. return pipelineContext;
  1976. }
  1977. protected _createShaderProgram(pipelineContext: WebGLPipelineContext, vertexShader: WebGLShader, fragmentShader: WebGLShader, context: WebGLRenderingContext, transformFeedbackVaryings: Nullable<string[]> = null): WebGLProgram {
  1978. var shaderProgram = context.createProgram();
  1979. pipelineContext.program = shaderProgram;
  1980. if (!shaderProgram) {
  1981. throw new Error("Unable to create program");
  1982. }
  1983. context.attachShader(shaderProgram, vertexShader);
  1984. context.attachShader(shaderProgram, fragmentShader);
  1985. context.linkProgram(shaderProgram);
  1986. pipelineContext.context = context;
  1987. pipelineContext.vertexShader = vertexShader;
  1988. pipelineContext.fragmentShader = fragmentShader;
  1989. if (!pipelineContext.isParallelCompiled) {
  1990. this._finalizePipelineContext(pipelineContext);
  1991. }
  1992. return shaderProgram;
  1993. }
  1994. protected _finalizePipelineContext(pipelineContext: WebGLPipelineContext) {
  1995. const context = pipelineContext.context!;
  1996. const vertexShader = pipelineContext.vertexShader!;
  1997. const fragmentShader = pipelineContext.fragmentShader!;
  1998. const program = pipelineContext.program!;
  1999. var linked = context.getProgramParameter(program, context.LINK_STATUS);
  2000. if (!linked) { // Get more info
  2001. // Vertex
  2002. if (!this._gl.getShaderParameter(vertexShader, this._gl.COMPILE_STATUS)) {
  2003. const log = this._gl.getShaderInfoLog(vertexShader);
  2004. if (log) {
  2005. pipelineContext.vertexCompilationError = log;
  2006. throw new Error("VERTEX SHADER " + log);
  2007. }
  2008. }
  2009. // Fragment
  2010. if (!this._gl.getShaderParameter(fragmentShader, this._gl.COMPILE_STATUS)) {
  2011. const log = this._gl.getShaderInfoLog(fragmentShader);
  2012. if (log) {
  2013. pipelineContext.fragmentCompilationError = log;
  2014. throw new Error("FRAGMENT SHADER " + log);
  2015. }
  2016. }
  2017. var error = context.getProgramInfoLog(program);
  2018. if (error) {
  2019. pipelineContext.programLinkError = error;
  2020. throw new Error(error);
  2021. }
  2022. }
  2023. if (this.validateShaderPrograms) {
  2024. context.validateProgram(program);
  2025. var validated = context.getProgramParameter(program, context.VALIDATE_STATUS);
  2026. if (!validated) {
  2027. var error = context.getProgramInfoLog(program);
  2028. if (error) {
  2029. pipelineContext.programValidationError = error;
  2030. throw new Error(error);
  2031. }
  2032. }
  2033. }
  2034. context.deleteShader(vertexShader);
  2035. context.deleteShader(fragmentShader);
  2036. pipelineContext.vertexShader = undefined;
  2037. pipelineContext.fragmentShader = undefined;
  2038. if (pipelineContext.onCompiled) {
  2039. pipelineContext.onCompiled();
  2040. pipelineContext.onCompiled = undefined;
  2041. }
  2042. }
  2043. /** @hidden */
  2044. public _preparePipelineContext(pipelineContext: IPipelineContext, vertexSourceCode: string, fragmentSourceCode: string, createAsRaw: boolean, rawVertexSourceCode: string, rawFragmentSourceCode: string,
  2045. rebuildRebind: any,
  2046. defines: Nullable<string>,
  2047. transformFeedbackVaryings: Nullable<string[]>,
  2048. key: string) {
  2049. let webGLRenderingState = pipelineContext as WebGLPipelineContext;
  2050. if (createAsRaw) {
  2051. webGLRenderingState.program = this.createRawShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings);
  2052. }
  2053. else {
  2054. webGLRenderingState.program = this.createShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings);
  2055. }
  2056. webGLRenderingState.program.__SPECTOR_rebuildProgram = rebuildRebind;
  2057. }
  2058. /** @hidden */
  2059. public _isRenderingStateCompiled(pipelineContext: IPipelineContext): boolean {
  2060. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  2061. if (this._gl.getProgramParameter(webGLPipelineContext.program!, this._caps.parallelShaderCompile!.COMPLETION_STATUS_KHR)) {
  2062. this._finalizePipelineContext(webGLPipelineContext);
  2063. return true;
  2064. }
  2065. return false;
  2066. }
  2067. /** @hidden */
  2068. public _executeWhenRenderingStateIsCompiled(pipelineContext: IPipelineContext, action: () => void) {
  2069. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  2070. if (!webGLPipelineContext.isParallelCompiled) {
  2071. action();
  2072. return;
  2073. }
  2074. let oldHandler = webGLPipelineContext.onCompiled;
  2075. if (oldHandler) {
  2076. webGLPipelineContext.onCompiled = () => {
  2077. oldHandler!();
  2078. action();
  2079. };
  2080. } else {
  2081. webGLPipelineContext.onCompiled = action;
  2082. }
  2083. }
  2084. /**
  2085. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  2086. * @param pipelineContext defines the pipeline context to use
  2087. * @param uniformsNames defines the list of uniform names
  2088. * @returns an array of webGL uniform locations
  2089. */
  2090. public getUniforms(pipelineContext: IPipelineContext, uniformsNames: string[]): Nullable<WebGLUniformLocation>[] {
  2091. var results = new Array<Nullable<WebGLUniformLocation>>();
  2092. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  2093. for (var index = 0; index < uniformsNames.length; index++) {
  2094. results.push(this._gl.getUniformLocation(webGLPipelineContext.program!, uniformsNames[index]));
  2095. }
  2096. return results;
  2097. }
  2098. /**
  2099. * Gets the list of active attributes for a given webGL program
  2100. * @param pipelineContext defines the pipeline context to use
  2101. * @param attributesNames defines the list of attribute names to get
  2102. * @returns an array of indices indicating the offset of each attribute
  2103. */
  2104. public getAttributes(pipelineContext: IPipelineContext, attributesNames: string[]): number[] {
  2105. var results = [];
  2106. let webGLPipelineContext = pipelineContext as WebGLPipelineContext;
  2107. for (var index = 0; index < attributesNames.length; index++) {
  2108. try {
  2109. results.push(this._gl.getAttribLocation(webGLPipelineContext.program!, attributesNames[index]));
  2110. } catch (e) {
  2111. results.push(-1);
  2112. }
  2113. }
  2114. return results;
  2115. }
  2116. /**
  2117. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  2118. * @param effect defines the effect to activate
  2119. */
  2120. public enableEffect(effect: Nullable<Effect>): void {
  2121. if (!effect || effect === this._currentEffect) {
  2122. return;
  2123. }
  2124. // Use program
  2125. this.bindSamplers(effect);
  2126. this._currentEffect = effect;
  2127. if (effect.onBind) {
  2128. effect.onBind(effect);
  2129. }
  2130. if (effect._onBindObservable) {
  2131. effect._onBindObservable.notifyObservers(effect);
  2132. }
  2133. }
  2134. /**
  2135. * Set the value of an uniform to a number (int)
  2136. * @param uniform defines the webGL uniform location where to store the value
  2137. * @param value defines the int number to store
  2138. * @returns true if the value was set
  2139. */
  2140. public setInt(uniform: Nullable<WebGLUniformLocation>, value: number): boolean {
  2141. if (!uniform) {
  2142. return false;
  2143. }
  2144. this._gl.uniform1i(uniform, value);
  2145. return true;
  2146. }
  2147. /**
  2148. * Set the value of an uniform to a int2
  2149. * @param uniform defines the webGL uniform location where to store the value
  2150. * @param x defines the 1st component of the value
  2151. * @param y defines the 2nd component of the value
  2152. * @returns true if the value was set
  2153. */
  2154. public setInt2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): boolean {
  2155. if (!uniform) {
  2156. return false;
  2157. }
  2158. this._gl.uniform2i(uniform, x, y);
  2159. return true;
  2160. }
  2161. /**
  2162. * Set the value of an uniform to a int3
  2163. * @param uniform defines the webGL uniform location where to store the value
  2164. * @param x defines the 1st component of the value
  2165. * @param y defines the 2nd component of the value
  2166. * @param z defines the 3rd component of the value
  2167. * @returns true if the value was set
  2168. */
  2169. public setInt3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): boolean {
  2170. if (!uniform) {
  2171. return false;
  2172. }
  2173. this._gl.uniform3i(uniform, x, y, z);
  2174. return true;
  2175. }
  2176. /**
  2177. * Set the value of an uniform to a int4
  2178. * @param uniform defines the webGL uniform location where to store the value
  2179. * @param x defines the 1st component of the value
  2180. * @param y defines the 2nd component of the value
  2181. * @param z defines the 3rd component of the value
  2182. * @param w defines the 4th component of the value
  2183. * @returns true if the value was set
  2184. */
  2185. public setInt4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): boolean {
  2186. if (!uniform) {
  2187. return false;
  2188. }
  2189. this._gl.uniform4i(uniform, x, y, z, w);
  2190. return true;
  2191. }
  2192. /**
  2193. * Set the value of an uniform to an array of int32
  2194. * @param uniform defines the webGL uniform location where to store the value
  2195. * @param array defines the array of int32 to store
  2196. * @returns true if the value was set
  2197. */
  2198. public setIntArray(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): boolean {
  2199. if (!uniform) {
  2200. return false;
  2201. }
  2202. this._gl.uniform1iv(uniform, array);
  2203. return true;
  2204. }
  2205. /**
  2206. * Set the value of an uniform to an array of int32 (stored as vec2)
  2207. * @param uniform defines the webGL uniform location where to store the value
  2208. * @param array defines the array of int32 to store
  2209. * @returns true if the value was set
  2210. */
  2211. public setIntArray2(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): boolean {
  2212. if (!uniform || array.length % 2 !== 0) {
  2213. return false;
  2214. }
  2215. this._gl.uniform2iv(uniform, array);
  2216. return true;
  2217. }
  2218. /**
  2219. * Set the value of an uniform to an array of int32 (stored as vec3)
  2220. * @param uniform defines the webGL uniform location where to store the value
  2221. * @param array defines the array of int32 to store
  2222. * @returns true if the value was set
  2223. */
  2224. public setIntArray3(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): boolean {
  2225. if (!uniform || array.length % 3 !== 0) {
  2226. return false;
  2227. }
  2228. this._gl.uniform3iv(uniform, array);
  2229. return true;
  2230. }
  2231. /**
  2232. * Set the value of an uniform to an array of int32 (stored as vec4)
  2233. * @param uniform defines the webGL uniform location where to store the value
  2234. * @param array defines the array of int32 to store
  2235. * @returns true if the value was set
  2236. */
  2237. public setIntArray4(uniform: Nullable<WebGLUniformLocation>, array: Int32Array): boolean {
  2238. if (!uniform || array.length % 4 !== 0) {
  2239. return false;
  2240. }
  2241. this._gl.uniform4iv(uniform, array);
  2242. return true;
  2243. }
  2244. /**
  2245. * Set the value of an uniform to an array of number
  2246. * @param uniform defines the webGL uniform location where to store the value
  2247. * @param array defines the array of number to store
  2248. * @returns true if the value was set
  2249. */
  2250. public setArray(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): boolean {
  2251. if (!uniform) {
  2252. return false;
  2253. }
  2254. this._gl.uniform1fv(uniform, array);
  2255. return true;
  2256. }
  2257. /**
  2258. * Set the value of an uniform to an array of number (stored as vec2)
  2259. * @param uniform defines the webGL uniform location where to store the value
  2260. * @param array defines the array of number to store
  2261. * @returns true if the value was set
  2262. */
  2263. public setArray2(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): boolean {
  2264. if (!uniform || array.length % 2 !== 0) {
  2265. return false;
  2266. }
  2267. this._gl.uniform2fv(uniform, <any>array);
  2268. return true;
  2269. }
  2270. /**
  2271. * Set the value of an uniform to an array of number (stored as vec3)
  2272. * @param uniform defines the webGL uniform location where to store the value
  2273. * @param array defines the array of number to store
  2274. * @returns true if the value was set
  2275. */
  2276. public setArray3(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): boolean {
  2277. if (!uniform || array.length % 3 !== 0) {
  2278. return false;
  2279. }
  2280. this._gl.uniform3fv(uniform, <any>array);
  2281. return true;
  2282. }
  2283. /**
  2284. * Set the value of an uniform to an array of number (stored as vec4)
  2285. * @param uniform defines the webGL uniform location where to store the value
  2286. * @param array defines the array of number to store
  2287. * @returns true if the value was set
  2288. */
  2289. public setArray4(uniform: Nullable<WebGLUniformLocation>, array: number[] | Float32Array): boolean {
  2290. if (!uniform || array.length % 4 !== 0) {
  2291. return false;
  2292. }
  2293. this._gl.uniform4fv(uniform, <any>array);
  2294. return true;
  2295. }
  2296. /**
  2297. * Set the value of an uniform to an array of float32 (stored as matrices)
  2298. * @param uniform defines the webGL uniform location where to store the value
  2299. * @param matrices defines the array of float32 to store
  2300. * @returns true if the value was set
  2301. */
  2302. public setMatrices(uniform: Nullable<WebGLUniformLocation>, matrices: Float32Array): boolean {
  2303. if (!uniform) {
  2304. return false;
  2305. }
  2306. this._gl.uniformMatrix4fv(uniform, false, matrices);
  2307. return true;
  2308. }
  2309. /**
  2310. * Set the value of an uniform to a matrix (3x3)
  2311. * @param uniform defines the webGL uniform location where to store the value
  2312. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  2313. * @returns true if the value was set
  2314. */
  2315. public setMatrix3x3(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): boolean {
  2316. if (!uniform) {
  2317. return false;
  2318. }
  2319. this._gl.uniformMatrix3fv(uniform, false, matrix);
  2320. return true;
  2321. }
  2322. /**
  2323. * Set the value of an uniform to a matrix (2x2)
  2324. * @param uniform defines the webGL uniform location where to store the value
  2325. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  2326. * @returns true if the value was set
  2327. */
  2328. public setMatrix2x2(uniform: Nullable<WebGLUniformLocation>, matrix: Float32Array): boolean {
  2329. if (!uniform) {
  2330. return false;
  2331. }
  2332. this._gl.uniformMatrix2fv(uniform, false, matrix);
  2333. return true;
  2334. }
  2335. /**
  2336. * Set the value of an uniform to a number (float)
  2337. * @param uniform defines the webGL uniform location where to store the value
  2338. * @param value defines the float number to store
  2339. * @returns true if the value was transfered
  2340. */
  2341. public setFloat(uniform: Nullable<WebGLUniformLocation>, value: number): boolean {
  2342. if (!uniform) {
  2343. return false;
  2344. }
  2345. this._gl.uniform1f(uniform, value);
  2346. return true;
  2347. }
  2348. /**
  2349. * Set the value of an uniform to a vec2
  2350. * @param uniform defines the webGL uniform location where to store the value
  2351. * @param x defines the 1st component of the value
  2352. * @param y defines the 2nd component of the value
  2353. * @returns true if the value was set
  2354. */
  2355. public setFloat2(uniform: Nullable<WebGLUniformLocation>, x: number, y: number): boolean {
  2356. if (!uniform) {
  2357. return false;
  2358. }
  2359. this._gl.uniform2f(uniform, x, y);
  2360. return true;
  2361. }
  2362. /**
  2363. * Set the value of an uniform to a vec3
  2364. * @param uniform defines the webGL uniform location where to store the value
  2365. * @param x defines the 1st component of the value
  2366. * @param y defines the 2nd component of the value
  2367. * @param z defines the 3rd component of the value
  2368. * @returns true if the value was set
  2369. */
  2370. public setFloat3(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number): boolean {
  2371. if (!uniform) {
  2372. return false;
  2373. }
  2374. this._gl.uniform3f(uniform, x, y, z);
  2375. return true;
  2376. }
  2377. /**
  2378. * Set the value of an uniform to a vec4
  2379. * @param uniform defines the webGL uniform location where to store the value
  2380. * @param x defines the 1st component of the value
  2381. * @param y defines the 2nd component of the value
  2382. * @param z defines the 3rd component of the value
  2383. * @param w defines the 4th component of the value
  2384. * @returns true if the value was set
  2385. */
  2386. public setFloat4(uniform: Nullable<WebGLUniformLocation>, x: number, y: number, z: number, w: number): boolean {
  2387. if (!uniform) {
  2388. return false;
  2389. }
  2390. this._gl.uniform4f(uniform, x, y, z, w);
  2391. return true;
  2392. }
  2393. // States
  2394. /**
  2395. * Apply all cached states (depth, culling, stencil and alpha)
  2396. */
  2397. public applyStates() {
  2398. this._depthCullingState.apply(this._gl);
  2399. this._stencilState.apply(this._gl);
  2400. this._alphaState.apply(this._gl);
  2401. if (this._colorWriteChanged) {
  2402. this._colorWriteChanged = false;
  2403. const enable = this._colorWrite;
  2404. this._gl.colorMask(enable, enable, enable, enable);
  2405. }
  2406. }
  2407. /**
  2408. * Enable or disable color writing
  2409. * @param enable defines the state to set
  2410. */
  2411. public setColorWrite(enable: boolean): void {
  2412. if (enable !== this._colorWrite) {
  2413. this._colorWriteChanged = true;
  2414. this._colorWrite = enable;
  2415. }
  2416. }
  2417. /**
  2418. * Gets a boolean indicating if color writing is enabled
  2419. * @returns the current color writing state
  2420. */
  2421. public getColorWrite(): boolean {
  2422. return this._colorWrite;
  2423. }
  2424. /**
  2425. * Gets the depth culling state manager
  2426. */
  2427. public get depthCullingState(): DepthCullingState {
  2428. return this._depthCullingState;
  2429. }
  2430. /**
  2431. * Gets the alpha state manager
  2432. */
  2433. public get alphaState(): AlphaState {
  2434. return this._alphaState;
  2435. }
  2436. /**
  2437. * Gets the stencil state manager
  2438. */
  2439. public get stencilState(): StencilState {
  2440. return this._stencilState;
  2441. }
  2442. // Textures
  2443. /**
  2444. * Clears the list of texture accessible through engine.
  2445. * This can help preventing texture load conflict due to name collision.
  2446. */
  2447. public clearInternalTexturesCache() {
  2448. this._internalTexturesCache = [];
  2449. }
  2450. /**
  2451. * Force the entire cache to be cleared
  2452. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  2453. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  2454. */
  2455. public wipeCaches(bruteForce?: boolean): void {
  2456. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  2457. return;
  2458. }
  2459. this._currentEffect = null;
  2460. this._viewportCached.x = 0;
  2461. this._viewportCached.y = 0;
  2462. this._viewportCached.z = 0;
  2463. this._viewportCached.w = 0;
  2464. // Done before in case we clean the attributes
  2465. this._unbindVertexArrayObject();
  2466. if (bruteForce) {
  2467. this._currentProgram = null;
  2468. this.resetTextureCache();
  2469. this._stencilState.reset();
  2470. this._depthCullingState.reset();
  2471. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  2472. this._alphaState.reset();
  2473. this._alphaMode = Constants.ALPHA_ADD;
  2474. this._alphaEquation = Constants.ALPHA_DISABLE;
  2475. this._colorWrite = true;
  2476. this._colorWriteChanged = true;
  2477. this._unpackFlipYCached = null;
  2478. this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
  2479. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  2480. this._mustWipeVertexAttributes = true;
  2481. this.unbindAllAttributes();
  2482. }
  2483. this._resetVertexBufferBinding();
  2484. this._cachedIndexBuffer = null;
  2485. this._cachedEffectForVertexBuffers = null;
  2486. this.bindIndexBuffer(null);
  2487. }
  2488. /** @hidden */
  2489. public _getSamplingParameters(samplingMode: number, generateMipMaps: boolean): { min: number; mag: number } {
  2490. var gl = this._gl;
  2491. var magFilter = gl.NEAREST;
  2492. var minFilter = gl.NEAREST;
  2493. switch (samplingMode) {
  2494. case Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST:
  2495. magFilter = gl.LINEAR;
  2496. if (generateMipMaps) {
  2497. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2498. } else {
  2499. minFilter = gl.LINEAR;
  2500. }
  2501. break;
  2502. case Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR:
  2503. magFilter = gl.LINEAR;
  2504. if (generateMipMaps) {
  2505. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2506. } else {
  2507. minFilter = gl.LINEAR;
  2508. }
  2509. break;
  2510. case Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR:
  2511. magFilter = gl.NEAREST;
  2512. if (generateMipMaps) {
  2513. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2514. } else {
  2515. minFilter = gl.NEAREST;
  2516. }
  2517. break;
  2518. case Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  2519. magFilter = gl.NEAREST;
  2520. if (generateMipMaps) {
  2521. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  2522. } else {
  2523. minFilter = gl.NEAREST;
  2524. }
  2525. break;
  2526. case Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  2527. magFilter = gl.NEAREST;
  2528. if (generateMipMaps) {
  2529. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2530. } else {
  2531. minFilter = gl.LINEAR;
  2532. }
  2533. break;
  2534. case Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  2535. magFilter = gl.NEAREST;
  2536. if (generateMipMaps) {
  2537. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2538. } else {
  2539. minFilter = gl.LINEAR;
  2540. }
  2541. break;
  2542. case Constants.TEXTURE_NEAREST_LINEAR:
  2543. magFilter = gl.NEAREST;
  2544. minFilter = gl.LINEAR;
  2545. break;
  2546. case Constants.TEXTURE_NEAREST_NEAREST:
  2547. magFilter = gl.NEAREST;
  2548. minFilter = gl.NEAREST;
  2549. break;
  2550. case Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  2551. magFilter = gl.LINEAR;
  2552. if (generateMipMaps) {
  2553. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  2554. } else {
  2555. minFilter = gl.NEAREST;
  2556. }
  2557. break;
  2558. case Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  2559. magFilter = gl.LINEAR;
  2560. if (generateMipMaps) {
  2561. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2562. } else {
  2563. minFilter = gl.NEAREST;
  2564. }
  2565. break;
  2566. case Constants.TEXTURE_LINEAR_LINEAR:
  2567. magFilter = gl.LINEAR;
  2568. minFilter = gl.LINEAR;
  2569. break;
  2570. case Constants.TEXTURE_LINEAR_NEAREST:
  2571. magFilter = gl.LINEAR;
  2572. minFilter = gl.NEAREST;
  2573. break;
  2574. }
  2575. return {
  2576. min: minFilter,
  2577. mag: magFilter
  2578. };
  2579. }
  2580. /** @hidden */
  2581. protected _createTexture(): WebGLTexture {
  2582. let texture = this._gl.createTexture();
  2583. if (!texture) {
  2584. throw new Error("Unable to create texture");
  2585. }
  2586. return texture;
  2587. }
  2588. /** @hidden */
  2589. public _createHardwareTexture(): HardwareTextureWrapper {
  2590. return new WebGLHardwareTexture(this._createTexture(), this._gl);
  2591. }
  2592. protected _createTextureBase(url: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<ISceneLike>, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  2593. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  2594. prepareTexture: (texture: InternalTexture, extension: string, scene: Nullable<ISceneLike>, img: HTMLImageElement | ImageBitmap | { width: number, height: number }, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  2595. processFunction: (width: number, height: number, img: HTMLImageElement | ImageBitmap | { width: number, height: number }, extension: string, texture: InternalTexture, continuationCallback: () => void) => boolean, samplingMode: number) => void,
  2596. prepareTextureProcessFunction: (width: number, height: number, img: HTMLImageElement | ImageBitmap | { width: number, height: number }, extension: string, texture: InternalTexture, continuationCallback: () => void) => boolean,
  2597. buffer: Nullable<string | ArrayBuffer | ArrayBufferView | HTMLImageElement | Blob | ImageBitmap> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  2598. forcedExtension: Nullable<string> = null, mimeType?: string, loaderOptions?: any): InternalTexture {
  2599. url = url || "";
  2600. const fromData = url.substr(0, 5) === "data:";
  2601. const fromBlob = url.substr(0, 5) === "blob:";
  2602. const isBase64 = fromData && url.indexOf(";base64,") !== -1;
  2603. let texture = fallback ? fallback : new InternalTexture(this, InternalTextureSource.Url);
  2604. const originalUrl = url;
  2605. if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {
  2606. url = this._transformTextureUrl(url);
  2607. }
  2608. if (originalUrl !== url) {
  2609. texture._originalUrl = originalUrl;
  2610. }
  2611. // establish the file extension, if possible
  2612. const lastDot = url.lastIndexOf('.');
  2613. let extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  2614. let loader: Nullable<IInternalTextureLoader> = null;
  2615. // Remove query string
  2616. let queryStringIndex = extension.indexOf("?");
  2617. if (queryStringIndex > -1) {
  2618. extension = extension.split("?")[0];
  2619. }
  2620. for (const availableLoader of ThinEngine._TextureLoaders) {
  2621. if (availableLoader.canLoad(extension, mimeType)) {
  2622. loader = availableLoader;
  2623. break;
  2624. }
  2625. }
  2626. if (scene) {
  2627. scene._addPendingData(texture);
  2628. }
  2629. texture.url = url;
  2630. texture.generateMipMaps = !noMipmap;
  2631. texture.samplingMode = samplingMode;
  2632. texture.invertY = invertY;
  2633. if (!this._doNotHandleContextLost) {
  2634. // Keep a link to the buffer only if we plan to handle context lost
  2635. texture._buffer = buffer;
  2636. }
  2637. let onLoadObserver: Nullable<Observer<InternalTexture>> = null;
  2638. if (onLoad && !fallback) {
  2639. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  2640. }
  2641. if (!fallback) { this._internalTexturesCache.push(texture); }
  2642. const onInternalError = (message?: string, exception?: any) => {
  2643. if (scene) {
  2644. scene._removePendingData(texture);
  2645. }
  2646. if (url === originalUrl) {
  2647. if (onLoadObserver) {
  2648. texture.onLoadedObservable.remove(onLoadObserver);
  2649. }
  2650. if (EngineStore.UseFallbackTexture) {
  2651. this._createTextureBase(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, prepareTexture, prepareTextureProcessFunction, buffer, texture);
  2652. }
  2653. if (onError) {
  2654. onError((message || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""), exception);
  2655. }
  2656. }
  2657. else {
  2658. // fall back to the original url if the transformed url fails to load
  2659. Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`);
  2660. this._createTextureBase(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, prepareTexture, prepareTextureProcessFunction, buffer, texture, format, forcedExtension, mimeType, loaderOptions);
  2661. }
  2662. };
  2663. // processing for non-image formats
  2664. if (loader) {
  2665. const callback = (data: ArrayBufferView) => {
  2666. loader!.loadData(data, texture, (width: number, height: number, loadMipmap: boolean, isCompressed: boolean, done: () => void, loadFailed) => {
  2667. if (loadFailed) {
  2668. onInternalError("TextureLoader failed to load data");
  2669. } else {
  2670. prepareTexture(texture, extension, scene, { width, height }, texture.invertY, !loadMipmap, isCompressed, () => {
  2671. done();
  2672. return false;
  2673. }, samplingMode);
  2674. }
  2675. }, loaderOptions);
  2676. };
  2677. if (!buffer) {
  2678. this._loadFile(url, (data) => callback(new Uint8Array(data as ArrayBuffer)), undefined, scene ? scene.offlineProvider : undefined, true, (request?: IWebRequest, exception?: any) => {
  2679. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  2680. });
  2681. } else {
  2682. if (buffer instanceof ArrayBuffer) {
  2683. callback(new Uint8Array(buffer));
  2684. }
  2685. else if (ArrayBuffer.isView(buffer)) {
  2686. callback(buffer);
  2687. }
  2688. else {
  2689. if (onError) {
  2690. onError("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null);
  2691. }
  2692. }
  2693. }
  2694. } else {
  2695. const onload = (img: HTMLImageElement | ImageBitmap) => {
  2696. if (fromBlob && !this._doNotHandleContextLost) {
  2697. // We need to store the image if we need to rebuild the texture
  2698. // in case of a webgl context lost
  2699. texture._buffer = img;
  2700. }
  2701. prepareTexture(texture, extension, scene, img, texture.invertY, noMipmap, false, prepareTextureProcessFunction, samplingMode);
  2702. };
  2703. if (!fromData || isBase64) {
  2704. if (buffer && ((<HTMLImageElement>buffer).decoding || (<ImageBitmap>buffer).close)) {
  2705. onload(<HTMLImageElement>buffer);
  2706. } else {
  2707. ThinEngine._FileToolsLoadImage(url, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType);
  2708. }
  2709. }
  2710. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer) || buffer instanceof Blob) {
  2711. ThinEngine._FileToolsLoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType);
  2712. }
  2713. else if (buffer) {
  2714. onload(buffer);
  2715. }
  2716. }
  2717. return texture;
  2718. }
  2719. /**
  2720. * Usually called from Texture.ts.
  2721. * Passed information to create a WebGLTexture
  2722. * @param url defines a value which contains one of the following:
  2723. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  2724. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  2725. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  2726. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  2727. * @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)
  2728. * @param scene needed for loading to the correct scene
  2729. * @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
  2730. * @param onLoad optional callback to be called upon successful completion
  2731. * @param onError optional callback to be called upon failure
  2732. * @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
  2733. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  2734. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  2735. * @param forcedExtension defines the extension to use to pick the right loader
  2736. * @param mimeType defines an optional mime type
  2737. * @param loaderOptions options to be passed to the loader
  2738. * @returns a InternalTexture for assignment back into BABYLON.Texture
  2739. */
  2740. public createTexture(url: Nullable<string>, noMipmap: boolean, invertY: boolean, scene: Nullable<ISceneLike>, samplingMode: number = Constants.TEXTURE_TRILINEAR_SAMPLINGMODE,
  2741. onLoad: Nullable<() => void> = null, onError: Nullable<(message: string, exception: any) => void> = null,
  2742. buffer: Nullable<string | ArrayBuffer | ArrayBufferView | HTMLImageElement | Blob | ImageBitmap> = null, fallback: Nullable<InternalTexture> = null, format: Nullable<number> = null,
  2743. forcedExtension: Nullable<string> = null, mimeType?: string, loaderOptions?: any): InternalTexture {
  2744. return this._createTextureBase(
  2745. url, noMipmap, invertY, scene, samplingMode, onLoad, onError,
  2746. this._prepareWebGLTexture.bind(this),
  2747. (potWidth, potHeight, img, extension, texture, continuationCallback) => {
  2748. let gl = this._gl;
  2749. var isPot = (img.width === potWidth && img.height === potHeight);
  2750. let internalFormat = format ? this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  2751. if (isPot) {
  2752. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img as any);
  2753. return false;
  2754. }
  2755. let maxTextureSize = this._caps.maxTextureSize;
  2756. if (img.width > maxTextureSize || img.height > maxTextureSize || !this._supportsHardwareTextureRescaling) {
  2757. this._prepareWorkingCanvas();
  2758. if (!this._workingCanvas || !this._workingContext) {
  2759. return false;
  2760. }
  2761. this._workingCanvas.width = potWidth;
  2762. this._workingCanvas.height = potHeight;
  2763. this._workingContext.drawImage(img as any, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  2764. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, this._workingCanvas);
  2765. texture.width = potWidth;
  2766. texture.height = potHeight;
  2767. return false;
  2768. } else {
  2769. // Using shaders when possible to rescale because canvas.drawImage is lossy
  2770. let source = new InternalTexture(this, InternalTextureSource.Temp);
  2771. this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  2772. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img as any);
  2773. this._rescaleTexture(source, texture, scene, internalFormat, () => {
  2774. this._releaseTexture(source);
  2775. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  2776. continuationCallback();
  2777. });
  2778. }
  2779. return true;
  2780. },
  2781. buffer, fallback, format, forcedExtension, mimeType, loaderOptions
  2782. );
  2783. }
  2784. /**
  2785. * Loads an image as an HTMLImageElement.
  2786. * @param input url string, ArrayBuffer, or Blob to load
  2787. * @param onLoad callback called when the image successfully loads
  2788. * @param onError callback called when the image fails to load
  2789. * @param offlineProvider offline provider for caching
  2790. * @param mimeType optional mime type
  2791. * @returns the HTMLImageElement of the loaded image
  2792. * @hidden
  2793. */
  2794. 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> {
  2795. throw _DevTools.WarnImport("FileTools");
  2796. }
  2797. /**
  2798. * @hidden
  2799. */
  2800. public _rescaleTexture(source: InternalTexture, destination: InternalTexture, scene: Nullable<any>, internalFormat: number, onComplete: () => void): void {
  2801. }
  2802. /**
  2803. * Creates a raw texture
  2804. * @param data defines the data to store in the texture
  2805. * @param width defines the width of the texture
  2806. * @param height defines the height of the texture
  2807. * @param format defines the format of the data
  2808. * @param generateMipMaps defines if the engine should generate the mip levels
  2809. * @param invertY defines if data must be stored with Y axis inverted
  2810. * @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
  2811. * @param compression defines the compression used (null by default)
  2812. * @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
  2813. * @returns the raw texture inside an InternalTexture
  2814. */
  2815. 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 {
  2816. throw _DevTools.WarnImport("Engine.RawTexture");
  2817. }
  2818. /**
  2819. * Creates a new raw cube texture
  2820. * @param data defines the array of data to use to create each face
  2821. * @param size defines the size of the textures
  2822. * @param format defines the format of the data
  2823. * @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT)
  2824. * @param generateMipMaps defines if the engine should generate the mip levels
  2825. * @param invertY defines if data must be stored with Y axis inverted
  2826. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2827. * @param compression defines the compression used (null by default)
  2828. * @returns the cube texture as an InternalTexture
  2829. */
  2830. public createRawCubeTexture(data: Nullable<ArrayBufferView[]>, size: number, format: number, type: number,
  2831. generateMipMaps: boolean, invertY: boolean, samplingMode: number,
  2832. compression: Nullable<string> = null): InternalTexture {
  2833. throw _DevTools.WarnImport("Engine.RawTexture");
  2834. }
  2835. /**
  2836. * Creates a new raw 3D texture
  2837. * @param data defines the data used to create the texture
  2838. * @param width defines the width of the texture
  2839. * @param height defines the height of the texture
  2840. * @param depth defines the depth of the texture
  2841. * @param format defines the format of the texture
  2842. * @param generateMipMaps defines if the engine must generate mip levels
  2843. * @param invertY defines if data must be stored with Y axis inverted
  2844. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2845. * @param compression defines the compressed used (can be null)
  2846. * @param textureType defines the compressed used (can be null)
  2847. * @returns a new raw 3D texture (stored in an InternalTexture)
  2848. */
  2849. 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 {
  2850. throw _DevTools.WarnImport("Engine.RawTexture");
  2851. }
  2852. /**
  2853. * Creates a new raw 2D array texture
  2854. * @param data defines the data used to create the texture
  2855. * @param width defines the width of the texture
  2856. * @param height defines the height of the texture
  2857. * @param depth defines the number of layers of the texture
  2858. * @param format defines the format of the texture
  2859. * @param generateMipMaps defines if the engine must generate mip levels
  2860. * @param invertY defines if data must be stored with Y axis inverted
  2861. * @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
  2862. * @param compression defines the compressed used (can be null)
  2863. * @param textureType defines the compressed used (can be null)
  2864. * @returns a new raw 2D array texture (stored in an InternalTexture)
  2865. */
  2866. 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 {
  2867. throw _DevTools.WarnImport("Engine.RawTexture");
  2868. }
  2869. private _unpackFlipYCached: Nullable<boolean> = null;
  2870. /**
  2871. * In case you are sharing the context with other applications, it might
  2872. * be interested to not cache the unpack flip y state to ensure a consistent
  2873. * value would be set.
  2874. */
  2875. public enableUnpackFlipYCached = true;
  2876. /** @hidden */
  2877. public _unpackFlipY(value: boolean): void {
  2878. if (this._unpackFlipYCached !== value) {
  2879. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  2880. if (this.enableUnpackFlipYCached) {
  2881. this._unpackFlipYCached = value;
  2882. }
  2883. }
  2884. }
  2885. /** @hidden */
  2886. public _getUnpackAlignement(): number {
  2887. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  2888. }
  2889. private _getTextureTarget(texture: InternalTexture): number {
  2890. if (texture.isCube) {
  2891. return this._gl.TEXTURE_CUBE_MAP;
  2892. } else if (texture.is3D) {
  2893. return this._gl.TEXTURE_3D;
  2894. } else if (texture.is2DArray || texture.isMultiview) {
  2895. return this._gl.TEXTURE_2D_ARRAY;
  2896. }
  2897. return this._gl.TEXTURE_2D;
  2898. }
  2899. /**
  2900. * Update the sampling mode of a given texture
  2901. * @param samplingMode defines the required sampling mode
  2902. * @param texture defines the texture to update
  2903. * @param generateMipMaps defines whether to generate mipmaps for the texture
  2904. */
  2905. public updateTextureSamplingMode(samplingMode: number, texture: InternalTexture, generateMipMaps: boolean = false): void {
  2906. const target = this._getTextureTarget(texture);
  2907. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps || generateMipMaps);
  2908. this._setTextureParameterInteger(target, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  2909. this._setTextureParameterInteger(target, this._gl.TEXTURE_MIN_FILTER, filters.min);
  2910. if (generateMipMaps) {
  2911. texture.generateMipMaps = true;
  2912. this._gl.generateMipmap(target);
  2913. }
  2914. this._bindTextureDirectly(target, null);
  2915. texture.samplingMode = samplingMode;
  2916. }
  2917. /**
  2918. * Update the dimensions of a texture
  2919. * @param texture texture to update
  2920. * @param width new width of the texture
  2921. * @param height new height of the texture
  2922. * @param depth new depth of the texture
  2923. */
  2924. public updateTextureDimensions(texture: InternalTexture, width: number, height: number, depth: number = 1): void {
  2925. }
  2926. /**
  2927. * Update the sampling mode of a given texture
  2928. * @param texture defines the texture to update
  2929. * @param wrapU defines the texture wrap mode of the u coordinates
  2930. * @param wrapV defines the texture wrap mode of the v coordinates
  2931. * @param wrapR defines the texture wrap mode of the r coordinates
  2932. */
  2933. public updateTextureWrappingMode(texture: InternalTexture, wrapU: Nullable<number>, wrapV: Nullable<number> = null, wrapR: Nullable<number> = null): void {
  2934. const target = this._getTextureTarget(texture);
  2935. if (wrapU !== null) {
  2936. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(wrapU), texture);
  2937. texture._cachedWrapU = wrapU;
  2938. }
  2939. if (wrapV !== null) {
  2940. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(wrapV), texture);
  2941. texture._cachedWrapV = wrapV;
  2942. }
  2943. if ((texture.is2DArray || texture.is3D) && (wrapR !== null)) {
  2944. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(wrapR), texture);
  2945. texture._cachedWrapR = wrapR;
  2946. }
  2947. this._bindTextureDirectly(target, null);
  2948. }
  2949. /** @hidden */
  2950. public _setupDepthStencilTexture(internalTexture: InternalTexture, size: number | { width: number, height: number, layers?: number }, generateStencil: boolean, bilinearFiltering: boolean, comparisonFunction: number, samples = 1): void {
  2951. const width = (<{ width: number, height: number, layers?: number }>size).width || <number>size;
  2952. const height = (<{ width: number, height: number, layers?: number }>size).height || <number>size;
  2953. const layers = (<{ width: number, height: number, layers?: number }>size).layers || 0;
  2954. internalTexture.baseWidth = width;
  2955. internalTexture.baseHeight = height;
  2956. internalTexture.width = width;
  2957. internalTexture.height = height;
  2958. internalTexture.is2DArray = layers > 0;
  2959. internalTexture.depth = layers;
  2960. internalTexture.isReady = true;
  2961. internalTexture.samples = samples;
  2962. internalTexture.generateMipMaps = false;
  2963. internalTexture._generateDepthBuffer = true;
  2964. internalTexture._generateStencilBuffer = generateStencil;
  2965. internalTexture.samplingMode = bilinearFiltering ? Constants.TEXTURE_BILINEAR_SAMPLINGMODE : Constants.TEXTURE_NEAREST_SAMPLINGMODE;
  2966. internalTexture.type = Constants.TEXTURETYPE_UNSIGNED_INT;
  2967. internalTexture._comparisonFunction = comparisonFunction;
  2968. const gl = this._gl;
  2969. const target = this._getTextureTarget(internalTexture);
  2970. const samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  2971. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  2972. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  2973. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  2974. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  2975. if (comparisonFunction === 0) {
  2976. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Constants.LEQUAL);
  2977. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  2978. }
  2979. else {
  2980. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  2981. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  2982. }
  2983. }
  2984. /** @hidden */
  2985. public _uploadCompressedDataToTextureDirectly(texture: InternalTexture, internalFormat: number, width: number, height: number, data: ArrayBufferView, faceIndex: number = 0, lod: number = 0) {
  2986. var gl = this._gl;
  2987. var target = gl.TEXTURE_2D;
  2988. if (texture.isCube) {
  2989. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  2990. }
  2991. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, <DataView>data);
  2992. }
  2993. /** @hidden */
  2994. public _uploadDataToTextureDirectly(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0, babylonInternalFormat?: number, useTextureWidthAndHeight = false): void {
  2995. var gl = this._gl;
  2996. var textureType = this._getWebGLTextureType(texture.type);
  2997. var format = this._getInternalFormat(texture.format);
  2998. var internalFormat = babylonInternalFormat === undefined ? this._getRGBABufferInternalSizedFormat(texture.type, texture.format) : this._getInternalFormat(babylonInternalFormat);
  2999. this._unpackFlipY(texture.invertY);
  3000. var target = gl.TEXTURE_2D;
  3001. if (texture.isCube) {
  3002. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  3003. }
  3004. const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);
  3005. const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);
  3006. const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  3007. const height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  3008. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  3009. }
  3010. /**
  3011. * Update a portion of an internal texture
  3012. * @param texture defines the texture to update
  3013. * @param imageData defines the data to store into the texture
  3014. * @param xOffset defines the x coordinates of the update rectangle
  3015. * @param yOffset defines the y coordinates of the update rectangle
  3016. * @param width defines the width of the update rectangle
  3017. * @param height defines the height of the update rectangle
  3018. * @param faceIndex defines the face index if texture is a cube (0 by default)
  3019. * @param lod defines the lod level to update (0 by default)
  3020. */
  3021. public updateTextureData(texture: InternalTexture, imageData: ArrayBufferView, xOffset: number, yOffset: number, width: number, height: number, faceIndex: number = 0, lod: number = 0): void {
  3022. var gl = this._gl;
  3023. var textureType = this._getWebGLTextureType(texture.type);
  3024. var format = this._getInternalFormat(texture.format);
  3025. this._unpackFlipY(texture.invertY);
  3026. var target = gl.TEXTURE_2D;
  3027. if (texture.isCube) {
  3028. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  3029. }
  3030. gl.texSubImage2D(target, lod, xOffset, yOffset, width, height, format, textureType, imageData);
  3031. }
  3032. /** @hidden */
  3033. public _uploadArrayBufferViewToTexture(texture: InternalTexture, imageData: ArrayBufferView, faceIndex: number = 0, lod: number = 0): void {
  3034. var gl = this._gl;
  3035. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  3036. this._bindTextureDirectly(bindTarget, texture, true);
  3037. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  3038. this._bindTextureDirectly(bindTarget, null, true);
  3039. }
  3040. protected _prepareWebGLTextureContinuation(texture: InternalTexture, scene: Nullable<ISceneLike>, noMipmap: boolean, isCompressed: boolean, samplingMode: number): void {
  3041. var gl = this._gl;
  3042. if (!gl) {
  3043. return;
  3044. }
  3045. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  3046. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3047. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3048. if (!noMipmap && !isCompressed) {
  3049. gl.generateMipmap(gl.TEXTURE_2D);
  3050. }
  3051. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  3052. // this.resetTextureCache();
  3053. if (scene) {
  3054. scene._removePendingData(texture);
  3055. }
  3056. texture.onLoadedObservable.notifyObservers(texture);
  3057. texture.onLoadedObservable.clear();
  3058. }
  3059. private _prepareWebGLTexture(texture: InternalTexture, extension: string, scene: Nullable<ISceneLike>, img: HTMLImageElement | ImageBitmap | { width: number, height: number }, invertY: boolean, noMipmap: boolean, isCompressed: boolean,
  3060. 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 {
  3061. var maxTextureSize = this.getCaps().maxTextureSize;
  3062. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(img.width, maxTextureSize) : img.width);
  3063. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(img.height, maxTextureSize) : img.height);
  3064. var gl = this._gl;
  3065. if (!gl) {
  3066. return;
  3067. }
  3068. if (!texture._hardwareTexture) {
  3069. // this.resetTextureCache();
  3070. if (scene) {
  3071. scene._removePendingData(texture);
  3072. }
  3073. return;
  3074. }
  3075. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  3076. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  3077. texture.baseWidth = img.width;
  3078. texture.baseHeight = img.height;
  3079. texture.width = potWidth;
  3080. texture.height = potHeight;
  3081. texture.isReady = true;
  3082. if (processFunction(potWidth, potHeight, img, extension, texture, () => {
  3083. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3084. })) {
  3085. // Returning as texture needs extra async steps
  3086. return;
  3087. }
  3088. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  3089. }
  3090. /** @hidden */
  3091. public _setupFramebufferDepthAttachments(generateStencilBuffer: boolean, generateDepthBuffer: boolean, width: number, height: number, samples = 1): Nullable<WebGLRenderbuffer> {
  3092. var gl = this._gl;
  3093. // Create the depth/stencil buffer
  3094. if (generateStencilBuffer && generateDepthBuffer) {
  3095. return this._getDepthStencilBuffer(width, height, samples, gl.DEPTH_STENCIL, gl.DEPTH24_STENCIL8, gl.DEPTH_STENCIL_ATTACHMENT);
  3096. }
  3097. if (generateDepthBuffer) {
  3098. let depthFormat = gl.DEPTH_COMPONENT16;
  3099. if (this._webGLVersion > 1) {
  3100. depthFormat = gl.DEPTH_COMPONENT32F;
  3101. }
  3102. return this._getDepthStencilBuffer(width, height, samples, depthFormat, depthFormat, gl.DEPTH_ATTACHMENT);
  3103. }
  3104. if (generateStencilBuffer) {
  3105. return this._getDepthStencilBuffer(width, height, samples, gl.STENCIL_INDEX8, gl.STENCIL_INDEX8, gl.STENCIL_ATTACHMENT);
  3106. }
  3107. return null;
  3108. }
  3109. private _getDepthStencilBuffer = (width: number, height: number, samples: number, internalFormat: number, msInternalFormat: number, attachment: number) => {
  3110. var gl = this._gl;
  3111. const depthStencilBuffer = gl.createRenderbuffer();
  3112. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  3113. if (samples > 1 && gl.renderbufferStorageMultisample) {
  3114. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, msInternalFormat, width, height);
  3115. } else {
  3116. gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, width, height);
  3117. }
  3118. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, depthStencilBuffer);
  3119. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  3120. return depthStencilBuffer;
  3121. }
  3122. /** @hidden */
  3123. public _releaseFramebufferObjects(texture: InternalTexture): void {
  3124. var gl = this._gl;
  3125. if (texture._framebuffer) {
  3126. gl.deleteFramebuffer(texture._framebuffer);
  3127. texture._framebuffer = null;
  3128. }
  3129. if (texture._depthStencilBuffer) {
  3130. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  3131. texture._depthStencilBuffer = null;
  3132. }
  3133. if (texture._MSAAFramebuffer) {
  3134. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  3135. texture._MSAAFramebuffer = null;
  3136. }
  3137. if (texture._MSAARenderBuffer) {
  3138. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  3139. texture._MSAARenderBuffer = null;
  3140. }
  3141. }
  3142. /** @hidden */
  3143. public _releaseTexture(texture: InternalTexture): void {
  3144. this._releaseFramebufferObjects(texture);
  3145. this._deleteTexture(texture._hardwareTexture?.underlyingResource);
  3146. // Unbind channels
  3147. this.unbindAllTextures();
  3148. var index = this._internalTexturesCache.indexOf(texture);
  3149. if (index !== -1) {
  3150. this._internalTexturesCache.splice(index, 1);
  3151. }
  3152. // Integrated fixed lod samplers.
  3153. if (texture._lodTextureHigh) {
  3154. texture._lodTextureHigh.dispose();
  3155. }
  3156. if (texture._lodTextureMid) {
  3157. texture._lodTextureMid.dispose();
  3158. }
  3159. if (texture._lodTextureLow) {
  3160. texture._lodTextureLow.dispose();
  3161. }
  3162. // Integrated irradiance map.
  3163. if (texture._irradianceTexture) {
  3164. texture._irradianceTexture.dispose();
  3165. }
  3166. texture._depthStencilTexture?.dispose();
  3167. }
  3168. protected _deleteTexture(texture: Nullable<WebGLTexture>): void {
  3169. if (texture) {
  3170. this._gl.deleteTexture(texture);
  3171. }
  3172. }
  3173. protected _setProgram(program: WebGLProgram): void {
  3174. if (this._currentProgram !== program) {
  3175. this._gl.useProgram(program);
  3176. this._currentProgram = program;
  3177. }
  3178. }
  3179. protected _boundUniforms: { [key: number]: WebGLUniformLocation } = {};
  3180. /**
  3181. * Binds an effect to the webGL context
  3182. * @param effect defines the effect to bind
  3183. */
  3184. public bindSamplers(effect: Effect): void {
  3185. let webGLPipelineContext = effect.getPipelineContext() as WebGLPipelineContext;
  3186. this._setProgram(webGLPipelineContext.program!);
  3187. var samplers = effect.getSamplers();
  3188. for (var index = 0; index < samplers.length; index++) {
  3189. var uniform = effect.getUniform(samplers[index]);
  3190. if (uniform) {
  3191. this._boundUniforms[index] = uniform;
  3192. }
  3193. }
  3194. this._currentEffect = null;
  3195. }
  3196. private _activateCurrentTexture() {
  3197. if (this._currentTextureChannel !== this._activeChannel) {
  3198. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  3199. this._currentTextureChannel = this._activeChannel;
  3200. }
  3201. }
  3202. /** @hidden */
  3203. public _bindTextureDirectly(target: number, texture: Nullable<InternalTexture>, forTextureDataUpdate = false, force = false): boolean {
  3204. var wasPreviouslyBound = false;
  3205. let isTextureForRendering = texture && texture._associatedChannel > -1;
  3206. if (forTextureDataUpdate && isTextureForRendering) {
  3207. this._activeChannel = texture!._associatedChannel;
  3208. }
  3209. let currentTextureBound = this._boundTexturesCache[this._activeChannel];
  3210. if (currentTextureBound !== texture || force) {
  3211. this._activateCurrentTexture();
  3212. if (texture && texture.isMultiview) {
  3213. this._gl.bindTexture(target, texture ? texture._colorTextureArray : null);
  3214. } else {
  3215. this._gl.bindTexture(target, texture?._hardwareTexture?.underlyingResource ?? null);
  3216. }
  3217. this._boundTexturesCache[this._activeChannel] = texture;
  3218. if (texture) {
  3219. texture._associatedChannel = this._activeChannel;
  3220. }
  3221. } else if (forTextureDataUpdate) {
  3222. wasPreviouslyBound = true;
  3223. this._activateCurrentTexture();
  3224. }
  3225. if (isTextureForRendering && !forTextureDataUpdate) {
  3226. this._bindSamplerUniformToChannel(texture!._associatedChannel, this._activeChannel);
  3227. }
  3228. return wasPreviouslyBound;
  3229. }
  3230. /** @hidden */
  3231. public _bindTexture(channel: number, texture: Nullable<InternalTexture>, name: string): void {
  3232. if (channel === undefined) {
  3233. return;
  3234. }
  3235. if (texture) {
  3236. texture._associatedChannel = channel;
  3237. }
  3238. this._activeChannel = channel;
  3239. const target = texture ? this._getTextureTarget(texture) : this._gl.TEXTURE_2D;
  3240. this._bindTextureDirectly(target, texture);
  3241. }
  3242. /**
  3243. * Unbind all textures from the webGL context
  3244. */
  3245. public unbindAllTextures(): void {
  3246. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  3247. this._activeChannel = channel;
  3248. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3249. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3250. if (this.webGLVersion > 1) {
  3251. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3252. this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null);
  3253. }
  3254. }
  3255. }
  3256. /**
  3257. * Sets a texture to the according uniform.
  3258. * @param channel The texture channel
  3259. * @param uniform The uniform to set
  3260. * @param texture The texture to apply
  3261. * @param name The name of the uniform in the effect
  3262. */
  3263. public setTexture(channel: number, uniform: Nullable<WebGLUniformLocation>, texture: Nullable<ThinTexture>, name: string): void {
  3264. if (channel === undefined) {
  3265. return;
  3266. }
  3267. if (uniform) {
  3268. this._boundUniforms[channel] = uniform;
  3269. }
  3270. this._setTexture(channel, texture);
  3271. }
  3272. private _bindSamplerUniformToChannel(sourceSlot: number, destination: number) {
  3273. let uniform = this._boundUniforms[sourceSlot];
  3274. if (!uniform || uniform._currentState === destination) {
  3275. return;
  3276. }
  3277. this._gl.uniform1i(uniform, destination);
  3278. uniform._currentState = destination;
  3279. }
  3280. private _getTextureWrapMode(mode: number): number {
  3281. switch (mode) {
  3282. case Constants.TEXTURE_WRAP_ADDRESSMODE:
  3283. return this._gl.REPEAT;
  3284. case Constants.TEXTURE_CLAMP_ADDRESSMODE:
  3285. return this._gl.CLAMP_TO_EDGE;
  3286. case Constants.TEXTURE_MIRROR_ADDRESSMODE:
  3287. return this._gl.MIRRORED_REPEAT;
  3288. }
  3289. return this._gl.REPEAT;
  3290. }
  3291. protected _setTexture(channel: number, texture: Nullable<ThinTexture>, isPartOfTextureArray = false, depthStencilTexture = false, name = ""): boolean {
  3292. // Not ready?
  3293. if (!texture) {
  3294. if (this._boundTexturesCache[channel] != null) {
  3295. this._activeChannel = channel;
  3296. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  3297. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  3298. if (this.webGLVersion > 1) {
  3299. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  3300. this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null);
  3301. }
  3302. }
  3303. return false;
  3304. }
  3305. // Video
  3306. if ((<VideoTexture>texture).video) {
  3307. this._activeChannel = channel;
  3308. (<VideoTexture>texture).update();
  3309. } else if (texture.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  3310. texture.delayLoad();
  3311. return false;
  3312. }
  3313. let internalTexture: InternalTexture;
  3314. if (depthStencilTexture) {
  3315. internalTexture = (<RenderTargetTexture>texture).depthStencilTexture!;
  3316. }
  3317. else if (texture.isReady()) {
  3318. internalTexture = <InternalTexture>texture.getInternalTexture();
  3319. }
  3320. else if (texture.isCube) {
  3321. internalTexture = this.emptyCubeTexture;
  3322. }
  3323. else if (texture.is3D) {
  3324. internalTexture = this.emptyTexture3D;
  3325. }
  3326. else if (texture.is2DArray) {
  3327. internalTexture = this.emptyTexture2DArray;
  3328. }
  3329. else {
  3330. internalTexture = this.emptyTexture;
  3331. }
  3332. if (!isPartOfTextureArray && internalTexture) {
  3333. internalTexture._associatedChannel = channel;
  3334. }
  3335. let needToBind = true;
  3336. if (this._boundTexturesCache[channel] === internalTexture) {
  3337. if (!isPartOfTextureArray) {
  3338. this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel);
  3339. }
  3340. needToBind = false;
  3341. }
  3342. this._activeChannel = channel;
  3343. const target = this._getTextureTarget(internalTexture);
  3344. if (needToBind) {
  3345. this._bindTextureDirectly(target, internalTexture, isPartOfTextureArray);
  3346. }
  3347. if (internalTexture && !internalTexture.isMultiview) {
  3348. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  3349. if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  3350. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  3351. var textureWrapMode = (texture.coordinatesMode !== Constants.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Constants.TEXTURE_SKYBOX_MODE) ? Constants.TEXTURE_WRAP_ADDRESSMODE : Constants.TEXTURE_CLAMP_ADDRESSMODE;
  3352. texture.wrapU = textureWrapMode;
  3353. texture.wrapV = textureWrapMode;
  3354. }
  3355. if (internalTexture._cachedWrapU !== texture.wrapU) {
  3356. internalTexture._cachedWrapU = texture.wrapU;
  3357. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  3358. }
  3359. if (internalTexture._cachedWrapV !== texture.wrapV) {
  3360. internalTexture._cachedWrapV = texture.wrapV;
  3361. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  3362. }
  3363. if (internalTexture.is3D && internalTexture._cachedWrapR !== texture.wrapR) {
  3364. internalTexture._cachedWrapR = texture.wrapR;
  3365. this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  3366. }
  3367. this._setAnisotropicLevel(target, internalTexture, texture.anisotropicFilteringLevel);
  3368. }
  3369. return true;
  3370. }
  3371. /**
  3372. * Sets an array of texture to the webGL context
  3373. * @param channel defines the channel where the texture array must be set
  3374. * @param uniform defines the associated uniform location
  3375. * @param textures defines the array of textures to bind
  3376. * @param name name of the channel
  3377. */
  3378. public setTextureArray(channel: number, uniform: Nullable<WebGLUniformLocation>, textures: ThinTexture[], name: string): void {
  3379. if (channel === undefined || !uniform) {
  3380. return;
  3381. }
  3382. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  3383. this._textureUnits = new Int32Array(textures.length);
  3384. }
  3385. for (let i = 0; i < textures.length; i++) {
  3386. let texture = textures[i].getInternalTexture();
  3387. if (texture) {
  3388. this._textureUnits[i] = channel + i;
  3389. texture._associatedChannel = channel + i;
  3390. } else {
  3391. this._textureUnits[i] = -1;
  3392. }
  3393. }
  3394. this._gl.uniform1iv(uniform, this._textureUnits);
  3395. for (var index = 0; index < textures.length; index++) {
  3396. this._setTexture(this._textureUnits[index], textures[index], true);
  3397. }
  3398. }
  3399. /** @hidden */
  3400. public _setAnisotropicLevel(target: number, internalTexture: InternalTexture, anisotropicFilteringLevel: number) {
  3401. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  3402. if (internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  3403. && internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  3404. && internalTexture.samplingMode !== Constants.TEXTURE_LINEAR_LINEAR) {
  3405. anisotropicFilteringLevel = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  3406. }
  3407. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) {
  3408. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy), internalTexture);
  3409. internalTexture._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel;
  3410. }
  3411. }
  3412. private _setTextureParameterFloat(target: number, parameter: number, value: number, texture: InternalTexture): void {
  3413. this._bindTextureDirectly(target, texture, true, true);
  3414. this._gl.texParameterf(target, parameter, value);
  3415. }
  3416. private _setTextureParameterInteger(target: number, parameter: number, value: number, texture?: InternalTexture) {
  3417. if (texture) {
  3418. this._bindTextureDirectly(target, texture, true, true);
  3419. }
  3420. this._gl.texParameteri(target, parameter, value);
  3421. }
  3422. /**
  3423. * Unbind all vertex attributes from the webGL context
  3424. */
  3425. public unbindAllAttributes() {
  3426. if (this._mustWipeVertexAttributes) {
  3427. this._mustWipeVertexAttributes = false;
  3428. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  3429. this.disableAttributeByIndex(i);
  3430. }
  3431. return;
  3432. }
  3433. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  3434. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  3435. continue;
  3436. }
  3437. this.disableAttributeByIndex(i);
  3438. }
  3439. }
  3440. /**
  3441. * 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
  3442. */
  3443. public releaseEffects() {
  3444. for (var name in this._compiledEffects) {
  3445. let webGLPipelineContext = this._compiledEffects[name].getPipelineContext() as WebGLPipelineContext;
  3446. this._deletePipelineContext(webGLPipelineContext);
  3447. }
  3448. this._compiledEffects = {};
  3449. }
  3450. /**
  3451. * Dispose and release all associated resources
  3452. */
  3453. public dispose(): void {
  3454. this.stopRenderLoop();
  3455. // Clear observables
  3456. if (this.onBeforeTextureInitObservable) {
  3457. this.onBeforeTextureInitObservable.clear();
  3458. }
  3459. // Empty texture
  3460. if (this._emptyTexture) {
  3461. this._releaseTexture(this._emptyTexture);
  3462. this._emptyTexture = null;
  3463. }
  3464. if (this._emptyCubeTexture) {
  3465. this._releaseTexture(this._emptyCubeTexture);
  3466. this._emptyCubeTexture = null;
  3467. }
  3468. if (this._dummyFramebuffer) {
  3469. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  3470. }
  3471. // Release effects
  3472. this.releaseEffects();
  3473. // Unbind
  3474. this.unbindAllAttributes();
  3475. this._boundUniforms = [];
  3476. // Events
  3477. if (DomManagement.IsWindowObjectExist()) {
  3478. if (this._renderingCanvas) {
  3479. if (!this._doNotHandleContextLost) {
  3480. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  3481. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  3482. }
  3483. }
  3484. }
  3485. this._workingCanvas = null;
  3486. this._workingContext = null;
  3487. this._currentBufferPointers = [];
  3488. this._renderingCanvas = null;
  3489. this._currentProgram = null;
  3490. this._boundRenderFunction = null;
  3491. Effect.ResetCache();
  3492. // Abort active requests
  3493. for (let request of this._activeRequests) {
  3494. request.abort();
  3495. }
  3496. }
  3497. /**
  3498. * Attach a new callback raised when context lost event is fired
  3499. * @param callback defines the callback to call
  3500. */
  3501. public attachContextLostEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3502. if (this._renderingCanvas) {
  3503. this._renderingCanvas.addEventListener("webglcontextlost", <any>callback, false);
  3504. }
  3505. }
  3506. /**
  3507. * Attach a new callback raised when context restored event is fired
  3508. * @param callback defines the callback to call
  3509. */
  3510. public attachContextRestoredEvent(callback: ((event: WebGLContextEvent) => void)): void {
  3511. if (this._renderingCanvas) {
  3512. this._renderingCanvas.addEventListener("webglcontextrestored", <any>callback, false);
  3513. }
  3514. }
  3515. /**
  3516. * Get the current error code of the webGL context
  3517. * @returns the error code
  3518. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  3519. */
  3520. public getError(): number {
  3521. return this._gl.getError();
  3522. }
  3523. private _canRenderToFloatFramebuffer(): boolean {
  3524. if (this._webGLVersion > 1) {
  3525. return this._caps.colorBufferFloat;
  3526. }
  3527. return this._canRenderToFramebuffer(Constants.TEXTURETYPE_FLOAT);
  3528. }
  3529. private _canRenderToHalfFloatFramebuffer(): boolean {
  3530. if (this._webGLVersion > 1) {
  3531. return this._caps.colorBufferFloat;
  3532. }
  3533. return this._canRenderToFramebuffer(Constants.TEXTURETYPE_HALF_FLOAT);
  3534. }
  3535. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  3536. private _canRenderToFramebuffer(type: number): boolean {
  3537. let gl = this._gl;
  3538. //clear existing errors
  3539. while (gl.getError() !== gl.NO_ERROR) { }
  3540. let successful = true;
  3541. let texture = gl.createTexture();
  3542. gl.bindTexture(gl.TEXTURE_2D, texture);
  3543. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  3544. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  3545. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  3546. let fb = gl.createFramebuffer();
  3547. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  3548. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  3549. let status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  3550. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  3551. successful = successful && (gl.getError() === gl.NO_ERROR);
  3552. //try render by clearing frame buffer's color buffer
  3553. if (successful) {
  3554. gl.clear(gl.COLOR_BUFFER_BIT);
  3555. successful = successful && (gl.getError() === gl.NO_ERROR);
  3556. }
  3557. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  3558. if (successful) {
  3559. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  3560. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3561. let readFormat = gl.RGBA;
  3562. let readType = gl.UNSIGNED_BYTE;
  3563. let buffer = new Uint8Array(4);
  3564. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  3565. successful = successful && (gl.getError() === gl.NO_ERROR);
  3566. }
  3567. //clean up
  3568. gl.deleteTexture(texture);
  3569. gl.deleteFramebuffer(fb);
  3570. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  3571. //clear accumulated errors
  3572. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  3573. return successful;
  3574. }
  3575. /** @hidden */
  3576. public _getWebGLTextureType(type: number): number {
  3577. if (this._webGLVersion === 1) {
  3578. switch (type) {
  3579. case Constants.TEXTURETYPE_FLOAT:
  3580. return this._gl.FLOAT;
  3581. case Constants.TEXTURETYPE_HALF_FLOAT:
  3582. return this._gl.HALF_FLOAT_OES;
  3583. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3584. return this._gl.UNSIGNED_BYTE;
  3585. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3586. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  3587. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3588. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  3589. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3590. return this._gl.UNSIGNED_SHORT_5_6_5;
  3591. }
  3592. return this._gl.UNSIGNED_BYTE;
  3593. }
  3594. switch (type) {
  3595. case Constants.TEXTURETYPE_BYTE:
  3596. return this._gl.BYTE;
  3597. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3598. return this._gl.UNSIGNED_BYTE;
  3599. case Constants.TEXTURETYPE_SHORT:
  3600. return this._gl.SHORT;
  3601. case Constants.TEXTURETYPE_UNSIGNED_SHORT:
  3602. return this._gl.UNSIGNED_SHORT;
  3603. case Constants.TEXTURETYPE_INT:
  3604. return this._gl.INT;
  3605. case Constants.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  3606. return this._gl.UNSIGNED_INT;
  3607. case Constants.TEXTURETYPE_FLOAT:
  3608. return this._gl.FLOAT;
  3609. case Constants.TEXTURETYPE_HALF_FLOAT:
  3610. return this._gl.HALF_FLOAT;
  3611. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3612. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  3613. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3614. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  3615. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3616. return this._gl.UNSIGNED_SHORT_5_6_5;
  3617. case Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  3618. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  3619. case Constants.TEXTURETYPE_UNSIGNED_INT_24_8:
  3620. return this._gl.UNSIGNED_INT_24_8;
  3621. case Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  3622. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  3623. case Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  3624. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  3625. case Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  3626. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  3627. }
  3628. return this._gl.UNSIGNED_BYTE;
  3629. }
  3630. /** @hidden */
  3631. public _getInternalFormat(format: number): number {
  3632. var internalFormat = this._gl.RGBA;
  3633. switch (format) {
  3634. case Constants.TEXTUREFORMAT_ALPHA:
  3635. internalFormat = this._gl.ALPHA;
  3636. break;
  3637. case Constants.TEXTUREFORMAT_LUMINANCE:
  3638. internalFormat = this._gl.LUMINANCE;
  3639. break;
  3640. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3641. internalFormat = this._gl.LUMINANCE_ALPHA;
  3642. break;
  3643. case Constants.TEXTUREFORMAT_RED:
  3644. internalFormat = this._gl.RED;
  3645. break;
  3646. case Constants.TEXTUREFORMAT_RG:
  3647. internalFormat = this._gl.RG;
  3648. break;
  3649. case Constants.TEXTUREFORMAT_RGB:
  3650. internalFormat = this._gl.RGB;
  3651. break;
  3652. case Constants.TEXTUREFORMAT_RGBA:
  3653. internalFormat = this._gl.RGBA;
  3654. break;
  3655. }
  3656. if (this._webGLVersion > 1) {
  3657. switch (format) {
  3658. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3659. internalFormat = this._gl.RED_INTEGER;
  3660. break;
  3661. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3662. internalFormat = this._gl.RG_INTEGER;
  3663. break;
  3664. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3665. internalFormat = this._gl.RGB_INTEGER;
  3666. break;
  3667. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3668. internalFormat = this._gl.RGBA_INTEGER;
  3669. break;
  3670. }
  3671. }
  3672. return internalFormat;
  3673. }
  3674. /** @hidden */
  3675. public _getRGBABufferInternalSizedFormat(type: number, format?: number): number {
  3676. if (this._webGLVersion === 1) {
  3677. if (format !== undefined) {
  3678. switch (format) {
  3679. case Constants.TEXTUREFORMAT_ALPHA:
  3680. return this._gl.ALPHA;
  3681. case Constants.TEXTUREFORMAT_LUMINANCE:
  3682. return this._gl.LUMINANCE;
  3683. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3684. return this._gl.LUMINANCE_ALPHA;
  3685. case Constants.TEXTUREFORMAT_RGB:
  3686. return this._gl.RGB;
  3687. }
  3688. }
  3689. return this._gl.RGBA;
  3690. }
  3691. switch (type) {
  3692. case Constants.TEXTURETYPE_BYTE:
  3693. switch (format) {
  3694. case Constants.TEXTUREFORMAT_RED:
  3695. return this._gl.R8_SNORM;
  3696. case Constants.TEXTUREFORMAT_RG:
  3697. return this._gl.RG8_SNORM;
  3698. case Constants.TEXTUREFORMAT_RGB:
  3699. return this._gl.RGB8_SNORM;
  3700. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3701. return this._gl.R8I;
  3702. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3703. return this._gl.RG8I;
  3704. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3705. return this._gl.RGB8I;
  3706. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3707. return this._gl.RGBA8I;
  3708. default:
  3709. return this._gl.RGBA8_SNORM;
  3710. }
  3711. case Constants.TEXTURETYPE_UNSIGNED_BYTE:
  3712. switch (format) {
  3713. case Constants.TEXTUREFORMAT_RED:
  3714. return this._gl.R8;
  3715. case Constants.TEXTUREFORMAT_RG:
  3716. return this._gl.RG8;
  3717. case Constants.TEXTUREFORMAT_RGB:
  3718. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  3719. case Constants.TEXTUREFORMAT_RGBA:
  3720. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  3721. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3722. return this._gl.R8UI;
  3723. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3724. return this._gl.RG8UI;
  3725. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3726. return this._gl.RGB8UI;
  3727. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3728. return this._gl.RGBA8UI;
  3729. case Constants.TEXTUREFORMAT_ALPHA:
  3730. return this._gl.ALPHA;
  3731. case Constants.TEXTUREFORMAT_LUMINANCE:
  3732. return this._gl.LUMINANCE;
  3733. case Constants.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3734. return this._gl.LUMINANCE_ALPHA;
  3735. default:
  3736. return this._gl.RGBA8;
  3737. }
  3738. case Constants.TEXTURETYPE_SHORT:
  3739. switch (format) {
  3740. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3741. return this._gl.R16I;
  3742. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3743. return this._gl.RG16I;
  3744. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3745. return this._gl.RGB16I;
  3746. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3747. return this._gl.RGBA16I;
  3748. default:
  3749. return this._gl.RGBA16I;
  3750. }
  3751. case Constants.TEXTURETYPE_UNSIGNED_SHORT:
  3752. switch (format) {
  3753. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3754. return this._gl.R16UI;
  3755. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3756. return this._gl.RG16UI;
  3757. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3758. return this._gl.RGB16UI;
  3759. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3760. return this._gl.RGBA16UI;
  3761. default:
  3762. return this._gl.RGBA16UI;
  3763. }
  3764. case Constants.TEXTURETYPE_INT:
  3765. switch (format) {
  3766. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3767. return this._gl.R32I;
  3768. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3769. return this._gl.RG32I;
  3770. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3771. return this._gl.RGB32I;
  3772. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3773. return this._gl.RGBA32I;
  3774. default:
  3775. return this._gl.RGBA32I;
  3776. }
  3777. case Constants.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  3778. switch (format) {
  3779. case Constants.TEXTUREFORMAT_RED_INTEGER:
  3780. return this._gl.R32UI;
  3781. case Constants.TEXTUREFORMAT_RG_INTEGER:
  3782. return this._gl.RG32UI;
  3783. case Constants.TEXTUREFORMAT_RGB_INTEGER:
  3784. return this._gl.RGB32UI;
  3785. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3786. return this._gl.RGBA32UI;
  3787. default:
  3788. return this._gl.RGBA32UI;
  3789. }
  3790. case Constants.TEXTURETYPE_FLOAT:
  3791. switch (format) {
  3792. case Constants.TEXTUREFORMAT_RED:
  3793. return this._gl.R32F; // By default. Other possibility is R16F.
  3794. case Constants.TEXTUREFORMAT_RG:
  3795. return this._gl.RG32F; // By default. Other possibility is RG16F.
  3796. case Constants.TEXTUREFORMAT_RGB:
  3797. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  3798. case Constants.TEXTUREFORMAT_RGBA:
  3799. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  3800. default:
  3801. return this._gl.RGBA32F;
  3802. }
  3803. case Constants.TEXTURETYPE_HALF_FLOAT:
  3804. switch (format) {
  3805. case Constants.TEXTUREFORMAT_RED:
  3806. return this._gl.R16F;
  3807. case Constants.TEXTUREFORMAT_RG:
  3808. return this._gl.RG16F;
  3809. case Constants.TEXTUREFORMAT_RGB:
  3810. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  3811. case Constants.TEXTUREFORMAT_RGBA:
  3812. return this._gl.RGBA16F;
  3813. default:
  3814. return this._gl.RGBA16F;
  3815. }
  3816. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  3817. return this._gl.RGB565;
  3818. case Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  3819. return this._gl.R11F_G11F_B10F;
  3820. case Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  3821. return this._gl.RGB9_E5;
  3822. case Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  3823. return this._gl.RGBA4;
  3824. case Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  3825. return this._gl.RGB5_A1;
  3826. case Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  3827. switch (format) {
  3828. case Constants.TEXTUREFORMAT_RGBA:
  3829. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  3830. case Constants.TEXTUREFORMAT_RGBA_INTEGER:
  3831. return this._gl.RGB10_A2UI;
  3832. default:
  3833. return this._gl.RGB10_A2;
  3834. }
  3835. }
  3836. return this._gl.RGBA8;
  3837. }
  3838. /** @hidden */
  3839. public _getRGBAMultiSampleBufferFormat(type: number): number {
  3840. if (type === Constants.TEXTURETYPE_FLOAT) {
  3841. return this._gl.RGBA32F;
  3842. }
  3843. else if (type === Constants.TEXTURETYPE_HALF_FLOAT) {
  3844. return this._gl.RGBA16F;
  3845. }
  3846. return this._gl.RGBA8;
  3847. }
  3848. /** @hidden */
  3849. public _loadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void,
  3850. offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: IWebRequest, exception?: any) => void): IFileRequest {
  3851. let request = ThinEngine._FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  3852. this._activeRequests.push(request);
  3853. request.onCompleteObservable.add((request) => {
  3854. this._activeRequests.splice(this._activeRequests.indexOf(request), 1);
  3855. });
  3856. return request;
  3857. }
  3858. /**
  3859. * Loads a file from a url
  3860. * @param url url to load
  3861. * @param onSuccess callback called when the file successfully loads
  3862. * @param onProgress callback called while file is loading (if the server supports this mode)
  3863. * @param offlineProvider defines the offline provider for caching
  3864. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  3865. * @param onError callback called when the file fails to load
  3866. * @returns a file request object
  3867. * @hidden
  3868. */
  3869. 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 {
  3870. throw _DevTools.WarnImport("FileTools");
  3871. }
  3872. /**
  3873. * Reads pixels from the current frame buffer. Please note that this function can be slow
  3874. * @param x defines the x coordinate of the rectangle where pixels must be read
  3875. * @param y defines the y coordinate of the rectangle where pixels must be read
  3876. * @param width defines the width of the rectangle where pixels must be read
  3877. * @param height defines the height of the rectangle where pixels must be read
  3878. * @param hasAlpha defines whether the output should have alpha or not (defaults to true)
  3879. * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels
  3880. * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors
  3881. */
  3882. public readPixels(x: number, y: number, width: number, height: number, hasAlpha = true, flushRenderer = true): Promise<ArrayBufferView> {
  3883. const numChannels = hasAlpha ? 4 : 3;
  3884. const format = hasAlpha ? this._gl.RGBA : this._gl.RGB;
  3885. const data = new Uint8Array(height * width * numChannels);
  3886. if (flushRenderer) {
  3887. this.flushFramebuffer();
  3888. }
  3889. this._gl.readPixels(x, y, width, height, format, this._gl.UNSIGNED_BYTE, data);
  3890. return Promise.resolve(data);
  3891. }
  3892. // Statics
  3893. private static _IsSupported: Nullable<boolean> = null;
  3894. private static _HasMajorPerformanceCaveat : Nullable<boolean> = null;
  3895. /**
  3896. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  3897. */
  3898. public static get IsSupported(): boolean {
  3899. return this.isSupported(); // Backward compat
  3900. }
  3901. /**
  3902. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  3903. * @returns true if the engine can be created
  3904. * @ignorenaming
  3905. */
  3906. public static isSupported(): boolean {
  3907. if (this._HasMajorPerformanceCaveat !== null) {
  3908. return !this._HasMajorPerformanceCaveat; // We know it is performant so WebGL is supported
  3909. }
  3910. if (this._IsSupported === null) {
  3911. try {
  3912. var tempcanvas = CanvasGenerator.CreateCanvas(1, 1);
  3913. var gl = tempcanvas.getContext("webgl") || (tempcanvas as any).getContext("experimental-webgl");
  3914. this._IsSupported = gl != null && !!window.WebGLRenderingContext;
  3915. } catch (e) {
  3916. this._IsSupported = false;
  3917. }
  3918. }
  3919. return this._IsSupported;
  3920. }
  3921. /**
  3922. * 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)
  3923. */
  3924. public static get HasMajorPerformanceCaveat(): boolean {
  3925. if (this._HasMajorPerformanceCaveat === null) {
  3926. try {
  3927. var tempcanvas = CanvasGenerator.CreateCanvas(1, 1);
  3928. var gl = tempcanvas.getContext("webgl", { failIfMajorPerformanceCaveat: true }) || (tempcanvas as any).getContext("experimental-webgl", { failIfMajorPerformanceCaveat: true });
  3929. this._HasMajorPerformanceCaveat = !gl;
  3930. } catch (e) {
  3931. this._HasMajorPerformanceCaveat = false;
  3932. }
  3933. }
  3934. return this._HasMajorPerformanceCaveat;
  3935. }
  3936. /**
  3937. * Find the next highest power of two.
  3938. * @param x Number to start search from.
  3939. * @return Next highest power of two.
  3940. */
  3941. public static CeilingPOT(x: number): number {
  3942. x--;
  3943. x |= x >> 1;
  3944. x |= x >> 2;
  3945. x |= x >> 4;
  3946. x |= x >> 8;
  3947. x |= x >> 16;
  3948. x++;
  3949. return x;
  3950. }
  3951. /**
  3952. * Find the next lowest power of two.
  3953. * @param x Number to start search from.
  3954. * @return Next lowest power of two.
  3955. */
  3956. public static FloorPOT(x: number): number {
  3957. x = x | (x >> 1);
  3958. x = x | (x >> 2);
  3959. x = x | (x >> 4);
  3960. x = x | (x >> 8);
  3961. x = x | (x >> 16);
  3962. return x - (x >> 1);
  3963. }
  3964. /**
  3965. * Find the nearest power of two.
  3966. * @param x Number to start search from.
  3967. * @return Next nearest power of two.
  3968. */
  3969. public static NearestPOT(x: number): number {
  3970. var c = ThinEngine.CeilingPOT(x);
  3971. var f = ThinEngine.FloorPOT(x);
  3972. return (c - x) > (x - f) ? f : c;
  3973. }
  3974. /**
  3975. * Get the closest exponent of two
  3976. * @param value defines the value to approximate
  3977. * @param max defines the maximum value to return
  3978. * @param mode defines how to define the closest value
  3979. * @returns closest exponent of two of the given value
  3980. */
  3981. public static GetExponentOfTwo(value: number, max: number, mode = Constants.SCALEMODE_NEAREST): number {
  3982. let pot;
  3983. switch (mode) {
  3984. case Constants.SCALEMODE_FLOOR:
  3985. pot = ThinEngine.FloorPOT(value);
  3986. break;
  3987. case Constants.SCALEMODE_NEAREST:
  3988. pot = ThinEngine.NearestPOT(value);
  3989. break;
  3990. case Constants.SCALEMODE_CEILING:
  3991. default:
  3992. pot = ThinEngine.CeilingPOT(value);
  3993. break;
  3994. }
  3995. return Math.min(pot, max);
  3996. }
  3997. /**
  3998. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  3999. * @param func - the function to be called
  4000. * @param requester - the object that will request the next frame. Falls back to window.
  4001. * @returns frame number
  4002. */
  4003. public static QueueNewFrame(func: () => void, requester?: any): number {
  4004. if (!DomManagement.IsWindowObjectExist()) {
  4005. if (typeof requestAnimationFrame !== "undefined") {
  4006. return requestAnimationFrame(func);
  4007. }
  4008. return setTimeout(func, 16);
  4009. }
  4010. if (!requester) {
  4011. requester = window;
  4012. }
  4013. if (requester.requestPostAnimationFrame) {
  4014. return requester.requestPostAnimationFrame(func);
  4015. }
  4016. else if (requester.requestAnimationFrame) {
  4017. return requester.requestAnimationFrame(func);
  4018. }
  4019. else if (requester.msRequestAnimationFrame) {
  4020. return requester.msRequestAnimationFrame(func);
  4021. }
  4022. else if (requester.webkitRequestAnimationFrame) {
  4023. return requester.webkitRequestAnimationFrame(func);
  4024. }
  4025. else if (requester.mozRequestAnimationFrame) {
  4026. return requester.mozRequestAnimationFrame(func);
  4027. }
  4028. else if (requester.oRequestAnimationFrame) {
  4029. return requester.oRequestAnimationFrame(func);
  4030. }
  4031. else {
  4032. return window.setTimeout(func, 16);
  4033. }
  4034. }
  4035. /**
  4036. * Gets host document
  4037. * @returns the host document object
  4038. */
  4039. public getHostDocument(): Nullable<Document> {
  4040. if (this._renderingCanvas && this._renderingCanvas.ownerDocument) {
  4041. return this._renderingCanvas.ownerDocument;
  4042. }
  4043. return document;
  4044. }
  4045. }