WebGPUBackend.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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 ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  272. renderContextData.registerBundlesPhase = false;
  273. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  274. }
  275. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  276. renderContextData.currentPass.endOcclusionQuery();
  277. }
  278. renderContextData.currentPass.end();
  279. if ( occlusionQueryCount > 0 ) {
  280. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  281. //
  282. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  283. if ( queryResolveBuffer === undefined ) {
  284. queryResolveBuffer = this.device.createBuffer(
  285. {
  286. size: bufferSize,
  287. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  288. }
  289. );
  290. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  291. }
  292. //
  293. const readBuffer = this.device.createBuffer(
  294. {
  295. size: bufferSize,
  296. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  297. }
  298. );
  299. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  300. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  301. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  302. renderContextData.occlusionQueryBuffer = readBuffer;
  303. //
  304. this.resolveOccludedAsync( renderContext );
  305. }
  306. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  307. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  308. //
  309. if ( renderContext.textures !== null ) {
  310. const textures = renderContext.textures;
  311. for ( let i = 0; i < textures.length; i ++ ) {
  312. const texture = textures[ i ];
  313. if ( texture.generateMipmaps === true ) {
  314. this.textureUtils.generateMipmaps( texture );
  315. }
  316. }
  317. }
  318. }
  319. isOccluded( renderContext, object ) {
  320. const renderContextData = this.get( renderContext );
  321. return renderContextData.occluded && renderContextData.occluded.has( object );
  322. }
  323. async resolveOccludedAsync( renderContext ) {
  324. const renderContextData = this.get( renderContext );
  325. // handle occlusion query results
  326. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  327. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  328. const occluded = new WeakSet();
  329. renderContextData.currentOcclusionQueryObjects = null;
  330. renderContextData.currentOcclusionQueryBuffer = null;
  331. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  332. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  333. const results = new BigUint64Array( buffer );
  334. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  335. if ( results[ i ] !== 0n ) {
  336. occluded.add( currentOcclusionQueryObjects[ i ] );
  337. }
  338. }
  339. currentOcclusionQueryBuffer.destroy();
  340. renderContextData.occluded = occluded;
  341. }
  342. }
  343. updateViewport( renderContext ) {
  344. const { currentPass } = this.get( renderContext );
  345. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  346. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  347. }
  348. clear( color, depth, stencil, renderTargetData = null ) {
  349. const device = this.device;
  350. const renderer = this.renderer;
  351. let colorAttachments = [];
  352. let depthStencilAttachment;
  353. let clearValue;
  354. let supportsDepth;
  355. let supportsStencil;
  356. if ( color ) {
  357. const clearColor = this.getClearColor();
  358. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  359. }
  360. if ( renderTargetData === null ) {
  361. supportsDepth = renderer.depth;
  362. supportsStencil = renderer.stencil;
  363. const descriptor = this._getDefaultRenderPassDescriptor();
  364. if ( color ) {
  365. colorAttachments = descriptor.colorAttachments;
  366. const colorAttachment = colorAttachments[ 0 ];
  367. colorAttachment.clearValue = clearValue;
  368. colorAttachment.loadOp = GPULoadOp.Clear;
  369. colorAttachment.storeOp = GPUStoreOp.Store;
  370. }
  371. if ( supportsDepth || supportsStencil ) {
  372. depthStencilAttachment = descriptor.depthStencilAttachment;
  373. }
  374. } else {
  375. supportsDepth = renderTargetData.depth;
  376. supportsStencil = renderTargetData.stencil;
  377. if ( color ) {
  378. for ( const texture of renderTargetData.textures ) {
  379. const textureData = this.get( texture );
  380. const textureView = textureData.texture.createView();
  381. let view, resolveTarget;
  382. if ( textureData.msaaTexture !== undefined ) {
  383. view = textureData.msaaTexture.createView();
  384. resolveTarget = textureView;
  385. } else {
  386. view = textureView;
  387. resolveTarget = undefined;
  388. }
  389. colorAttachments.push( {
  390. view,
  391. resolveTarget,
  392. clearValue,
  393. loadOp: GPULoadOp.Clear,
  394. storeOp: GPUStoreOp.Store
  395. } );
  396. }
  397. }
  398. if ( supportsDepth || supportsStencil ) {
  399. const depthTextureData = this.get( renderTargetData.depthTexture );
  400. depthStencilAttachment = {
  401. view: depthTextureData.texture.createView()
  402. };
  403. }
  404. }
  405. //
  406. if ( supportsDepth ) {
  407. if ( depth ) {
  408. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  409. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  410. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  411. } else {
  412. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  413. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  414. }
  415. }
  416. //
  417. if ( supportsStencil ) {
  418. if ( stencil ) {
  419. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  420. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  421. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  422. } else {
  423. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  424. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  425. }
  426. }
  427. //
  428. const encoder = device.createCommandEncoder( {} );
  429. const currentPass = encoder.beginRenderPass( {
  430. colorAttachments,
  431. depthStencilAttachment
  432. } );
  433. currentPass.end();
  434. device.queue.submit( [ encoder.finish() ] );
  435. }
  436. // compute
  437. beginCompute( computeGroup ) {
  438. const groupGPU = this.get( computeGroup );
  439. const descriptor = {};
  440. this.initTimestampQuery( computeGroup, descriptor );
  441. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  442. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  443. }
  444. compute( computeGroup, computeNode, bindings, pipeline ) {
  445. const { passEncoderGPU } = this.get( computeGroup );
  446. // pipeline
  447. const pipelineGPU = this.get( pipeline ).pipeline;
  448. passEncoderGPU.setPipeline( pipelineGPU );
  449. // bind groups
  450. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  451. const bindGroup = bindings[ i ];
  452. const bindingsData = this.get( bindGroup );
  453. passEncoderGPU.setBindGroup( i, bindingsData.group );
  454. }
  455. passEncoderGPU.dispatchWorkgroups( computeNode.dispatchCount );
  456. }
  457. finishCompute( computeGroup ) {
  458. const groupData = this.get( computeGroup );
  459. groupData.passEncoderGPU.end();
  460. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  461. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  462. }
  463. // render object
  464. draw( renderObject, info ) {
  465. const { object, geometry, context, pipeline } = renderObject;
  466. const bindings = renderObject.getBindings();
  467. const contextData = this.get( context );
  468. const pipelineGPU = this.get( pipeline ).pipeline;
  469. const currentSets = contextData.currentSets;
  470. const renderObjectData = this.get( renderObject );
  471. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  472. const renderContextData = this.get( context );
  473. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  474. renderContextData.renderBundles.push( renderBundle );
  475. return;
  476. }
  477. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  478. // pipeline
  479. if ( currentSets.pipeline !== pipelineGPU ) {
  480. passEncoderGPU.setPipeline( pipelineGPU );
  481. currentSets.pipeline = pipelineGPU;
  482. }
  483. // bind groups
  484. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  485. const bindGroup = bindings[ i ];
  486. const bindingsData = this.get( bindGroup );
  487. passEncoderGPU.setBindGroup( i, bindingsData.group );
  488. }
  489. // attributes
  490. const index = renderObject.getIndex();
  491. const hasIndex = ( index !== null );
  492. // index
  493. if ( hasIndex === true ) {
  494. if ( currentSets.index !== index ) {
  495. const buffer = this.get( index ).buffer;
  496. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  497. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  498. currentSets.index = index;
  499. }
  500. }
  501. // vertex buffers
  502. const vertexBuffers = renderObject.getVertexBuffers();
  503. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  504. const vertexBuffer = vertexBuffers[ i ];
  505. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  506. const buffer = this.get( vertexBuffer ).buffer;
  507. passEncoderGPU.setVertexBuffer( i, buffer );
  508. currentSets.attributes[ i ] = vertexBuffer;
  509. }
  510. }
  511. // occlusion queries - handle multiple consecutive draw calls for an object
  512. if ( contextData.occlusionQuerySet !== undefined ) {
  513. const lastObject = contextData.lastOcclusionObject;
  514. if ( lastObject !== object ) {
  515. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  516. passEncoderGPU.endOcclusionQuery();
  517. contextData.occlusionQueryIndex ++;
  518. }
  519. if ( object.occlusionTest === true ) {
  520. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  521. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  522. }
  523. contextData.lastOcclusionObject = object;
  524. }
  525. }
  526. // draw
  527. const drawRange = renderObject.drawRange;
  528. const firstVertex = drawRange.start;
  529. const instanceCount = this.getInstanceCount( renderObject );
  530. if ( instanceCount === 0 ) return;
  531. if ( object.isBatchedMesh === true ) {
  532. const starts = object._multiDrawStarts;
  533. const counts = object._multiDrawCounts;
  534. const drawCount = object._multiDrawCount;
  535. const drawInstances = object._multiDrawInstances;
  536. const bytesPerElement = index.bytesPerElement || 1;
  537. for ( let i = 0; i < drawCount; i ++ ) {
  538. const count = drawInstances ? drawInstances[ i ] : 1;
  539. const firstInstance = count > 1 ? 0 : i;
  540. passEncoderGPU.drawIndexed( counts[ i ] / bytesPerElement, count, starts[ i ] / 4, 0, firstInstance );
  541. }
  542. } else if ( hasIndex === true ) {
  543. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  544. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  545. info.update( object, indexCount, instanceCount );
  546. } else {
  547. const positionAttribute = geometry.attributes.position;
  548. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  549. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  550. info.update( object, vertexCount, instanceCount );
  551. }
  552. if ( this.renderer._currentRenderBundle ) {
  553. const renderBundle = passEncoderGPU.finish();
  554. renderObjectData.lastPipelineGPU = pipelineGPU;
  555. renderObjectData.renderBundle = renderBundle;
  556. renderObjectData.bundleEncoder = passEncoderGPU;
  557. }
  558. }
  559. // cache key
  560. needsRenderUpdate( renderObject ) {
  561. const data = this.get( renderObject );
  562. const { object, material } = renderObject;
  563. const utils = this.utils;
  564. const sampleCount = utils.getSampleCount( renderObject.context );
  565. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  566. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  567. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  568. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  569. let needsUpdate = false;
  570. if ( data.material !== material || data.materialVersion !== material.version ||
  571. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  572. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  573. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  574. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  575. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  576. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  577. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  578. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  579. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  580. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  581. data.primitiveTopology !== primitiveTopology ||
  582. data.clippingContextVersion !== renderObject.clippingContextVersion
  583. ) {
  584. data.material = material; data.materialVersion = material.version;
  585. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  586. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  587. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  588. data.colorWrite = material.colorWrite;
  589. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  590. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  591. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  592. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  593. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  594. data.sampleCount = sampleCount;
  595. data.colorSpace = colorSpace;
  596. data.colorFormat = colorFormat;
  597. data.depthStencilFormat = depthStencilFormat;
  598. data.primitiveTopology = primitiveTopology;
  599. data.clippingContextVersion = renderObject.clippingContextVersion;
  600. needsUpdate = true;
  601. }
  602. return needsUpdate;
  603. }
  604. getRenderCacheKey( renderObject ) {
  605. const { object, material } = renderObject;
  606. const utils = this.utils;
  607. const renderContext = renderObject.context;
  608. return [
  609. material.transparent, material.blending, material.premultipliedAlpha,
  610. material.blendSrc, material.blendDst, material.blendEquation,
  611. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  612. material.colorWrite,
  613. material.depthWrite, material.depthTest, material.depthFunc,
  614. material.stencilWrite, material.stencilFunc,
  615. material.stencilFail, material.stencilZFail, material.stencilZPass,
  616. material.stencilFuncMask, material.stencilWriteMask,
  617. material.side,
  618. utils.getSampleCount( renderContext ),
  619. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  620. utils.getPrimitiveTopology( object, material ),
  621. renderObject.clippingContextVersion
  622. ].join();
  623. }
  624. // textures
  625. createSampler( texture ) {
  626. this.textureUtils.createSampler( texture );
  627. }
  628. destroySampler( texture ) {
  629. this.textureUtils.destroySampler( texture );
  630. }
  631. createDefaultTexture( texture ) {
  632. this.textureUtils.createDefaultTexture( texture );
  633. }
  634. createTexture( texture, options ) {
  635. this.textureUtils.createTexture( texture, options );
  636. }
  637. updateTexture( texture, options ) {
  638. this.textureUtils.updateTexture( texture, options );
  639. }
  640. generateMipmaps( texture ) {
  641. this.textureUtils.generateMipmaps( texture );
  642. }
  643. destroyTexture( texture ) {
  644. this.textureUtils.destroyTexture( texture );
  645. }
  646. copyTextureToBuffer( texture, x, y, width, height ) {
  647. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  648. }
  649. initTimestampQuery( renderContext, descriptor ) {
  650. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  651. const renderContextData = this.get( renderContext );
  652. if ( ! renderContextData.timeStampQuerySet ) {
  653. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  654. // beginning and one for the end of compute pass execution.
  655. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  656. const timestampWrites = {
  657. querySet: timeStampQuerySet,
  658. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  659. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  660. };
  661. Object.assign( descriptor, {
  662. timestampWrites,
  663. } );
  664. renderContextData.timeStampQuerySet = timeStampQuerySet;
  665. }
  666. }
  667. // timestamp utils
  668. prepareTimestampBuffer( renderContext, encoder ) {
  669. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  670. const renderContextData = this.get( renderContext );
  671. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  672. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  673. renderContextData.currentTimestampQueryBuffers = {
  674. resolveBuffer: this.device.createBuffer({
  675. label: 'timestamp resolve buffer',
  676. size: size,
  677. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  678. }),
  679. resultBuffer: this.device.createBuffer({
  680. label: 'timestamp result buffer',
  681. size: size,
  682. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  683. }),
  684. isMappingPending: false,
  685. }
  686. }
  687. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers
  688. if ( isMappingPending === true ) return;
  689. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  690. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  691. }
  692. async resolveTimestampAsync( renderContext, type = 'render' ) {
  693. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  694. const renderContextData = this.get(renderContext);
  695. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  696. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  697. if ( isMappingPending === true ) return;
  698. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  699. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  700. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  701. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  702. this.renderer.info.updateTimestamp( type, duration );
  703. resultBuffer.unmap();
  704. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  705. })
  706. }
  707. // node builder
  708. createNodeBuilder( object, renderer ) {
  709. return new WGSLNodeBuilder( object, renderer );
  710. }
  711. // program
  712. createProgram( program ) {
  713. const programGPU = this.get( program );
  714. programGPU.module = {
  715. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  716. entryPoint: 'main'
  717. };
  718. }
  719. destroyProgram( program ) {
  720. this.delete( program );
  721. }
  722. // pipelines
  723. createRenderPipeline( renderObject, promises ) {
  724. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  725. }
  726. createComputePipeline( computePipeline, bindings ) {
  727. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  728. }
  729. createBundleEncoder( renderContext, renderObject ) {
  730. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  731. }
  732. // bindings
  733. createBindings( bindGroup ) {
  734. this.bindingUtils.createBindings( bindGroup );
  735. }
  736. updateBindings( bindGroup ) {
  737. this.bindingUtils.createBindings( bindGroup );
  738. }
  739. updateBinding( binding ) {
  740. this.bindingUtils.updateBinding( binding );
  741. }
  742. // attributes
  743. createIndexAttribute( attribute ) {
  744. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  745. }
  746. createAttribute( attribute ) {
  747. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  748. }
  749. createStorageAttribute( attribute ) {
  750. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  751. }
  752. updateAttribute( attribute ) {
  753. this.attributeUtils.updateAttribute( attribute );
  754. }
  755. destroyAttribute( attribute ) {
  756. this.attributeUtils.destroyAttribute( attribute );
  757. }
  758. // canvas
  759. updateSize() {
  760. this.colorBuffer = this.textureUtils.getColorBuffer();
  761. this.defaultRenderPassdescriptor = null;
  762. }
  763. // utils public
  764. getMaxAnisotropy() {
  765. return 16;
  766. }
  767. hasFeature( name ) {
  768. return this.device.features.has( name );
  769. }
  770. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  771. let dstX = 0;
  772. let dstY = 0;
  773. if ( dstPosition !== null ) {
  774. dstX = dstPosition.x;
  775. dstY = dstPosition.y;
  776. }
  777. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  778. const sourceGPU = this.get( srcTexture ).texture;
  779. const destinationGPU = this.get( dstTexture ).texture;
  780. encoder.copyTextureToTexture(
  781. {
  782. texture: sourceGPU,
  783. mipLevel: level,
  784. origin: { x: 0, y: 0, z: 0 }
  785. },
  786. {
  787. texture: destinationGPU,
  788. mipLevel: level,
  789. origin: { x: dstX, y: dstY, z: 0 }
  790. },
  791. [
  792. srcTexture.image.width,
  793. srcTexture.image.height
  794. ]
  795. );
  796. this.device.queue.submit( [ encoder.finish() ] );
  797. }
  798. copyFramebufferToTexture( texture, renderContext ) {
  799. const renderContextData = this.get( renderContext );
  800. const { encoder, descriptor } = renderContextData;
  801. let sourceGPU = null;
  802. if ( renderContext.renderTarget ) {
  803. if ( texture.isDepthTexture ) {
  804. sourceGPU = this.get( renderContext.depthTexture ).texture;
  805. } else {
  806. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  807. }
  808. } else {
  809. if ( texture.isDepthTexture ) {
  810. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  811. } else {
  812. sourceGPU = this.context.getCurrentTexture();
  813. }
  814. }
  815. const destinationGPU = this.get( texture ).texture;
  816. if ( sourceGPU.format !== destinationGPU.format ) {
  817. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  818. return;
  819. }
  820. renderContextData.currentPass.end();
  821. encoder.copyTextureToTexture(
  822. {
  823. texture: sourceGPU,
  824. origin: { x: 0, y: 0, z: 0 }
  825. },
  826. {
  827. texture: destinationGPU
  828. },
  829. [
  830. texture.image.width,
  831. texture.image.height
  832. ]
  833. );
  834. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  835. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  836. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  837. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  838. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  839. renderContextData.currentSets = { attributes: {} };
  840. }
  841. }
  842. export default WebGPUBackend;