WebGPUBackend.js 29 KB

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