WebGPUBackend.js 28 KB

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