WebGPUBackend.js 23 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  1. /*// debugger tools
  2. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  3. //*/
  4. import { GPUFeatureName, GPUTextureFormat, GPULoadOp, GPUStoreOp, GPUIndexFormat, GPUTextureViewDimension } from './utils/WebGPUConstants.js';
  5. import WGSLNodeBuilder from './nodes/WGSLNodeBuilder.js';
  6. import Backend from '../common/Backend.js';
  7. import { DepthTexture, DepthFormat, DepthStencilFormat, UnsignedInt248Type, UnsignedIntType, WebGPUCoordinateSystem } from 'three';
  8. import WebGPUUtils from './utils/WebGPUUtils.js';
  9. import WebGPUAttributeUtils from './utils/WebGPUAttributeUtils.js';
  10. import WebGPUBindingUtils from './utils/WebGPUBindingUtils.js';
  11. import WebGPUPipelineUtils from './utils/WebGPUPipelineUtils.js';
  12. import WebGPUTextureUtils from './utils/WebGPUTextureUtils.js';
  13. // statics
  14. let _staticAdapter = null;
  15. if ( navigator.gpu !== undefined ) {
  16. _staticAdapter = await navigator.gpu.requestAdapter();
  17. }
  18. //
  19. class WebGPUBackend extends Backend {
  20. constructor( parameters = {} ) {
  21. super( parameters );
  22. // some parameters require default values other than "undefined"
  23. this.parameters.antialias = ( parameters.antialias === true );
  24. if ( this.parameters.antialias === true ) {
  25. this.parameters.sampleCount = ( parameters.sampleCount === undefined ) ? 4 : parameters.sampleCount;
  26. } else {
  27. this.parameters.sampleCount = 1;
  28. }
  29. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  30. this.adapter = null;
  31. this.device = null;
  32. this.context = null;
  33. this.colorBuffer = null;
  34. this.defaultDepthTexture = new DepthTexture();
  35. this.defaultDepthTexture.name = 'depthBuffer';
  36. this.utils = new WebGPUUtils( this );
  37. this.attributeUtils = new WebGPUAttributeUtils( this );
  38. this.bindingUtils = new WebGPUBindingUtils( this );
  39. this.pipelineUtils = new WebGPUPipelineUtils( this );
  40. this.textureUtils = new WebGPUTextureUtils( this );
  41. this.occludedResolveCache = new Map();
  42. }
  43. async init( renderer ) {
  44. await super.init( renderer );
  45. //
  46. const parameters = this.parameters;
  47. const adapterOptions = {
  48. powerPreference: parameters.powerPreference
  49. };
  50. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  51. if ( adapter === null ) {
  52. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  53. }
  54. // feature support
  55. const features = Object.values( GPUFeatureName );
  56. const supportedFeatures = [];
  57. for ( const name of features ) {
  58. if ( adapter.features.has( name ) ) {
  59. supportedFeatures.push( name );
  60. }
  61. }
  62. const deviceDescriptor = {
  63. requiredFeatures: supportedFeatures,
  64. requiredLimits: parameters.requiredLimits
  65. };
  66. const device = await adapter.requestDevice( deviceDescriptor );
  67. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  68. this.adapter = adapter;
  69. this.device = device;
  70. this.context = context;
  71. this.updateSize();
  72. }
  73. get coordinateSystem() {
  74. return WebGPUCoordinateSystem;
  75. }
  76. async getArrayBufferAsync( attribute ) {
  77. return await this.attributeUtils.getArrayBufferAsync( attribute );
  78. }
  79. beginRender( renderContext ) {
  80. const renderContextData = this.get( renderContext );
  81. const device = this.device;
  82. const occlusionQueryCount = renderContext.occlusionQueryCount;
  83. let occlusionQuerySet;
  84. if ( occlusionQueryCount > 0 ) {
  85. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  86. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  87. // Get a reference to the array of objects with queries. The renderContextData property
  88. // can be changed by another render pass before the buffer.mapAsyc() completes.
  89. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  90. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  91. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  92. //
  93. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  94. renderContextData.occlusionQuerySet = occlusionQuerySet;
  95. renderContextData.occlusionQueryIndex = 0;
  96. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  97. renderContextData.lastOcclusionObject = null;
  98. }
  99. const descriptor = {
  100. colorAttachments: [ {
  101. view: null
  102. } ],
  103. depthStencilAttachment: {
  104. view: null
  105. },
  106. occlusionQuerySet
  107. };
  108. const colorAttachment = descriptor.colorAttachments[ 0 ];
  109. const depthStencilAttachment = descriptor.depthStencilAttachment;
  110. const antialias = this.parameters.antialias;
  111. if ( renderContext.texture !== null ) {
  112. const textureData = this.get( renderContext.texture );
  113. const depthTextureData = this.get( renderContext.depthTexture );
  114. const view = textureData.texture.createView( {
  115. baseMipLevel: 0,
  116. mipLevelCount: 1,
  117. baseArrayLayer: renderContext.activeCubeFace,
  118. dimension: GPUTextureViewDimension.TwoD
  119. } );
  120. if ( textureData.msaaTexture !== undefined ) {
  121. colorAttachment.view = textureData.msaaTexture.createView();
  122. colorAttachment.resolveTarget = view;
  123. } else {
  124. colorAttachment.view = view;
  125. colorAttachment.resolveTarget = undefined;
  126. }
  127. depthStencilAttachment.view = depthTextureData.texture.createView();
  128. if ( renderContext.stencil && renderContext.depthTexture.format === DepthFormat ) {
  129. renderContext.stencil = false;
  130. }
  131. } else {
  132. if ( antialias === true ) {
  133. colorAttachment.view = this.colorBuffer.createView();
  134. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  135. } else {
  136. colorAttachment.view = this.context.getCurrentTexture().createView();
  137. colorAttachment.resolveTarget = undefined;
  138. }
  139. depthStencilAttachment.view = this._getDepthBufferGPU( renderContext ).createView();
  140. }
  141. if ( renderContext.clearColor ) {
  142. colorAttachment.clearValue = renderContext.clearColorValue;
  143. colorAttachment.loadOp = GPULoadOp.Clear;
  144. colorAttachment.storeOp = GPUStoreOp.Store;
  145. } else {
  146. colorAttachment.loadOp = GPULoadOp.Load;
  147. colorAttachment.storeOp = GPUStoreOp.Store;
  148. }
  149. //
  150. if ( renderContext.depth ) {
  151. if ( renderContext.clearDepth ) {
  152. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  153. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  154. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  155. } else {
  156. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  157. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  158. }
  159. }
  160. if ( renderContext.stencil ) {
  161. if ( renderContext.clearStencil ) {
  162. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  163. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  164. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  165. } else {
  166. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  167. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  168. }
  169. }
  170. //
  171. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  172. const currentPass = encoder.beginRenderPass( descriptor );
  173. //
  174. renderContextData.descriptor = descriptor;
  175. renderContextData.encoder = encoder;
  176. renderContextData.currentPass = currentPass;
  177. renderContextData.currentSets = { attributes: {} };
  178. //
  179. if ( renderContext.viewport ) {
  180. this.updateViewport( renderContext );
  181. }
  182. if ( renderContext.scissor ) {
  183. const { x, y, width, height } = renderContext.scissorValue;
  184. currentPass.setScissorRect( x, y, width, height );
  185. }
  186. }
  187. finishRender( renderContext ) {
  188. const renderContextData = this.get( renderContext );
  189. const occlusionQueryCount = renderContext.occlusionQueryCount;
  190. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  191. renderContextData.currentPass.endOcclusionQuery();
  192. }
  193. renderContextData.currentPass.end();
  194. if ( occlusionQueryCount > 0 ) {
  195. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  196. //
  197. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  198. if ( queryResolveBuffer === undefined ) {
  199. queryResolveBuffer = this.device.createBuffer(
  200. {
  201. size: bufferSize,
  202. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  203. }
  204. );
  205. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  206. }
  207. //
  208. const readBuffer = this.device.createBuffer(
  209. {
  210. size: bufferSize,
  211. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  212. }
  213. );
  214. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  215. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  216. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  217. renderContextData.occlusionQueryBuffer = readBuffer;
  218. //
  219. this.resolveOccludedAsync( renderContext );
  220. }
  221. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  222. //
  223. if ( renderContext.texture !== null && renderContext.texture.generateMipmaps === true ) {
  224. this.textureUtils.generateMipmaps( renderContext.texture );
  225. }
  226. }
  227. isOccluded( renderContext, object ) {
  228. const renderContextData = this.get( renderContext );
  229. return renderContextData.occluded && renderContextData.occluded.has( object );
  230. }
  231. async resolveOccludedAsync( renderContext ) {
  232. const renderContextData = this.get( renderContext );
  233. // handle occlusion query results
  234. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  235. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  236. const occluded = new WeakSet();
  237. renderContextData.currentOcclusionQueryObjects = null;
  238. renderContextData.currentOcclusionQueryBuffer = null;
  239. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  240. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  241. const results = new BigUint64Array( buffer );
  242. for ( let i = 0; i < currentOcclusionQueryObjects.length; i++ ) {
  243. if ( results[ i ] !== 0n ) {
  244. occluded.add( currentOcclusionQueryObjects[ i ], true );
  245. }
  246. }
  247. currentOcclusionQueryBuffer.destroy();
  248. renderContextData.occluded = occluded;
  249. }
  250. }
  251. updateViewport( renderContext ) {
  252. const { currentPass } = this.get( renderContext );
  253. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  254. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  255. }
  256. clear( renderContext, color, depth, stencil ) {
  257. const device = this.device;
  258. const renderContextData = this.get( renderContext );
  259. const { descriptor } = renderContextData;
  260. depth = depth && renderContext.depth;
  261. stencil = stencil && renderContext.stencil;
  262. const colorAttachment = descriptor.colorAttachments[ 0 ];
  263. const depthStencilAttachment = descriptor.depthStencilAttachment;
  264. const antialias = this.parameters.antialias;
  265. // @TODO: Include render target in clear operation.
  266. if ( antialias === true ) {
  267. colorAttachment.view = this.colorBuffer.createView();
  268. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  269. } else {
  270. colorAttachment.view = this.context.getCurrentTexture().createView();
  271. colorAttachment.resolveTarget = undefined;
  272. }
  273. descriptor.depthStencilAttachment.view = this._getDepthBufferGPU( renderContext ).createView();
  274. if ( color ) {
  275. colorAttachment.loadOp = GPULoadOp.Clear;
  276. colorAttachment.clearValue = renderContext.clearColorValue;
  277. } else {
  278. colorAttachment.loadOp = GPULoadOp.Load;
  279. }
  280. if ( depth ) {
  281. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  282. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  283. } else {
  284. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  285. }
  286. if ( stencil ) {
  287. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  288. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  289. } else {
  290. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  291. }
  292. renderContextData.encoder = device.createCommandEncoder( {} );
  293. renderContextData.currentPass = renderContextData.encoder.beginRenderPass( descriptor );
  294. renderContextData.currentPass.end();
  295. device.queue.submit( [ renderContextData.encoder.finish() ] );
  296. }
  297. // compute
  298. beginCompute( computeGroup ) {
  299. const groupGPU = this.get( computeGroup );
  300. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( {} );
  301. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass();
  302. }
  303. compute( computeGroup, computeNode, bindings, pipeline ) {
  304. const { passEncoderGPU } = this.get( computeGroup );
  305. // pipeline
  306. const pipelineGPU = this.get( pipeline ).pipeline;
  307. passEncoderGPU.setPipeline( pipelineGPU );
  308. // bind group
  309. const bindGroupGPU = this.get( bindings ).group;
  310. passEncoderGPU.setBindGroup( 0, bindGroupGPU );
  311. passEncoderGPU.dispatchWorkgroups( computeNode.dispatchCount );
  312. }
  313. finishCompute( computeGroup ) {
  314. const groupData = this.get( computeGroup );
  315. groupData.passEncoderGPU.end();
  316. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  317. }
  318. // render object
  319. draw( renderObject, info ) {
  320. const { object, geometry, context, pipeline } = renderObject;
  321. const bindingsData = this.get( renderObject.getBindings() );
  322. const contextData = this.get( context );
  323. const pipelineGPU = this.get( pipeline ).pipeline;
  324. const currentSets = contextData.currentSets;
  325. // pipeline
  326. const passEncoderGPU = contextData.currentPass;
  327. if ( currentSets.pipeline !== pipelineGPU ) {
  328. passEncoderGPU.setPipeline( pipelineGPU );
  329. currentSets.pipeline = pipelineGPU;
  330. }
  331. // bind group
  332. const bindGroupGPU = bindingsData.group;
  333. passEncoderGPU.setBindGroup( 0, bindGroupGPU );
  334. // attributes
  335. const index = renderObject.getIndex();
  336. const hasIndex = ( index !== null );
  337. // index
  338. if ( hasIndex === true ) {
  339. if ( currentSets.index !== index ) {
  340. const buffer = this.get( index ).buffer;
  341. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  342. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  343. currentSets.index = index;
  344. }
  345. }
  346. // vertex buffers
  347. const vertexBuffers = renderObject.getVertexBuffers();
  348. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  349. const vertexBuffer = vertexBuffers[ i ];
  350. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  351. const buffer = this.get( vertexBuffer ).buffer;
  352. passEncoderGPU.setVertexBuffer( i, buffer );
  353. currentSets.attributes[ i ] = vertexBuffer;
  354. }
  355. }
  356. // occlusion queries - handle multiple consecutive draw calls for an object
  357. if ( contextData.occlusionQuerySet !== undefined ) {
  358. const lastObject = contextData.lastOcclusionObject;
  359. if ( lastObject !== object ) {
  360. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  361. passEncoderGPU.endOcclusionQuery();
  362. contextData.occlusionQueryIndex ++;
  363. }
  364. if ( object.occlusionTest === true ) {
  365. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  366. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  367. }
  368. contextData.lastOcclusionObject = object;
  369. }
  370. }
  371. // draw
  372. const drawRange = geometry.drawRange;
  373. const firstVertex = drawRange.start;
  374. const instanceCount = this.getInstanceCount( renderObject );
  375. if ( hasIndex === true ) {
  376. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  377. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  378. info.update( object, indexCount, instanceCount );
  379. } else {
  380. const positionAttribute = geometry.attributes.position;
  381. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  382. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  383. info.update( object, vertexCount, instanceCount );
  384. }
  385. }
  386. // cache key
  387. needsUpdate( renderObject ) {
  388. const renderObjectGPU = this.get( renderObject );
  389. const { object, material } = renderObject;
  390. const utils = this.utils;
  391. const sampleCount = utils.getSampleCount( renderObject.context );
  392. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  393. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  394. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  395. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  396. let needsUpdate = false;
  397. if ( renderObjectGPU.sampleCount !== sampleCount || renderObjectGPU.colorSpace !== colorSpace ||
  398. renderObjectGPU.colorFormat !== colorFormat || renderObjectGPU.depthStencilFormat !== depthStencilFormat ||
  399. renderObjectGPU.primitiveTopology !== primitiveTopology ) {
  400. renderObjectGPU.sampleCount = sampleCount;
  401. renderObjectGPU.colorSpace = colorSpace;
  402. renderObjectGPU.colorFormat = colorFormat;
  403. renderObjectGPU.depthStencilFormat = depthStencilFormat;
  404. renderObjectGPU.primitiveTopology = primitiveTopology;
  405. needsUpdate = true;
  406. }
  407. return needsUpdate;
  408. }
  409. getCacheKey( renderObject ) {
  410. const { object, material } = renderObject;
  411. const utils = this.utils;
  412. const renderContext = renderObject.context;
  413. return [
  414. utils.getSampleCount( renderContext ),
  415. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  416. utils.getPrimitiveTopology( object, material )
  417. ].join();
  418. }
  419. // textures
  420. createSampler( texture ) {
  421. this.textureUtils.createSampler( texture );
  422. }
  423. destroySampler( texture ) {
  424. this.textureUtils.destroySampler( texture );
  425. }
  426. createDefaultTexture( texture ) {
  427. this.textureUtils.createDefaultTexture( texture );
  428. }
  429. createTexture( texture, options ) {
  430. this.textureUtils.createTexture( texture, options );
  431. }
  432. updateTexture( texture, options ) {
  433. this.textureUtils.updateTexture( texture, options );
  434. }
  435. generateMipmaps( texture ) {
  436. this.textureUtils.generateMipmaps( texture );
  437. }
  438. destroyTexture( texture ) {
  439. this.textureUtils.destroyTexture( texture );
  440. }
  441. copyTextureToBuffer( texture, x, y, width, height ) {
  442. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  443. }
  444. // node builder
  445. createNodeBuilder( object, renderer, scene = null ) {
  446. return new WGSLNodeBuilder( object, renderer, scene );
  447. }
  448. // program
  449. createProgram( program ) {
  450. const programGPU = this.get( program );
  451. programGPU.module = {
  452. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  453. entryPoint: 'main'
  454. };
  455. }
  456. destroyProgram( program ) {
  457. this.delete( program );
  458. }
  459. // pipelines
  460. createRenderPipeline( renderObject ) {
  461. this.pipelineUtils.createRenderPipeline( renderObject );
  462. }
  463. createComputePipeline( computePipeline, bindings ) {
  464. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  465. }
  466. // bindings
  467. createBindings( bindings ) {
  468. this.bindingUtils.createBindings( bindings );
  469. }
  470. updateBindings( bindings ) {
  471. this.bindingUtils.createBindings( bindings );
  472. }
  473. updateBinding( binding ) {
  474. this.bindingUtils.updateBinding( binding );
  475. }
  476. // attributes
  477. createIndexAttribute( attribute ) {
  478. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  479. }
  480. createAttribute( attribute ) {
  481. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  482. }
  483. createStorageAttribute( attribute ) {
  484. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  485. }
  486. updateAttribute( attribute ) {
  487. this.attributeUtils.updateAttribute( attribute );
  488. }
  489. destroyAttribute( attribute ) {
  490. this.attributeUtils.destroyAttribute( attribute );
  491. }
  492. // canvas
  493. updateSize() {
  494. this._configureContext();
  495. this._setupColorBuffer();
  496. }
  497. // utils public
  498. hasFeature( name ) {
  499. const adapter = this.adapter || _staticAdapter;
  500. //
  501. const features = Object.values( GPUFeatureName );
  502. if ( features.includes( name ) === false ) {
  503. throw new Error( 'THREE.WebGPURenderer: Unknown WebGPU GPU feature: ' + name );
  504. }
  505. //
  506. return adapter.features.has( name );
  507. }
  508. copyFramebufferToTexture( texture, renderContext ) {
  509. const renderContextData = this.get( renderContext );
  510. const { encoder, descriptor } = renderContextData;
  511. let sourceGPU = null;
  512. if ( texture.isFramebufferTexture ) {
  513. sourceGPU = this.context.getCurrentTexture();
  514. } else if ( texture.isDepthTexture ) {
  515. sourceGPU = this._getDepthBufferGPU( renderContext );
  516. }
  517. const destinationGPU = this.get( texture ).texture;
  518. renderContextData.currentPass.end();
  519. encoder.copyTextureToTexture(
  520. {
  521. texture: sourceGPU,
  522. origin: { x: 0, y: 0, z: 0 }
  523. },
  524. {
  525. texture: destinationGPU
  526. },
  527. [
  528. texture.image.width,
  529. texture.image.height
  530. ]
  531. );
  532. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  533. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  534. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  535. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  536. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  537. renderContextData.currentSets = { attributes: {} };
  538. }
  539. // utils
  540. _getDepthBufferGPU( renderContext ) {
  541. const { width, height } = this.getDrawingBufferSize();
  542. const depthTexture = this.defaultDepthTexture;
  543. const depthTextureGPU = this.get( depthTexture ).texture;
  544. let format, type;
  545. if ( renderContext.stencil ) {
  546. format = DepthStencilFormat;
  547. type = UnsignedInt248Type;
  548. } else if ( renderContext.depth ) {
  549. format = DepthFormat;
  550. type = UnsignedIntType;
  551. }
  552. if ( depthTextureGPU !== undefined ) {
  553. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  554. return depthTextureGPU;
  555. }
  556. this.textureUtils.destroyTexture( depthTexture );
  557. }
  558. depthTexture.name = 'depthBuffer';
  559. depthTexture.format = format;
  560. depthTexture.type = type;
  561. depthTexture.image.width = width;
  562. depthTexture.image.height = height;
  563. this.textureUtils.createTexture( depthTexture, { sampleCount: this.parameters.sampleCount, width, height } );
  564. return this.get( depthTexture ).texture;
  565. }
  566. _configureContext() {
  567. this.context.configure( {
  568. device: this.device,
  569. format: GPUTextureFormat.BGRA8Unorm,
  570. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  571. alphaMode: 'premultiplied'
  572. } );
  573. }
  574. _setupColorBuffer() {
  575. if ( this.colorBuffer ) this.colorBuffer.destroy();
  576. const { width, height } = this.getDrawingBufferSize();
  577. //const format = navigator.gpu.getPreferredCanvasFormat(); // @TODO: Move to WebGPUUtils
  578. this.colorBuffer = this.device.createTexture( {
  579. label: 'colorBuffer',
  580. size: {
  581. width: width,
  582. height: height,
  583. depthOrArrayLayers: 1
  584. },
  585. sampleCount: this.parameters.sampleCount,
  586. format: GPUTextureFormat.BGRA8Unorm,
  587. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  588. } );
  589. }
  590. }
  591. export default WebGPUBackend;