WebGPUBackend.js 32 KB

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