WebGPUBackend.js 27 KB

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