WebGPUBackend.js 32 KB

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