WebGLBackend.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596
  1. import { WebGLCoordinateSystem } from 'three';
  2. import GLSLNodeBuilder from './nodes/GLSLNodeBuilder.js';
  3. import Backend from '../common/Backend.js';
  4. import WebGLAttributeUtils from './utils/WebGLAttributeUtils.js';
  5. import WebGLState from './utils/WebGLState.js';
  6. import WebGLUtils from './utils/WebGLUtils.js';
  7. import WebGLTextureUtils from './utils/WebGLTextureUtils.js';
  8. import WebGLExtensions from './utils/WebGLExtensions.js';
  9. import WebGLCapabilities from './utils/WebGLCapabilities.js';
  10. import { GLFeatureName } from './utils/WebGLConstants.js';
  11. import { WebGLBufferRenderer } from './WebGLBufferRenderer.js';
  12. import { warnOnce } from '../../../../src/utils.js';
  13. //
  14. class WebGLBackend extends Backend {
  15. constructor( parameters = {} ) {
  16. super( parameters );
  17. this.isWebGLBackend = true;
  18. }
  19. init( renderer ) {
  20. super.init( renderer );
  21. //
  22. const parameters = this.parameters;
  23. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  24. this.gl = glContext;
  25. this.extensions = new WebGLExtensions( this );
  26. this.capabilities = new WebGLCapabilities( this );
  27. this.attributeUtils = new WebGLAttributeUtils( this );
  28. this.textureUtils = new WebGLTextureUtils( this );
  29. this.bufferRenderer = new WebGLBufferRenderer( this );
  30. this.state = new WebGLState( this );
  31. this.utils = new WebGLUtils( this );
  32. this.vaoCache = {};
  33. this.transformFeedbackCache = {};
  34. this.discard = false;
  35. this.trackTimestamp = ( parameters.trackTimestamp === true );
  36. this.extensions.get( 'EXT_color_buffer_float' );
  37. this.extensions.get( 'WEBGL_multi_draw' );
  38. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  39. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40. this._currentContext = null;
  41. }
  42. get coordinateSystem() {
  43. return WebGLCoordinateSystem;
  44. }
  45. async getArrayBufferAsync( attribute ) {
  46. return await this.attributeUtils.getArrayBufferAsync( attribute );
  47. }
  48. initTimestampQuery( renderContext ) {
  49. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  50. const renderContextData = this.get( renderContext );
  51. if ( this.queryRunning ) {
  52. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  53. renderContextData.queryQueue.push( renderContext );
  54. return;
  55. }
  56. if ( renderContextData.activeQuery ) {
  57. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  58. renderContextData.activeQuery = null;
  59. }
  60. renderContextData.activeQuery = this.gl.createQuery();
  61. if ( renderContextData.activeQuery !== null ) {
  62. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  63. this.queryRunning = true;
  64. }
  65. }
  66. // timestamp utils
  67. prepareTimestampBuffer( renderContext ) {
  68. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  69. const renderContextData = this.get( renderContext );
  70. if ( renderContextData.activeQuery ) {
  71. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  72. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  73. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  74. renderContextData.activeQuery = null;
  75. this.queryRunning = false;
  76. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  77. const nextRenderContext = renderContextData.queryQueue.shift();
  78. this.initTimestampQuery( nextRenderContext );
  79. }
  80. }
  81. }
  82. async resolveTimestampAsync( renderContext, type = 'render' ) {
  83. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  84. const renderContextData = this.get( renderContext );
  85. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  86. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  87. const queryInfo = renderContextData.gpuQueries[ i ];
  88. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  89. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  90. if ( available && ! disjoint ) {
  91. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  92. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  93. this.gl.deleteQuery( queryInfo.query );
  94. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  95. i --;
  96. this.renderer.info.updateTimestamp( type, duration );
  97. }
  98. }
  99. }
  100. getContext() {
  101. return this.gl;
  102. }
  103. beginRender( renderContext ) {
  104. const { gl } = this;
  105. const renderContextData = this.get( renderContext );
  106. //
  107. //
  108. this.initTimestampQuery( renderContext );
  109. renderContextData.previousContext = this._currentContext;
  110. this._currentContext = renderContext;
  111. this._setFramebuffer( renderContext );
  112. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  113. //
  114. if ( renderContext.viewport ) {
  115. this.updateViewport( renderContext );
  116. } else {
  117. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  118. }
  119. if ( renderContext.scissor ) {
  120. const { x, y, width, height } = renderContext.scissorValue;
  121. gl.scissor( x, y, width, height );
  122. }
  123. const occlusionQueryCount = renderContext.occlusionQueryCount;
  124. if ( occlusionQueryCount > 0 ) {
  125. // Get a reference to the array of objects with queries. The renderContextData property
  126. // can be changed by another render pass before the async reading of all previous queries complete
  127. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  128. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  129. renderContextData.lastOcclusionObject = null;
  130. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  131. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  132. renderContextData.occlusionQueryIndex = 0;
  133. }
  134. }
  135. finishRender( renderContext ) {
  136. const { gl, state } = this;
  137. const renderContextData = this.get( renderContext );
  138. const previousContext = renderContextData.previousContext;
  139. const textures = renderContext.textures;
  140. if ( textures !== null ) {
  141. for ( let i = 0; i < textures.length; i ++ ) {
  142. const texture = textures[ i ];
  143. if ( texture.generateMipmaps ) {
  144. this.generateMipmaps( texture );
  145. }
  146. }
  147. }
  148. this._currentContext = previousContext;
  149. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  150. const renderTargetContextData = this.get( renderContext.renderTarget );
  151. const { samples } = renderContext.renderTarget;
  152. const fb = renderTargetContextData.framebuffer;
  153. const mask = gl.COLOR_BUFFER_BIT;
  154. if ( samples > 0 ) {
  155. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  156. const textures = renderContext.textures;
  157. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  158. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  159. for ( let i = 0; i < textures.length; i ++ ) {
  160. // TODO Add support for MRT
  161. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  162. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  163. }
  164. }
  165. }
  166. if ( previousContext !== null ) {
  167. this._setFramebuffer( previousContext );
  168. if ( previousContext.viewport ) {
  169. this.updateViewport( previousContext );
  170. } else {
  171. const gl = this.gl;
  172. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  173. }
  174. }
  175. const occlusionQueryCount = renderContext.occlusionQueryCount;
  176. if ( occlusionQueryCount > 0 ) {
  177. const renderContextData = this.get( renderContext );
  178. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  179. const { gl } = this;
  180. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  181. }
  182. this.resolveOccludedAsync( renderContext );
  183. }
  184. this.prepareTimestampBuffer( renderContext );
  185. }
  186. resolveOccludedAsync( renderContext ) {
  187. const renderContextData = this.get( renderContext );
  188. // handle occlusion query results
  189. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  190. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  191. const occluded = new WeakSet();
  192. const { gl } = this;
  193. renderContextData.currentOcclusionQueryObjects = null;
  194. renderContextData.currentOcclusionQueries = null;
  195. const check = () => {
  196. let completed = 0;
  197. // check all queries and requeue as appropriate
  198. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  199. const query = currentOcclusionQueries[ i ];
  200. if ( query === null ) continue;
  201. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  202. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  203. currentOcclusionQueries[ i ] = null;
  204. gl.deleteQuery( query );
  205. completed ++;
  206. }
  207. }
  208. if ( completed < currentOcclusionQueries.length ) {
  209. requestAnimationFrame( check );
  210. } else {
  211. renderContextData.occluded = occluded;
  212. }
  213. };
  214. check();
  215. }
  216. }
  217. isOccluded( renderContext, object ) {
  218. const renderContextData = this.get( renderContext );
  219. return renderContextData.occluded && renderContextData.occluded.has( object );
  220. }
  221. updateViewport( renderContext ) {
  222. const gl = this.gl;
  223. const { x, y, width, height } = renderContext.viewportValue;
  224. gl.viewport( x, y, width, height );
  225. }
  226. setScissorTest( boolean ) {
  227. const gl = this.gl;
  228. if ( boolean ) {
  229. gl.enable( gl.SCISSOR_TEST );
  230. } else {
  231. gl.disable( gl.SCISSOR_TEST );
  232. }
  233. }
  234. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  235. const { gl } = this;
  236. if ( descriptor === null ) {
  237. descriptor = {
  238. textures: null,
  239. clearColorValue: this.getClearColor()
  240. };
  241. }
  242. //
  243. let clear = 0;
  244. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  245. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  246. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  247. if ( clear !== 0 ) {
  248. const clearColor = descriptor.clearColorValue || this.getClearColor();
  249. if ( depth ) this.state.setDepthMask( true );
  250. if ( descriptor.textures === null ) {
  251. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  252. gl.clear( clear );
  253. } else {
  254. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  255. if ( color ) {
  256. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  257. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  258. }
  259. }
  260. if ( depth && stencil ) {
  261. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  262. } else if ( depth ) {
  263. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  264. } else if ( stencil ) {
  265. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  266. }
  267. }
  268. }
  269. }
  270. beginCompute( computeGroup ) {
  271. const gl = this.gl;
  272. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  273. this.initTimestampQuery( computeGroup );
  274. }
  275. compute( computeGroup, computeNode, bindings, pipeline ) {
  276. const gl = this.gl;
  277. if ( ! this.discard ) {
  278. // required here to handle async behaviour of render.compute()
  279. gl.enable( gl.RASTERIZER_DISCARD );
  280. this.discard = true;
  281. }
  282. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  283. const vaoKey = this._getVaoKey( null, attributes );
  284. const vaoGPU = this.vaoCache[ vaoKey ];
  285. if ( vaoGPU === undefined ) {
  286. this._createVao( null, attributes );
  287. } else {
  288. gl.bindVertexArray( vaoGPU );
  289. }
  290. gl.useProgram( programGPU );
  291. this._bindUniforms( bindings );
  292. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  293. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  294. gl.beginTransformFeedback( gl.POINTS );
  295. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  296. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  297. } else {
  298. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  299. }
  300. gl.endTransformFeedback();
  301. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  302. // switch active buffers
  303. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  304. const dualAttributeData = transformBuffers[ i ];
  305. if ( dualAttributeData.pbo ) {
  306. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  307. }
  308. dualAttributeData.switchBuffers();
  309. }
  310. }
  311. finishCompute( computeGroup ) {
  312. const gl = this.gl;
  313. this.discard = false;
  314. gl.disable( gl.RASTERIZER_DISCARD );
  315. this.prepareTimestampBuffer( computeGroup );
  316. }
  317. draw( renderObject/*, info*/ ) {
  318. const { object, pipeline, material, context } = renderObject;
  319. const { programGPU } = this.get( pipeline );
  320. const { gl, state } = this;
  321. const contextData = this.get( context );
  322. //
  323. this._bindUniforms( renderObject.getBindings() );
  324. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  325. state.setMaterial( material, frontFaceCW );
  326. gl.useProgram( programGPU );
  327. //
  328. let vaoGPU = renderObject.staticVao;
  329. if ( vaoGPU === undefined ) {
  330. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  331. vaoGPU = this.vaoCache[ vaoKey ];
  332. if ( vaoGPU === undefined ) {
  333. let staticVao;
  334. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  335. if ( staticVao ) renderObject.staticVao = vaoGPU;
  336. }
  337. }
  338. gl.bindVertexArray( vaoGPU );
  339. //
  340. const index = renderObject.getIndex();
  341. const geometry = renderObject.geometry;
  342. const drawRange = renderObject.drawRange;
  343. const firstVertex = drawRange.start;
  344. //
  345. const lastObject = contextData.lastOcclusionObject;
  346. if ( lastObject !== object && lastObject !== undefined ) {
  347. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  348. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  349. contextData.occlusionQueryIndex ++;
  350. }
  351. if ( object.occlusionTest === true ) {
  352. const query = gl.createQuery();
  353. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  354. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  355. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  356. }
  357. contextData.lastOcclusionObject = object;
  358. }
  359. //
  360. const renderer = this.bufferRenderer;
  361. if ( object.isPoints ) renderer.mode = gl.POINTS;
  362. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  363. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  364. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  365. else {
  366. if ( material.wireframe === true ) {
  367. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  368. renderer.mode = gl.LINES;
  369. } else {
  370. renderer.mode = gl.TRIANGLES;
  371. }
  372. }
  373. //
  374. let count;
  375. renderer.object = object;
  376. if ( index !== null ) {
  377. const indexData = this.get( index );
  378. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  379. renderer.index = index.count;
  380. renderer.type = indexData.type;
  381. count = indexCount;
  382. } else {
  383. renderer.index = 0;
  384. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : geometry.attributes.position.count;
  385. count = vertexCount;
  386. }
  387. const instanceCount = this.getInstanceCount( renderObject );
  388. if ( object.isBatchedMesh ) {
  389. if ( object._multiDrawInstances !== null ) {
  390. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  391. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  392. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  393. } else {
  394. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  395. }
  396. } else if ( instanceCount > 1 ) {
  397. renderer.renderInstances( firstVertex, count, instanceCount );
  398. } else {
  399. renderer.render( firstVertex, count );
  400. }
  401. //
  402. gl.bindVertexArray( null );
  403. }
  404. needsRenderUpdate( /*renderObject*/ ) {
  405. return false;
  406. }
  407. getRenderCacheKey( renderObject ) {
  408. return renderObject.id;
  409. }
  410. // textures
  411. createDefaultTexture( texture ) {
  412. this.textureUtils.createDefaultTexture( texture );
  413. }
  414. createTexture( texture, options ) {
  415. this.textureUtils.createTexture( texture, options );
  416. }
  417. updateTexture( texture, options ) {
  418. this.textureUtils.updateTexture( texture, options );
  419. }
  420. generateMipmaps( texture ) {
  421. this.textureUtils.generateMipmaps( texture );
  422. }
  423. destroyTexture( texture ) {
  424. this.textureUtils.destroyTexture( texture );
  425. }
  426. copyTextureToBuffer( texture, x, y, width, height ) {
  427. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  428. }
  429. createSampler( /*texture*/ ) {
  430. //console.warn( 'Abstract class.' );
  431. }
  432. destroySampler() {}
  433. // node builder
  434. createNodeBuilder( object, renderer ) {
  435. return new GLSLNodeBuilder( object, renderer );
  436. }
  437. // program
  438. createProgram( program ) {
  439. const gl = this.gl;
  440. const { stage, code } = program;
  441. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  442. gl.shaderSource( shader, code );
  443. gl.compileShader( shader );
  444. this.set( program, {
  445. shaderGPU: shader
  446. } );
  447. }
  448. destroyProgram( /*program*/ ) {
  449. console.warn( 'Abstract class.' );
  450. }
  451. createRenderPipeline( renderObject, promises ) {
  452. const gl = this.gl;
  453. const pipeline = renderObject.pipeline;
  454. // Program
  455. const { fragmentProgram, vertexProgram } = pipeline;
  456. const programGPU = gl.createProgram();
  457. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  458. const vertexShader = this.get( vertexProgram ).shaderGPU;
  459. gl.attachShader( programGPU, fragmentShader );
  460. gl.attachShader( programGPU, vertexShader );
  461. gl.linkProgram( programGPU );
  462. this.set( pipeline, {
  463. programGPU,
  464. fragmentShader,
  465. vertexShader
  466. } );
  467. if ( promises !== null && this.parallel ) {
  468. const p = new Promise( ( resolve /*, reject*/ ) => {
  469. const parallel = this.parallel;
  470. const checkStatus = () => {
  471. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  472. this._completeCompile( renderObject, pipeline );
  473. resolve();
  474. } else {
  475. requestAnimationFrame( checkStatus );
  476. }
  477. };
  478. checkStatus();
  479. } );
  480. promises.push( p );
  481. return;
  482. }
  483. this._completeCompile( renderObject, pipeline );
  484. }
  485. _handleSource( string, errorLine ) {
  486. const lines = string.split( '\n' );
  487. const lines2 = [];
  488. const from = Math.max( errorLine - 6, 0 );
  489. const to = Math.min( errorLine + 6, lines.length );
  490. for ( let i = from; i < to; i ++ ) {
  491. const line = i + 1;
  492. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  493. }
  494. return lines2.join( '\n' );
  495. }
  496. _getShaderErrors( gl, shader, type ) {
  497. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  498. const errors = gl.getShaderInfoLog( shader ).trim();
  499. if ( status && errors === '' ) return '';
  500. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  501. if ( errorMatches ) {
  502. const errorLine = parseInt( errorMatches[ 1 ] );
  503. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  504. } else {
  505. return errors;
  506. }
  507. }
  508. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  509. if ( this.renderer.debug.checkShaderErrors ) {
  510. const gl = this.gl;
  511. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  512. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  513. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  514. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  515. } else {
  516. // default error reporting
  517. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  518. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  519. console.error(
  520. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  521. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  522. 'Program Info Log: ' + programLog + '\n' +
  523. vertexErrors + '\n' +
  524. fragmentErrors
  525. );
  526. }
  527. } else if ( programLog !== '' ) {
  528. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  529. }
  530. }
  531. }
  532. _completeCompile( renderObject, pipeline ) {
  533. const gl = this.gl;
  534. const pipelineData = this.get( pipeline );
  535. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  536. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  537. this._logProgramError( programGPU, fragmentShader, vertexShader );
  538. }
  539. gl.useProgram( programGPU );
  540. // Bindings
  541. const bindings = renderObject.getBindings();
  542. this._setupBindings( bindings, programGPU );
  543. //
  544. this.set( pipeline, {
  545. programGPU
  546. } );
  547. }
  548. createComputePipeline( computePipeline, bindings ) {
  549. const gl = this.gl;
  550. // Program
  551. const fragmentProgram = {
  552. stage: 'fragment',
  553. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  554. };
  555. this.createProgram( fragmentProgram );
  556. const { computeProgram } = computePipeline;
  557. const programGPU = gl.createProgram();
  558. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  559. const vertexShader = this.get( computeProgram ).shaderGPU;
  560. const transforms = computeProgram.transforms;
  561. const transformVaryingNames = [];
  562. const transformAttributeNodes = [];
  563. for ( let i = 0; i < transforms.length; i ++ ) {
  564. const transform = transforms[ i ];
  565. transformVaryingNames.push( transform.varyingName );
  566. transformAttributeNodes.push( transform.attributeNode );
  567. }
  568. gl.attachShader( programGPU, fragmentShader );
  569. gl.attachShader( programGPU, vertexShader );
  570. gl.transformFeedbackVaryings(
  571. programGPU,
  572. transformVaryingNames,
  573. gl.SEPARATE_ATTRIBS
  574. );
  575. gl.linkProgram( programGPU );
  576. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  577. this._logProgramError( programGPU, fragmentShader, vertexShader );
  578. }
  579. gl.useProgram( programGPU );
  580. // Bindings
  581. this.createBindings( null, bindings );
  582. this._setupBindings( bindings, programGPU );
  583. const attributeNodes = computeProgram.attributes;
  584. const attributes = [];
  585. const transformBuffers = [];
  586. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  587. const attribute = attributeNodes[ i ].node.attribute;
  588. attributes.push( attribute );
  589. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  590. }
  591. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  592. const attribute = transformAttributeNodes[ i ].attribute;
  593. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  594. const attributeData = this.get( attribute );
  595. transformBuffers.push( attributeData );
  596. }
  597. //
  598. this.set( computePipeline, {
  599. programGPU,
  600. transformBuffers,
  601. attributes
  602. } );
  603. }
  604. createBindings( bindGroup, bindings ) {
  605. this.updateBindings( bindGroup, bindings );
  606. }
  607. updateBindings( bindGroup, bindings ) {
  608. const { gl } = this;
  609. let groupIndex = 0;
  610. let textureIndex = 0;
  611. for ( const bindGroup of bindings ) {
  612. for ( const binding of bindGroup.bindings ) {
  613. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  614. const bufferGPU = gl.createBuffer();
  615. const data = binding.buffer;
  616. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  617. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  618. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  619. this.set( binding, {
  620. index: groupIndex ++,
  621. bufferGPU
  622. } );
  623. } else if ( binding.isSampledTexture ) {
  624. const { textureGPU, glTextureType } = this.get( binding.texture );
  625. this.set( binding, {
  626. index: textureIndex ++,
  627. textureGPU,
  628. glTextureType
  629. } );
  630. }
  631. }
  632. }
  633. }
  634. updateBinding( binding ) {
  635. const gl = this.gl;
  636. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  637. const bindingData = this.get( binding );
  638. const bufferGPU = bindingData.bufferGPU;
  639. const data = binding.buffer;
  640. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  641. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  642. }
  643. }
  644. // attributes
  645. createIndexAttribute( attribute ) {
  646. const gl = this.gl;
  647. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  648. }
  649. createAttribute( attribute ) {
  650. if ( this.has( attribute ) ) return;
  651. const gl = this.gl;
  652. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  653. }
  654. createStorageAttribute( attribute ) {
  655. if ( this.has( attribute ) ) return;
  656. const gl = this.gl;
  657. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  658. }
  659. updateAttribute( attribute ) {
  660. this.attributeUtils.updateAttribute( attribute );
  661. }
  662. destroyAttribute( attribute ) {
  663. this.attributeUtils.destroyAttribute( attribute );
  664. }
  665. updateSize() {
  666. //console.warn( 'Abstract class.' );
  667. }
  668. hasFeature( name ) {
  669. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  670. const extensions = this.extensions;
  671. for ( let i = 0; i < keysMatching.length; i ++ ) {
  672. if ( extensions.has( keysMatching[ i ] ) ) return true;
  673. }
  674. return false;
  675. }
  676. getMaxAnisotropy() {
  677. return this.capabilities.getMaxAnisotropy();
  678. }
  679. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  680. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  681. }
  682. copyFramebufferToTexture( texture, renderContext ) {
  683. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  684. }
  685. _setFramebuffer( renderContext ) {
  686. const { gl, state } = this;
  687. let currentFrameBuffer = null;
  688. if ( renderContext.textures !== null ) {
  689. const renderTarget = renderContext.renderTarget;
  690. const renderTargetContextData = this.get( renderTarget );
  691. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  692. const cubeFace = this.renderer._activeCubeFace;
  693. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  694. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  695. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  696. let fb;
  697. if ( isCube ) {
  698. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  699. renderTargetContextData.cubeFramebuffers = [];
  700. }
  701. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  702. } else {
  703. fb = renderTargetContextData.framebuffer;
  704. }
  705. if ( fb === undefined ) {
  706. fb = gl.createFramebuffer();
  707. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  708. const textures = renderContext.textures;
  709. if ( isCube ) {
  710. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  711. const { textureGPU } = this.get( textures[ 0 ] );
  712. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  713. } else {
  714. for ( let i = 0; i < textures.length; i ++ ) {
  715. const texture = textures[ i ];
  716. const textureData = this.get( texture );
  717. textureData.renderTarget = renderContext.renderTarget;
  718. const attachment = gl.COLOR_ATTACHMENT0 + i;
  719. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  720. }
  721. renderTargetContextData.framebuffer = fb;
  722. state.drawBuffers( renderContext, fb );
  723. }
  724. if ( renderContext.depthTexture !== null ) {
  725. const textureData = this.get( renderContext.depthTexture );
  726. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  727. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  728. }
  729. }
  730. if ( samples > 0 ) {
  731. if ( msaaFb === undefined ) {
  732. const invalidationArray = [];
  733. msaaFb = gl.createFramebuffer();
  734. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  735. const msaaRenderbuffers = [];
  736. const textures = renderContext.textures;
  737. for ( let i = 0; i < textures.length; i ++ ) {
  738. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  739. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  740. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  741. if ( depthBuffer ) {
  742. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  743. invalidationArray.push( depthStyle );
  744. }
  745. const texture = renderContext.textures[ i ];
  746. const textureData = this.get( texture );
  747. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  748. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  749. }
  750. renderTargetContextData.msaaFrameBuffer = msaaFb;
  751. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  752. if ( depthRenderbuffer === undefined ) {
  753. depthRenderbuffer = gl.createRenderbuffer();
  754. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  755. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  756. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  757. invalidationArray.push( depthStyle );
  758. }
  759. renderTargetContextData.invalidationArray = invalidationArray;
  760. }
  761. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  762. } else {
  763. currentFrameBuffer = fb;
  764. }
  765. }
  766. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  767. }
  768. _getVaoKey( index, attributes ) {
  769. let key = [];
  770. if ( index !== null ) {
  771. const indexData = this.get( index );
  772. key += ':' + indexData.id;
  773. }
  774. for ( let i = 0; i < attributes.length; i ++ ) {
  775. const attributeData = this.get( attributes[ i ] );
  776. key += ':' + attributeData.id;
  777. }
  778. return key;
  779. }
  780. _createVao( index, attributes ) {
  781. const { gl } = this;
  782. const vaoGPU = gl.createVertexArray();
  783. let key = '';
  784. let staticVao = true;
  785. gl.bindVertexArray( vaoGPU );
  786. if ( index !== null ) {
  787. const indexData = this.get( index );
  788. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  789. key += ':' + indexData.id;
  790. }
  791. for ( let i = 0; i < attributes.length; i ++ ) {
  792. const attribute = attributes[ i ];
  793. const attributeData = this.get( attribute );
  794. key += ':' + attributeData.id;
  795. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  796. gl.enableVertexAttribArray( i );
  797. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  798. let stride, offset;
  799. if ( attribute.isInterleavedBufferAttribute === true ) {
  800. stride = attribute.data.stride * attributeData.bytesPerElement;
  801. offset = attribute.offset * attributeData.bytesPerElement;
  802. } else {
  803. stride = 0;
  804. offset = 0;
  805. }
  806. if ( attributeData.isInteger ) {
  807. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  808. } else {
  809. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  810. }
  811. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  812. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  813. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  814. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  815. }
  816. }
  817. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  818. this.vaoCache[ key ] = vaoGPU;
  819. return { vaoGPU, staticVao };
  820. }
  821. _getTransformFeedback( transformBuffers ) {
  822. let key = '';
  823. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  824. key += ':' + transformBuffers[ i ].id;
  825. }
  826. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  827. if ( transformFeedbackGPU !== undefined ) {
  828. return transformFeedbackGPU;
  829. }
  830. const gl = this.gl;
  831. transformFeedbackGPU = gl.createTransformFeedback();
  832. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  833. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  834. const attributeData = transformBuffers[ i ];
  835. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  836. }
  837. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  838. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  839. return transformFeedbackGPU;
  840. }
  841. _setupBindings( bindings, programGPU ) {
  842. const gl = this.gl;
  843. for ( const bindGroup of bindings ) {
  844. for ( const binding of bindGroup.bindings ) {
  845. const bindingData = this.get( binding );
  846. const index = bindingData.index;
  847. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  848. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  849. gl.uniformBlockBinding( programGPU, location, index );
  850. } else if ( binding.isSampledTexture ) {
  851. const location = gl.getUniformLocation( programGPU, binding.name );
  852. gl.uniform1i( location, index );
  853. }
  854. }
  855. }
  856. }
  857. _bindUniforms( bindings ) {
  858. const { gl, state } = this;
  859. for ( const bindGroup of bindings ) {
  860. for ( const binding of bindGroup.bindings ) {
  861. const bindingData = this.get( binding );
  862. const index = bindingData.index;
  863. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  864. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  865. } else if ( binding.isSampledTexture ) {
  866. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  867. }
  868. }
  869. }
  870. }
  871. }
  872. export default WebGLBackend;