thinEngine.ts 190 KB

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