thinEngine.js 163 KB

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