WebGPUBackend.js 27 KB

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