WebGPUBackend.js 32 KB

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