WebGPUBackend.js 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  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. return adapter.features.has( name );
  634. }
  635. copyFramebufferToTexture( texture, renderContext ) {
  636. const renderContextData = this.get( renderContext );
  637. const { encoder, descriptor } = renderContextData;
  638. let sourceGPU = null;
  639. if ( texture.isFramebufferTexture ) {
  640. sourceGPU = this.context.getCurrentTexture();
  641. } else if ( texture.isDepthTexture ) {
  642. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  643. }
  644. const destinationGPU = this.get( texture ).texture;
  645. renderContextData.currentPass.end();
  646. encoder.copyTextureToTexture(
  647. {
  648. texture: sourceGPU,
  649. origin: { x: 0, y: 0, z: 0 }
  650. },
  651. {
  652. texture: destinationGPU
  653. },
  654. [
  655. texture.image.width,
  656. texture.image.height
  657. ]
  658. );
  659. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  660. descriptor.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  661. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  662. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  663. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  664. renderContextData.currentSets = { attributes: {} };
  665. }
  666. }
  667. export default WebGPUBackend;