WebGLBackend.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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. //
  12. class WebGLBackend extends Backend {
  13. constructor( parameters = {} ) {
  14. super( parameters );
  15. this.isWebGLBackend = true;
  16. }
  17. init( renderer ) {
  18. super.init( renderer );
  19. //
  20. const parameters = this.parameters;
  21. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  22. this.gl = glContext;
  23. this.extensions = new WebGLExtensions( this );
  24. this.capabilities = new WebGLCapabilities( this );
  25. this.attributeUtils = new WebGLAttributeUtils( this );
  26. this.textureUtils = new WebGLTextureUtils( this );
  27. this.state = new WebGLState( this );
  28. this.utils = new WebGLUtils( this );
  29. this.extensions.get( 'EXT_color_buffer_float' );
  30. this._currentContext = null;
  31. }
  32. get coordinateSystem() {
  33. return WebGLCoordinateSystem;
  34. }
  35. async getArrayBufferAsync( attribute ) {
  36. return await this.attributeUtils.getArrayBufferAsync( attribute );
  37. }
  38. getContext() {
  39. return this.gl;
  40. }
  41. beginRender( renderContext ) {
  42. const { gl } = this;
  43. const renderContextData = this.get( renderContext );
  44. //
  45. renderContextData.previousContext = this._currentContext;
  46. this._currentContext = renderContext;
  47. this._setFramebuffer( renderContext );
  48. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext );
  49. //
  50. if ( renderContext.viewport ) {
  51. this.updateViewport( renderContext );
  52. } else {
  53. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  54. }
  55. const occlusionQueryCount = renderContext.occlusionQueryCount;
  56. if ( occlusionQueryCount > 0 ) {
  57. // Get a reference to the array of objects with queries. The renderContextData property
  58. // can be changed by another render pass before the async reading of all previous queries complete
  59. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  60. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  61. renderContextData.lastOcclusionObject = null;
  62. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  63. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  64. renderContextData.occlusionQueryIndex = 0;
  65. }
  66. }
  67. finishRender( renderContext ) {
  68. const renderContextData = this.get( renderContext );
  69. const previousContext = renderContextData.previousContext;
  70. this._currentContext = previousContext;
  71. if ( previousContext !== null ) {
  72. this._setFramebuffer( previousContext );
  73. if ( previousContext.viewport ) {
  74. this.updateViewport( previousContext );
  75. } else {
  76. const gl = this.gl;
  77. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  78. }
  79. }
  80. const occlusionQueryCount = renderContext.occlusionQueryCount;
  81. if ( occlusionQueryCount > 0 ) {
  82. const renderContextData = this.get( renderContext );
  83. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  84. const { gl } = this;
  85. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  86. }
  87. this.resolveOccludedAsync( renderContext );
  88. }
  89. }
  90. resolveOccludedAsync( renderContext ) {
  91. const renderContextData = this.get( renderContext );
  92. // handle occlusion query results
  93. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  94. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  95. const occluded = new WeakSet();
  96. const { gl } = this;
  97. renderContextData.currentOcclusionQueryObjects = null;
  98. renderContextData.currentOcclusionQueries = null;
  99. const check = () => {
  100. let completed = 0;
  101. // check all queries and requeue as appropriate
  102. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  103. const query = currentOcclusionQueries[ i ];
  104. if ( query === null ) continue;
  105. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  106. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  107. currentOcclusionQueries[ i ] = null;
  108. gl.deleteQuery( query );
  109. completed ++;
  110. }
  111. }
  112. if ( completed < currentOcclusionQueries.length ) {
  113. requestAnimationFrame( check );
  114. } else {
  115. renderContextData.occluded = occluded;
  116. }
  117. };
  118. check();
  119. }
  120. }
  121. isOccluded( renderContext, object ) {
  122. const renderContextData = this.get( renderContext );
  123. return renderContextData.occluded && renderContextData.occluded.has( object );
  124. }
  125. updateViewport( renderContext ) {
  126. const gl = this.gl;
  127. const { x, y, width, height } = renderContext.viewportValue;
  128. gl.viewport( x, y, width, height );
  129. }
  130. clear( color, depth, stencil, descriptor = null ) {
  131. const { gl } = this;
  132. if ( descriptor === null ) {
  133. descriptor = {
  134. textures: null,
  135. clearColorValue: this.getClearColor()
  136. };
  137. }
  138. //
  139. let clear = 0;
  140. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  141. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  142. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  143. if ( clear !== 0 ) {
  144. const clearColor = descriptor.clearColorValue;
  145. if ( depth ) this.state.setDepthMask( true );
  146. if ( descriptor.textures === null ) {
  147. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  148. gl.clear( clear );
  149. } else {
  150. if ( color ) {
  151. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  152. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  153. }
  154. }
  155. if ( depth && stencil ) {
  156. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  157. } else if ( depth ) {
  158. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  159. } else if ( stencil ) {
  160. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  161. }
  162. }
  163. }
  164. }
  165. beginCompute( /*computeGroup*/ ) {
  166. console.warn( 'Abstract class.' );
  167. }
  168. compute( /*computeGroup, computeNode, bindings, pipeline*/ ) {
  169. console.warn( 'Abstract class.' );
  170. }
  171. finishCompute( /*computeGroup*/ ) {
  172. console.warn( 'Abstract class.' );
  173. }
  174. draw( renderObject, info ) {
  175. const { pipeline, material, context } = renderObject;
  176. const { programGPU, vaoGPU } = this.get( pipeline );
  177. const { gl, state } = this;
  178. const contextData = this.get( context );
  179. //
  180. const bindings = renderObject.getBindings();
  181. for ( const binding of bindings ) {
  182. const bindingData = this.get( binding );
  183. const index = bindingData.index;
  184. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  185. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  186. } else if ( binding.isSampledTexture ) {
  187. gl.activeTexture( gl.TEXTURE0 + index );
  188. gl.bindTexture( bindingData.glTextureType, bindingData.textureGPU );
  189. }
  190. }
  191. state.setMaterial( material );
  192. gl.useProgram( programGPU );
  193. gl.bindVertexArray( vaoGPU );
  194. //
  195. const index = renderObject.getIndex();
  196. const object = renderObject.object;
  197. const geometry = renderObject.geometry;
  198. const drawRange = geometry.drawRange;
  199. const firstVertex = drawRange.start;
  200. //
  201. const lastObject = contextData.lastOcclusionObject;
  202. if ( lastObject !== object && lastObject !== undefined ) {
  203. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  204. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  205. contextData.occlusionQueryIndex ++;
  206. }
  207. if ( object.occlusionTest === true ) {
  208. const query = gl.createQuery();
  209. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  210. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  211. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  212. }
  213. contextData.lastOcclusionObject = object;
  214. }
  215. //
  216. let mode;
  217. if ( object.isPoints ) mode = gl.POINTS;
  218. else if ( object.isLineSegments ) mode = gl.LINES;
  219. else if ( object.isLine ) mode = gl.LINE_STRIP;
  220. else if ( object.isLineLoop ) mode = gl.LINE_LOOP;
  221. else mode = gl.TRIANGLES;
  222. //
  223. const instanceCount = this.getInstanceCount( renderObject );
  224. if ( index !== null ) {
  225. const indexData = this.get( index );
  226. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  227. if ( instanceCount > 1 ) {
  228. gl.drawElementsInstanced( mode, index.count, indexData.type, firstVertex, instanceCount );
  229. } else {
  230. gl.drawElements( mode, index.count, indexData.type, firstVertex );
  231. }
  232. info.update( object, indexCount, 1 );
  233. } else {
  234. const positionAttribute = geometry.attributes.position;
  235. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  236. if ( instanceCount > 1 ) {
  237. gl.drawArraysInstanced( mode, 0, vertexCount, instanceCount );
  238. } else {
  239. gl.drawArrays( mode, 0, vertexCount );
  240. }
  241. //gl.drawArrays( mode, vertexCount, gl.UNSIGNED_SHORT, firstVertex );
  242. info.update( object, vertexCount, 1 );
  243. }
  244. //
  245. gl.bindVertexArray( null );
  246. }
  247. needsRenderUpdate( /*renderObject*/ ) {
  248. return false;
  249. }
  250. getRenderCacheKey( renderObject ) {
  251. return renderObject.id;
  252. }
  253. // textures
  254. createDefaultTexture( texture ) {
  255. this.textureUtils.createDefaultTexture( texture );
  256. }
  257. createTexture( texture, options ) {
  258. this.textureUtils.createTexture( texture, options );
  259. }
  260. updateTexture( texture, options ) {
  261. this.textureUtils.updateTexture( texture, options );
  262. }
  263. generateMipmaps( texture ) {
  264. this.textureUtils.generateMipmaps( texture );
  265. }
  266. destroyTexture( texture ) {
  267. this.textureUtils.destroyTexture( texture );
  268. }
  269. copyTextureToBuffer( texture, x, y, width, height ) {
  270. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  271. }
  272. createSampler( /*texture*/ ) {
  273. //console.warn( 'Abstract class.' );
  274. }
  275. destroySampler() {}
  276. // node builder
  277. createNodeBuilder( object, renderer, scene = null ) {
  278. return new GLSLNodeBuilder( object, renderer, scene );
  279. }
  280. // program
  281. createProgram( program ) {
  282. const gl = this.gl;
  283. const { stage, code } = program;
  284. const shader = stage === 'vertex' ? gl.createShader( gl.VERTEX_SHADER ) : gl.createShader( gl.FRAGMENT_SHADER );
  285. gl.shaderSource( shader, code );
  286. gl.compileShader( shader );
  287. this.set( program, {
  288. shaderGPU: shader
  289. } );
  290. }
  291. destroyProgram( /*program*/ ) {
  292. console.warn( 'Abstract class.' );
  293. }
  294. createRenderPipeline( renderObject ) {
  295. const gl = this.gl;
  296. const pipeline = renderObject.pipeline;
  297. // Program
  298. const { fragmentProgram, vertexProgram } = pipeline;
  299. const programGPU = gl.createProgram();
  300. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  301. const vertexShader = this.get( vertexProgram ).shaderGPU;
  302. gl.attachShader( programGPU, fragmentShader );
  303. gl.attachShader( programGPU, vertexShader );
  304. gl.linkProgram( programGPU );
  305. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  306. console.error( 'THREE.WebGLBackend:', gl.getProgramInfoLog( programGPU ) );
  307. console.error( 'THREE.WebGLBackend:', gl.getShaderInfoLog( fragmentShader ) );
  308. console.error( 'THREE.WebGLBackend:', gl.getShaderInfoLog( vertexShader ) );
  309. }
  310. gl.useProgram( programGPU );
  311. // Bindings
  312. const bindings = renderObject.getBindings();
  313. for ( const binding of bindings ) {
  314. const bindingData = this.get( binding );
  315. const index = bindingData.index;
  316. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  317. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  318. gl.uniformBlockBinding( programGPU, location, index );
  319. } else if ( binding.isSampledTexture ) {
  320. const location = gl.getUniformLocation( programGPU, binding.name );
  321. gl.uniform1i( location, index );
  322. }
  323. }
  324. // VAO
  325. const vaoGPU = gl.createVertexArray();
  326. const index = renderObject.getIndex();
  327. const attributes = renderObject.getAttributes();
  328. gl.bindVertexArray( vaoGPU );
  329. if ( index !== null ) {
  330. const indexData = this.get( index );
  331. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  332. }
  333. for ( let i = 0; i < attributes.length; i ++ ) {
  334. const attribute = attributes[ i ];
  335. const attributeData = this.get( attribute );
  336. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  337. gl.enableVertexAttribArray( i );
  338. let stride, offset;
  339. if ( attribute.isInterleavedBufferAttribute === true ) {
  340. stride = attribute.data.stride * attributeData.bytesPerElement;
  341. offset = attribute.offset * attributeData.bytesPerElement;
  342. } else {
  343. stride = 0;
  344. offset = 0;
  345. }
  346. if ( attributeData.isInteger ) {
  347. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  348. } else {
  349. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  350. }
  351. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  352. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  353. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  354. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  355. }
  356. }
  357. gl.bindVertexArray( null );
  358. //
  359. this.set( pipeline, {
  360. programGPU,
  361. vaoGPU
  362. } );
  363. }
  364. createComputePipeline( /*computePipeline, bindings*/ ) {
  365. console.warn( 'Abstract class.' );
  366. }
  367. createBindings( bindings ) {
  368. this.updateBindings( bindings );
  369. }
  370. updateBindings( bindings ) {
  371. const { gl } = this;
  372. let groupIndex = 0;
  373. let textureIndex = 0;
  374. for ( const binding of bindings ) {
  375. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  376. const bufferGPU = gl.createBuffer();
  377. const data = binding.buffer;
  378. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  379. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  380. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  381. this.set( binding, {
  382. index: groupIndex ++,
  383. bufferGPU
  384. } );
  385. } else if ( binding.isSampledTexture ) {
  386. const { textureGPU, glTextureType } = this.get( binding.texture );
  387. this.set( binding, {
  388. index: textureIndex ++,
  389. textureGPU,
  390. glTextureType
  391. } );
  392. }
  393. }
  394. }
  395. updateBinding( binding ) {
  396. const gl = this.gl;
  397. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  398. const bindingData = this.get( binding );
  399. const bufferGPU = bindingData.bufferGPU;
  400. const data = binding.buffer;
  401. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  402. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  403. }
  404. }
  405. // attributes
  406. createIndexAttribute( attribute ) {
  407. const gl = this.gl;
  408. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  409. }
  410. createAttribute( attribute ) {
  411. const gl = this.gl;
  412. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  413. }
  414. createStorageAttribute( /*attribute*/ ) {
  415. console.warn( 'Abstract class.' );
  416. }
  417. updateAttribute( attribute ) {
  418. this.attributeUtils.updateAttribute( attribute );
  419. }
  420. destroyAttribute( /*attribute*/ ) {
  421. console.warn( 'Abstract class.' );
  422. }
  423. updateSize() {
  424. //console.warn( 'Abstract class.' );
  425. }
  426. hasFeature( name ) {
  427. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  428. const extensions = this.extensions;
  429. for ( let i = 0; i < keysMatching.length; i ++ ) {
  430. if ( extensions.has( keysMatching[ i ] ) ) return true;
  431. }
  432. return false;
  433. }
  434. getMaxAnisotropy() {
  435. return this.capabilities.getMaxAnisotropy();
  436. }
  437. copyFramebufferToTexture( texture, renderContext ) {
  438. const { gl } = this;
  439. const { textureGPU } = this.get( texture );
  440. const width = texture.image.width;
  441. const height = texture.image.height;
  442. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  443. if ( texture.isDepthTexture ) {
  444. const fb = gl.createFramebuffer();
  445. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  446. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, textureGPU, 0 );
  447. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, gl.DEPTH_BUFFER_BIT, gl.NEAREST );
  448. gl.deleteFramebuffer( fb );
  449. } else {
  450. gl.bindTexture( gl.TEXTURE_2D, textureGPU );
  451. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, 0, 0, width, height );
  452. gl.bindTexture( gl.TEXTURE_2D, null );
  453. }
  454. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  455. this._setFramebuffer( renderContext );
  456. }
  457. _setFramebuffer( renderContext ) {
  458. const { gl } = this;
  459. if ( renderContext.textures !== null ) {
  460. const renderContextData = this.get( renderContext.renderTarget );
  461. let fb = renderContextData.framebuffer;
  462. if ( fb === undefined ) {
  463. fb = gl.createFramebuffer();
  464. gl.bindFramebuffer( gl.FRAMEBUFFER, fb );
  465. const textures = renderContext.textures;
  466. const drawBuffers = [];
  467. for ( let i = 0; i < textures.length; i ++ ) {
  468. const texture = textures[ i ];
  469. const { textureGPU } = this.get( texture );
  470. const attachment = gl.COLOR_ATTACHMENT0 + i;
  471. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  472. drawBuffers.push( attachment );
  473. }
  474. gl.drawBuffers( drawBuffers );
  475. if ( renderContext.depthTexture !== null ) {
  476. const { textureGPU } = this.get( renderContext.depthTexture );
  477. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, textureGPU, 0 );
  478. }
  479. renderContextData.framebuffer = fb;
  480. } else {
  481. gl.bindFramebuffer( gl.FRAMEBUFFER, fb );
  482. }
  483. } else {
  484. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  485. }
  486. }
  487. }
  488. export default WebGLBackend;