WebGPUBackend.js 27 KB

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