WebGPUBackend.js 31 KB

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