WebGLBackend.js 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592
  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 ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  390. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  391. } else {
  392. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  393. }
  394. } else if ( instanceCount > 1 ) {
  395. renderer.renderInstances( firstVertex, count, instanceCount );
  396. } else {
  397. renderer.render( firstVertex, count );
  398. }
  399. //
  400. gl.bindVertexArray( null );
  401. }
  402. needsRenderUpdate( /*renderObject*/ ) {
  403. return false;
  404. }
  405. getRenderCacheKey( renderObject ) {
  406. return renderObject.id;
  407. }
  408. // textures
  409. createDefaultTexture( texture ) {
  410. this.textureUtils.createDefaultTexture( texture );
  411. }
  412. createTexture( texture, options ) {
  413. this.textureUtils.createTexture( texture, options );
  414. }
  415. updateTexture( texture, options ) {
  416. this.textureUtils.updateTexture( texture, options );
  417. }
  418. generateMipmaps( texture ) {
  419. this.textureUtils.generateMipmaps( texture );
  420. }
  421. destroyTexture( texture ) {
  422. this.textureUtils.destroyTexture( texture );
  423. }
  424. copyTextureToBuffer( texture, x, y, width, height ) {
  425. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  426. }
  427. createSampler( /*texture*/ ) {
  428. //console.warn( 'Abstract class.' );
  429. }
  430. destroySampler() {}
  431. // node builder
  432. createNodeBuilder( object, renderer ) {
  433. return new GLSLNodeBuilder( object, renderer );
  434. }
  435. // program
  436. createProgram( program ) {
  437. const gl = this.gl;
  438. const { stage, code } = program;
  439. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  440. gl.shaderSource( shader, code );
  441. gl.compileShader( shader );
  442. this.set( program, {
  443. shaderGPU: shader
  444. } );
  445. }
  446. destroyProgram( /*program*/ ) {
  447. console.warn( 'Abstract class.' );
  448. }
  449. createRenderPipeline( renderObject, promises ) {
  450. const gl = this.gl;
  451. const pipeline = renderObject.pipeline;
  452. // Program
  453. const { fragmentProgram, vertexProgram } = pipeline;
  454. const programGPU = gl.createProgram();
  455. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  456. const vertexShader = this.get( vertexProgram ).shaderGPU;
  457. gl.attachShader( programGPU, fragmentShader );
  458. gl.attachShader( programGPU, vertexShader );
  459. gl.linkProgram( programGPU );
  460. this.set( pipeline, {
  461. programGPU,
  462. fragmentShader,
  463. vertexShader
  464. } );
  465. if ( promises !== null && this.parallel ) {
  466. const p = new Promise( ( resolve /*, reject*/ ) => {
  467. const parallel = this.parallel;
  468. const checkStatus = () => {
  469. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  470. this._completeCompile( renderObject, pipeline );
  471. resolve();
  472. } else {
  473. requestAnimationFrame( checkStatus );
  474. }
  475. };
  476. checkStatus();
  477. } );
  478. promises.push( p );
  479. return;
  480. }
  481. this._completeCompile( renderObject, pipeline );
  482. }
  483. _handleSource( string, errorLine ) {
  484. const lines = string.split( '\n' );
  485. const lines2 = [];
  486. const from = Math.max( errorLine - 6, 0 );
  487. const to = Math.min( errorLine + 6, lines.length );
  488. for ( let i = from; i < to; i ++ ) {
  489. const line = i + 1;
  490. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  491. }
  492. return lines2.join( '\n' );
  493. }
  494. _getShaderErrors( gl, shader, type ) {
  495. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  496. const errors = gl.getShaderInfoLog( shader ).trim();
  497. if ( status && errors === '' ) return '';
  498. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  499. if ( errorMatches ) {
  500. const errorLine = parseInt( errorMatches[ 1 ] );
  501. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  502. } else {
  503. return errors;
  504. }
  505. }
  506. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  507. if ( this.renderer.debug.checkShaderErrors ) {
  508. const gl = this.gl;
  509. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  510. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  511. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  512. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  513. } else {
  514. // default error reporting
  515. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  516. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  517. console.error(
  518. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  519. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  520. 'Program Info Log: ' + programLog + '\n' +
  521. vertexErrors + '\n' +
  522. fragmentErrors
  523. );
  524. }
  525. } else if ( programLog !== '' ) {
  526. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  527. }
  528. }
  529. }
  530. _completeCompile( renderObject, pipeline ) {
  531. const gl = this.gl;
  532. const pipelineData = this.get( pipeline );
  533. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  534. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  535. this._logProgramError( programGPU, fragmentShader, vertexShader );
  536. }
  537. gl.useProgram( programGPU );
  538. // Bindings
  539. const bindings = renderObject.getBindings();
  540. this._setupBindings( bindings, programGPU );
  541. //
  542. this.set( pipeline, {
  543. programGPU
  544. } );
  545. }
  546. createComputePipeline( computePipeline, bindings ) {
  547. const gl = this.gl;
  548. // Program
  549. const fragmentProgram = {
  550. stage: 'fragment',
  551. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  552. };
  553. this.createProgram( fragmentProgram );
  554. const { computeProgram } = computePipeline;
  555. const programGPU = gl.createProgram();
  556. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  557. const vertexShader = this.get( computeProgram ).shaderGPU;
  558. const transforms = computeProgram.transforms;
  559. const transformVaryingNames = [];
  560. const transformAttributeNodes = [];
  561. for ( let i = 0; i < transforms.length; i ++ ) {
  562. const transform = transforms[ i ];
  563. transformVaryingNames.push( transform.varyingName );
  564. transformAttributeNodes.push( transform.attributeNode );
  565. }
  566. gl.attachShader( programGPU, fragmentShader );
  567. gl.attachShader( programGPU, vertexShader );
  568. gl.transformFeedbackVaryings(
  569. programGPU,
  570. transformVaryingNames,
  571. gl.SEPARATE_ATTRIBS
  572. );
  573. gl.linkProgram( programGPU );
  574. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  575. this._logProgramError( programGPU, fragmentShader, vertexShader );
  576. }
  577. gl.useProgram( programGPU );
  578. // Bindings
  579. this.createBindings( null, bindings );
  580. this._setupBindings( bindings, programGPU );
  581. const attributeNodes = computeProgram.attributes;
  582. const attributes = [];
  583. const transformBuffers = [];
  584. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  585. const attribute = attributeNodes[ i ].node.attribute;
  586. attributes.push( attribute );
  587. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  588. }
  589. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  590. const attribute = transformAttributeNodes[ i ].attribute;
  591. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  592. const attributeData = this.get( attribute );
  593. transformBuffers.push( attributeData );
  594. }
  595. //
  596. this.set( computePipeline, {
  597. programGPU,
  598. transformBuffers,
  599. attributes
  600. } );
  601. }
  602. createBindings( bindGroup, bindings ) {
  603. this.updateBindings( bindGroup, bindings );
  604. }
  605. updateBindings( bindGroup, bindings ) {
  606. const { gl } = this;
  607. let groupIndex = 0;
  608. let textureIndex = 0;
  609. for ( const bindGroup of bindings ) {
  610. for ( const binding of bindGroup.bindings ) {
  611. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  612. const bufferGPU = gl.createBuffer();
  613. const data = binding.buffer;
  614. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  615. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  616. gl.bindBufferBase( gl.UNIFORM_BUFFER, groupIndex, bufferGPU );
  617. this.set( binding, {
  618. index: groupIndex ++,
  619. bufferGPU
  620. } );
  621. } else if ( binding.isSampledTexture ) {
  622. const { textureGPU, glTextureType } = this.get( binding.texture );
  623. this.set( binding, {
  624. index: textureIndex ++,
  625. textureGPU,
  626. glTextureType
  627. } );
  628. }
  629. }
  630. }
  631. }
  632. updateBinding( binding ) {
  633. const gl = this.gl;
  634. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  635. const bindingData = this.get( binding );
  636. const bufferGPU = bindingData.bufferGPU;
  637. const data = binding.buffer;
  638. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  639. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  640. }
  641. }
  642. // attributes
  643. createIndexAttribute( attribute ) {
  644. const gl = this.gl;
  645. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  646. }
  647. createAttribute( attribute ) {
  648. if ( this.has( attribute ) ) return;
  649. const gl = this.gl;
  650. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  651. }
  652. createStorageAttribute( attribute ) {
  653. if ( this.has( attribute ) ) return;
  654. const gl = this.gl;
  655. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  656. }
  657. updateAttribute( attribute ) {
  658. this.attributeUtils.updateAttribute( attribute );
  659. }
  660. destroyAttribute( attribute ) {
  661. this.attributeUtils.destroyAttribute( attribute );
  662. }
  663. updateSize() {
  664. //console.warn( 'Abstract class.' );
  665. }
  666. hasFeature( name ) {
  667. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  668. const extensions = this.extensions;
  669. for ( let i = 0; i < keysMatching.length; i ++ ) {
  670. if ( extensions.has( keysMatching[ i ] ) ) return true;
  671. }
  672. return false;
  673. }
  674. getMaxAnisotropy() {
  675. return this.capabilities.getMaxAnisotropy();
  676. }
  677. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  678. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  679. }
  680. copyFramebufferToTexture( texture, renderContext ) {
  681. this.textureUtils.copyFramebufferToTexture( texture, renderContext );
  682. }
  683. _setFramebuffer( renderContext ) {
  684. const { gl, state } = this;
  685. let currentFrameBuffer = null;
  686. if ( renderContext.textures !== null ) {
  687. const renderTarget = renderContext.renderTarget;
  688. const renderTargetContextData = this.get( renderTarget );
  689. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  690. const cubeFace = this.renderer._activeCubeFace;
  691. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  692. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  693. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  694. let fb;
  695. if ( isCube ) {
  696. if ( renderTargetContextData.cubeFramebuffers === undefined ) {
  697. renderTargetContextData.cubeFramebuffers = [];
  698. }
  699. fb = renderTargetContextData.cubeFramebuffers[ cubeFace ];
  700. } else {
  701. fb = renderTargetContextData.framebuffer;
  702. }
  703. if ( fb === undefined ) {
  704. fb = gl.createFramebuffer();
  705. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  706. const textures = renderContext.textures;
  707. if ( isCube ) {
  708. renderTargetContextData.cubeFramebuffers[ cubeFace ] = fb;
  709. const { textureGPU } = this.get( textures[ 0 ] );
  710. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  711. } else {
  712. for ( let i = 0; i < textures.length; i ++ ) {
  713. const texture = textures[ i ];
  714. const textureData = this.get( texture );
  715. textureData.renderTarget = renderContext.renderTarget;
  716. const attachment = gl.COLOR_ATTACHMENT0 + i;
  717. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  718. }
  719. renderTargetContextData.framebuffer = fb;
  720. state.drawBuffers( renderContext, fb );
  721. }
  722. if ( renderContext.depthTexture !== null ) {
  723. const textureData = this.get( renderContext.depthTexture );
  724. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  725. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  726. }
  727. }
  728. if ( samples > 0 ) {
  729. if ( msaaFb === undefined ) {
  730. const invalidationArray = [];
  731. msaaFb = gl.createFramebuffer();
  732. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  733. const msaaRenderbuffers = [];
  734. const textures = renderContext.textures;
  735. for ( let i = 0; i < textures.length; i ++ ) {
  736. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  737. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  738. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  739. if ( depthBuffer ) {
  740. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  741. invalidationArray.push( depthStyle );
  742. }
  743. const texture = renderContext.textures[ i ];
  744. const textureData = this.get( texture );
  745. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, renderContext.width, renderContext.height );
  746. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  747. }
  748. renderTargetContextData.msaaFrameBuffer = msaaFb;
  749. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  750. if ( depthRenderbuffer === undefined ) {
  751. depthRenderbuffer = gl.createRenderbuffer();
  752. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, renderContext );
  753. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  754. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  755. invalidationArray.push( depthStyle );
  756. }
  757. renderTargetContextData.invalidationArray = invalidationArray;
  758. }
  759. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  760. } else {
  761. currentFrameBuffer = fb;
  762. }
  763. }
  764. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  765. }
  766. _getVaoKey( index, attributes ) {
  767. let key = [];
  768. if ( index !== null ) {
  769. const indexData = this.get( index );
  770. key += ':' + indexData.id;
  771. }
  772. for ( let i = 0; i < attributes.length; i ++ ) {
  773. const attributeData = this.get( attributes[ i ] );
  774. key += ':' + attributeData.id;
  775. }
  776. return key;
  777. }
  778. _createVao( index, attributes ) {
  779. const { gl } = this;
  780. const vaoGPU = gl.createVertexArray();
  781. let key = '';
  782. let staticVao = true;
  783. gl.bindVertexArray( vaoGPU );
  784. if ( index !== null ) {
  785. const indexData = this.get( index );
  786. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  787. key += ':' + indexData.id;
  788. }
  789. for ( let i = 0; i < attributes.length; i ++ ) {
  790. const attribute = attributes[ i ];
  791. const attributeData = this.get( attribute );
  792. key += ':' + attributeData.id;
  793. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  794. gl.enableVertexAttribArray( i );
  795. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  796. let stride, offset;
  797. if ( attribute.isInterleavedBufferAttribute === true ) {
  798. stride = attribute.data.stride * attributeData.bytesPerElement;
  799. offset = attribute.offset * attributeData.bytesPerElement;
  800. } else {
  801. stride = 0;
  802. offset = 0;
  803. }
  804. if ( attributeData.isInteger ) {
  805. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  806. } else {
  807. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  808. }
  809. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  810. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  811. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  812. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  813. }
  814. }
  815. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  816. this.vaoCache[ key ] = vaoGPU;
  817. return { vaoGPU, staticVao };
  818. }
  819. _getTransformFeedback( transformBuffers ) {
  820. let key = '';
  821. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  822. key += ':' + transformBuffers[ i ].id;
  823. }
  824. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  825. if ( transformFeedbackGPU !== undefined ) {
  826. return transformFeedbackGPU;
  827. }
  828. const gl = this.gl;
  829. transformFeedbackGPU = gl.createTransformFeedback();
  830. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  831. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  832. const attributeData = transformBuffers[ i ];
  833. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  834. }
  835. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  836. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  837. return transformFeedbackGPU;
  838. }
  839. _setupBindings( bindings, programGPU ) {
  840. const gl = this.gl;
  841. for ( const bindGroup of bindings ) {
  842. for ( const binding of bindGroup.bindings ) {
  843. const bindingData = this.get( binding );
  844. const index = bindingData.index;
  845. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  846. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  847. gl.uniformBlockBinding( programGPU, location, index );
  848. } else if ( binding.isSampledTexture ) {
  849. const location = gl.getUniformLocation( programGPU, binding.name );
  850. gl.uniform1i( location, index );
  851. }
  852. }
  853. }
  854. }
  855. _bindUniforms( bindings ) {
  856. const { gl, state } = this;
  857. for ( const bindGroup of bindings ) {
  858. for ( const binding of bindGroup.bindings ) {
  859. const bindingData = this.get( binding );
  860. const index = bindingData.index;
  861. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  862. gl.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  863. } else if ( binding.isSampledTexture ) {
  864. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  865. }
  866. }
  867. }
  868. }
  869. }
  870. export default WebGLBackend;