WebGPUBackend.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481
  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 { WebGPUCoordinateSystem } from '../../constants.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.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  21. this.trackTimestamp = ( parameters.trackTimestamp === true );
  22. this.device = null;
  23. this.context = null;
  24. this.colorBuffer = null;
  25. this.defaultRenderPassdescriptor = null;
  26. this.utils = new WebGPUUtils( this );
  27. this.attributeUtils = new WebGPUAttributeUtils( this );
  28. this.bindingUtils = new WebGPUBindingUtils( this );
  29. this.pipelineUtils = new WebGPUPipelineUtils( this );
  30. this.textureUtils = new WebGPUTextureUtils( this );
  31. this.occludedResolveCache = new Map();
  32. }
  33. async init( renderer ) {
  34. await super.init( renderer );
  35. //
  36. const parameters = this.parameters;
  37. // create the device if it is not passed with parameters
  38. let device;
  39. if ( parameters.device === undefined ) {
  40. const adapterOptions = {
  41. powerPreference: parameters.powerPreference
  42. };
  43. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  44. if ( adapter === null ) {
  45. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  46. }
  47. // feature support
  48. const features = Object.values( GPUFeatureName );
  49. const supportedFeatures = [];
  50. for ( const name of features ) {
  51. if ( adapter.features.has( name ) ) {
  52. supportedFeatures.push( name );
  53. }
  54. }
  55. const deviceDescriptor = {
  56. requiredFeatures: supportedFeatures,
  57. requiredLimits: parameters.requiredLimits
  58. };
  59. device = await adapter.requestDevice( deviceDescriptor );
  60. } else {
  61. device = parameters.device;
  62. }
  63. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  64. this.device = device;
  65. this.context = context;
  66. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  67. this.context.configure( {
  68. device: this.device,
  69. format: GPUTextureFormat.BGRA8Unorm,
  70. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  71. alphaMode: alphaMode
  72. } );
  73. this.updateSize();
  74. }
  75. get coordinateSystem() {
  76. return WebGPUCoordinateSystem;
  77. }
  78. async getArrayBufferAsync( attribute ) {
  79. return await this.attributeUtils.getArrayBufferAsync( attribute );
  80. }
  81. getContext() {
  82. return this.context;
  83. }
  84. _getDefaultRenderPassDescriptor() {
  85. let descriptor = this.defaultRenderPassdescriptor;
  86. if ( descriptor === null ) {
  87. const renderer = this.renderer;
  88. descriptor = {
  89. colorAttachments: [ {
  90. view: null
  91. } ],
  92. depthStencilAttachment: {
  93. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  94. }
  95. };
  96. const colorAttachment = descriptor.colorAttachments[ 0 ];
  97. if ( this.renderer.samples > 0 ) {
  98. colorAttachment.view = this.colorBuffer.createView();
  99. } else {
  100. colorAttachment.resolveTarget = undefined;
  101. }
  102. this.defaultRenderPassdescriptor = descriptor;
  103. }
  104. const colorAttachment = descriptor.colorAttachments[ 0 ];
  105. if ( this.renderer.samples > 0 ) {
  106. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  107. } else {
  108. colorAttachment.view = this.context.getCurrentTexture().createView();
  109. }
  110. return descriptor;
  111. }
  112. _getRenderPassDescriptor( renderContext ) {
  113. const renderTarget = renderContext.renderTarget;
  114. const renderTargetData = this.get( renderTarget );
  115. let descriptors = renderTargetData.descriptors;
  116. if ( descriptors === undefined ||
  117. renderTargetData.width !== renderTarget.width ||
  118. renderTargetData.height !== renderTarget.height ||
  119. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  120. renderTargetData.samples !== renderTarget.samples
  121. ) {
  122. descriptors = {};
  123. renderTargetData.descriptors = descriptors;
  124. // dispose
  125. const onDispose = () => {
  126. renderTarget.removeEventListener( 'dispose', onDispose );
  127. this.delete( renderTarget );
  128. };
  129. renderTarget.addEventListener( 'dispose', onDispose );
  130. }
  131. const cacheKey = renderContext.getCacheKey();
  132. let descriptor = descriptors[ cacheKey ];
  133. if ( descriptor === undefined ) {
  134. const textures = renderContext.textures;
  135. const colorAttachments = [];
  136. for ( let i = 0; i < textures.length; i ++ ) {
  137. const textureData = this.get( textures[ i ] );
  138. const textureView = textureData.texture.createView( {
  139. baseMipLevel: renderContext.activeMipmapLevel,
  140. mipLevelCount: 1,
  141. baseArrayLayer: renderContext.activeCubeFace,
  142. dimension: GPUTextureViewDimension.TwoD
  143. } );
  144. let view, resolveTarget;
  145. if ( textureData.msaaTexture !== undefined ) {
  146. view = textureData.msaaTexture.createView();
  147. resolveTarget = textureView;
  148. } else {
  149. view = textureView;
  150. resolveTarget = undefined;
  151. }
  152. colorAttachments.push( {
  153. view,
  154. resolveTarget,
  155. loadOp: GPULoadOp.Load,
  156. storeOp: GPUStoreOp.Store
  157. } );
  158. }
  159. const depthTextureData = this.get( renderContext.depthTexture );
  160. const depthStencilAttachment = {
  161. view: depthTextureData.texture.createView()
  162. };
  163. descriptor = {
  164. colorAttachments,
  165. depthStencilAttachment
  166. };
  167. descriptors[ cacheKey ] = 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._getDefaultRenderPassDescriptor();
  198. } else {
  199. descriptor = this._getRenderPassDescriptor( renderContext );
  200. }
  201. this.initTimestampQuery( renderContext, descriptor );
  202. descriptor.occlusionQuerySet = occlusionQuerySet;
  203. const depthStencilAttachment = descriptor.depthStencilAttachment;
  204. if ( renderContext.textures !== null ) {
  205. const colorAttachments = descriptor.colorAttachments;
  206. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  207. const colorAttachment = colorAttachments[ i ];
  208. if ( renderContext.clearColor ) {
  209. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  210. colorAttachment.loadOp = GPULoadOp.Clear;
  211. colorAttachment.storeOp = GPUStoreOp.Store;
  212. } else {
  213. colorAttachment.loadOp = GPULoadOp.Load;
  214. colorAttachment.storeOp = GPUStoreOp.Store;
  215. }
  216. }
  217. } else {
  218. const colorAttachment = descriptor.colorAttachments[ 0 ];
  219. if ( renderContext.clearColor ) {
  220. colorAttachment.clearValue = renderContext.clearColorValue;
  221. colorAttachment.loadOp = GPULoadOp.Clear;
  222. colorAttachment.storeOp = GPUStoreOp.Store;
  223. } else {
  224. colorAttachment.loadOp = GPULoadOp.Load;
  225. colorAttachment.storeOp = GPUStoreOp.Store;
  226. }
  227. }
  228. //
  229. if ( renderContext.depth ) {
  230. if ( renderContext.clearDepth ) {
  231. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  232. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  233. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  234. } else {
  235. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  236. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  237. }
  238. }
  239. if ( renderContext.stencil ) {
  240. if ( renderContext.clearStencil ) {
  241. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  242. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  243. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  244. } else {
  245. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  246. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  247. }
  248. }
  249. //
  250. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  251. const currentPass = encoder.beginRenderPass( descriptor );
  252. //
  253. renderContextData.descriptor = descriptor;
  254. renderContextData.encoder = encoder;
  255. renderContextData.currentPass = currentPass;
  256. renderContextData.currentSets = { attributes: {} };
  257. //
  258. if ( renderContext.viewport ) {
  259. this.updateViewport( renderContext );
  260. }
  261. if ( renderContext.scissor ) {
  262. const { x, y, width, height } = renderContext.scissorValue;
  263. currentPass.setScissorRect( x, renderContext.height - height - y, width, height );
  264. }
  265. }
  266. finishRender( renderContext ) {
  267. const renderContextData = this.get( renderContext );
  268. const occlusionQueryCount = renderContext.occlusionQueryCount;
  269. if ( renderContextData.renderBundles !== undefined && renderContextData.renderBundles.length > 0 ) {
  270. renderContextData.registerBundlesPhase = false;
  271. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  272. }
  273. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  274. renderContextData.currentPass.endOcclusionQuery();
  275. }
  276. renderContextData.currentPass.end();
  277. if ( occlusionQueryCount > 0 ) {
  278. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  279. //
  280. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  281. if ( queryResolveBuffer === undefined ) {
  282. queryResolveBuffer = this.device.createBuffer(
  283. {
  284. size: bufferSize,
  285. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  286. }
  287. );
  288. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  289. }
  290. //
  291. const readBuffer = this.device.createBuffer(
  292. {
  293. size: bufferSize,
  294. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  295. }
  296. );
  297. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  298. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  299. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  300. renderContextData.occlusionQueryBuffer = readBuffer;
  301. //
  302. this.resolveOccludedAsync( renderContext );
  303. }
  304. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  305. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  306. //
  307. if ( renderContext.textures !== null ) {
  308. const textures = renderContext.textures;
  309. for ( let i = 0; i < textures.length; i ++ ) {
  310. const texture = textures[ i ];
  311. if ( texture.generateMipmaps === true ) {
  312. this.textureUtils.generateMipmaps( texture );
  313. }
  314. }
  315. }
  316. }
  317. isOccluded( renderContext, object ) {
  318. const renderContextData = this.get( renderContext );
  319. return renderContextData.occluded && renderContextData.occluded.has( object );
  320. }
  321. async resolveOccludedAsync( renderContext ) {
  322. const renderContextData = this.get( renderContext );
  323. // handle occlusion query results
  324. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  325. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  326. const occluded = new WeakSet();
  327. renderContextData.currentOcclusionQueryObjects = null;
  328. renderContextData.currentOcclusionQueryBuffer = null;
  329. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  330. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  331. const results = new BigUint64Array( buffer );
  332. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  333. if ( results[ i ] !== BigInt( 0 ) ) {
  334. occluded.add( currentOcclusionQueryObjects[ i ] );
  335. }
  336. }
  337. currentOcclusionQueryBuffer.destroy();
  338. renderContextData.occluded = occluded;
  339. }
  340. }
  341. updateViewport( renderContext ) {
  342. const { currentPass } = this.get( renderContext );
  343. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  344. currentPass.setViewport( x, renderContext.height - height - y, width, height, minDepth, maxDepth );
  345. }
  346. clear( color, depth, stencil, renderTargetData = null ) {
  347. const device = this.device;
  348. const renderer = this.renderer;
  349. let colorAttachments = [];
  350. let depthStencilAttachment;
  351. let clearValue;
  352. let supportsDepth;
  353. let supportsStencil;
  354. if ( color ) {
  355. const clearColor = this.getClearColor();
  356. if ( this.renderer.alpha === true ) {
  357. // premultiply alpha
  358. const a = clearColor.a;
  359. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  360. } else {
  361. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  362. }
  363. }
  364. if ( renderTargetData === null ) {
  365. supportsDepth = renderer.depth;
  366. supportsStencil = renderer.stencil;
  367. const descriptor = this._getDefaultRenderPassDescriptor();
  368. if ( color ) {
  369. colorAttachments = descriptor.colorAttachments;
  370. const colorAttachment = colorAttachments[ 0 ];
  371. colorAttachment.clearValue = clearValue;
  372. colorAttachment.loadOp = GPULoadOp.Clear;
  373. colorAttachment.storeOp = GPUStoreOp.Store;
  374. }
  375. if ( supportsDepth || supportsStencil ) {
  376. depthStencilAttachment = descriptor.depthStencilAttachment;
  377. }
  378. } else {
  379. supportsDepth = renderTargetData.depth;
  380. supportsStencil = renderTargetData.stencil;
  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 ( supportsDepth || supportsStencil ) {
  403. const depthTextureData = this.get( renderTargetData.depthTexture );
  404. depthStencilAttachment = {
  405. view: depthTextureData.texture.createView()
  406. };
  407. }
  408. }
  409. //
  410. if ( supportsDepth ) {
  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. //
  421. if ( supportsStencil ) {
  422. if ( stencil ) {
  423. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  424. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  425. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  426. } else {
  427. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  428. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  429. }
  430. }
  431. //
  432. const encoder = device.createCommandEncoder( {} );
  433. const currentPass = encoder.beginRenderPass( {
  434. colorAttachments,
  435. depthStencilAttachment
  436. } );
  437. currentPass.end();
  438. device.queue.submit( [ encoder.finish() ] );
  439. }
  440. // compute
  441. beginCompute( computeGroup ) {
  442. const groupGPU = this.get( computeGroup );
  443. const descriptor = {};
  444. this.initTimestampQuery( computeGroup, descriptor );
  445. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  446. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  447. }
  448. compute( computeGroup, computeNode, bindings, pipeline ) {
  449. const { passEncoderGPU } = this.get( computeGroup );
  450. // pipeline
  451. const pipelineGPU = this.get( pipeline ).pipeline;
  452. passEncoderGPU.setPipeline( pipelineGPU );
  453. // bind groups
  454. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  455. const bindGroup = bindings[ i ];
  456. const bindingsData = this.get( bindGroup );
  457. passEncoderGPU.setBindGroup( i, bindingsData.group );
  458. }
  459. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  460. const computeNodeData = this.get( computeNode );
  461. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  462. const { dispatchSize } = computeNodeData;
  463. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  464. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  465. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  466. } else {
  467. dispatchSize.x = computeNode.dispatchCount;
  468. }
  469. passEncoderGPU.dispatchWorkgroups(
  470. dispatchSize.x,
  471. dispatchSize.y,
  472. dispatchSize.z
  473. );
  474. }
  475. finishCompute( computeGroup ) {
  476. const groupData = this.get( computeGroup );
  477. groupData.passEncoderGPU.end();
  478. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  479. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  480. }
  481. // render object
  482. draw( renderObject, info ) {
  483. const { object, geometry, context, pipeline } = renderObject;
  484. const bindings = renderObject.getBindings();
  485. const contextData = this.get( context );
  486. const pipelineGPU = this.get( pipeline ).pipeline;
  487. const currentSets = contextData.currentSets;
  488. const renderObjectData = this.get( renderObject );
  489. const { bundleEncoder, renderBundle, lastPipelineGPU } = renderObjectData;
  490. const renderContextData = this.get( context );
  491. if ( renderContextData.registerBundlesPhase === true && bundleEncoder !== undefined && lastPipelineGPU === pipelineGPU ) {
  492. renderContextData.renderBundles.push( renderBundle );
  493. return;
  494. }
  495. const passEncoderGPU = this.renderer._currentRenderBundle ? this.createBundleEncoder( context, renderObject ) : contextData.currentPass;
  496. // pipeline
  497. if ( currentSets.pipeline !== pipelineGPU ) {
  498. passEncoderGPU.setPipeline( pipelineGPU );
  499. currentSets.pipeline = pipelineGPU;
  500. }
  501. // bind groups
  502. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  503. const bindGroup = bindings[ i ];
  504. const bindingsData = this.get( bindGroup );
  505. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  506. }
  507. // attributes
  508. const index = renderObject.getIndex();
  509. const hasIndex = ( index !== null );
  510. // index
  511. if ( hasIndex === true ) {
  512. if ( currentSets.index !== index ) {
  513. const buffer = this.get( index ).buffer;
  514. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  515. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  516. currentSets.index = index;
  517. }
  518. }
  519. // vertex buffers
  520. const vertexBuffers = renderObject.getVertexBuffers();
  521. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  522. const vertexBuffer = vertexBuffers[ i ];
  523. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  524. const buffer = this.get( vertexBuffer ).buffer;
  525. passEncoderGPU.setVertexBuffer( i, buffer );
  526. currentSets.attributes[ i ] = vertexBuffer;
  527. }
  528. }
  529. // occlusion queries - handle multiple consecutive draw calls for an object
  530. if ( contextData.occlusionQuerySet !== undefined ) {
  531. const lastObject = contextData.lastOcclusionObject;
  532. if ( lastObject !== object ) {
  533. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  534. passEncoderGPU.endOcclusionQuery();
  535. contextData.occlusionQueryIndex ++;
  536. }
  537. if ( object.occlusionTest === true ) {
  538. passEncoderGPU.beginOcclusionQuery( contextData.occlusionQueryIndex );
  539. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  540. }
  541. contextData.lastOcclusionObject = object;
  542. }
  543. }
  544. // draw
  545. const drawRange = renderObject.drawRange;
  546. const firstVertex = drawRange.start;
  547. const instanceCount = this.getInstanceCount( renderObject );
  548. if ( instanceCount === 0 ) return;
  549. if ( object.isBatchedMesh === true ) {
  550. const starts = object._multiDrawStarts;
  551. const counts = object._multiDrawCounts;
  552. const drawCount = object._multiDrawCount;
  553. const drawInstances = object._multiDrawInstances;
  554. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  555. for ( let i = 0; i < drawCount; i ++ ) {
  556. const count = drawInstances ? drawInstances[ i ] : 1;
  557. const firstInstance = count > 1 ? 0 : i;
  558. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  559. }
  560. } else if ( hasIndex === true ) {
  561. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  562. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  563. info.update( object, indexCount, instanceCount );
  564. } else {
  565. const positionAttribute = geometry.attributes.position;
  566. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  567. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  568. info.update( object, vertexCount, instanceCount );
  569. }
  570. if ( this.renderer._currentRenderBundle ) {
  571. const renderBundle = passEncoderGPU.finish();
  572. renderObjectData.lastPipelineGPU = pipelineGPU;
  573. renderObjectData.renderBundle = renderBundle;
  574. renderObjectData.bundleEncoder = passEncoderGPU;
  575. }
  576. }
  577. // cache key
  578. needsRenderUpdate( renderObject ) {
  579. const data = this.get( renderObject );
  580. const { object, material } = renderObject;
  581. const utils = this.utils;
  582. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  583. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  584. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  585. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  586. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  587. let needsUpdate = false;
  588. if ( data.material !== material || data.materialVersion !== material.version ||
  589. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  590. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  591. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  592. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  593. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  594. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  595. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  596. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  597. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  598. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  599. data.primitiveTopology !== primitiveTopology ||
  600. data.clippingContextVersion !== renderObject.clippingContextVersion
  601. ) {
  602. data.material = material; data.materialVersion = material.version;
  603. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  604. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  605. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  606. data.colorWrite = material.colorWrite;
  607. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  608. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  609. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  610. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  611. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  612. data.sampleCount = sampleCount;
  613. data.colorSpace = colorSpace;
  614. data.colorFormat = colorFormat;
  615. data.depthStencilFormat = depthStencilFormat;
  616. data.primitiveTopology = primitiveTopology;
  617. data.clippingContextVersion = renderObject.clippingContextVersion;
  618. needsUpdate = true;
  619. }
  620. return needsUpdate;
  621. }
  622. getRenderCacheKey( renderObject ) {
  623. const { object, material } = renderObject;
  624. const utils = this.utils;
  625. const renderContext = renderObject.context;
  626. return [
  627. material.transparent, material.blending, material.premultipliedAlpha,
  628. material.blendSrc, material.blendDst, material.blendEquation,
  629. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  630. material.colorWrite,
  631. material.depthWrite, material.depthTest, material.depthFunc,
  632. material.stencilWrite, material.stencilFunc,
  633. material.stencilFail, material.stencilZFail, material.stencilZPass,
  634. material.stencilFuncMask, material.stencilWriteMask,
  635. material.side,
  636. utils.getSampleCountRenderContext( renderContext ),
  637. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  638. utils.getPrimitiveTopology( object, material ),
  639. renderObject.clippingContextVersion
  640. ].join();
  641. }
  642. // textures
  643. createSampler( texture ) {
  644. this.textureUtils.createSampler( texture );
  645. }
  646. destroySampler( texture ) {
  647. this.textureUtils.destroySampler( texture );
  648. }
  649. createDefaultTexture( texture ) {
  650. this.textureUtils.createDefaultTexture( texture );
  651. }
  652. createTexture( texture, options ) {
  653. this.textureUtils.createTexture( texture, options );
  654. }
  655. updateTexture( texture, options ) {
  656. this.textureUtils.updateTexture( texture, options );
  657. }
  658. generateMipmaps( texture ) {
  659. this.textureUtils.generateMipmaps( texture );
  660. }
  661. destroyTexture( texture ) {
  662. this.textureUtils.destroyTexture( texture );
  663. }
  664. copyTextureToBuffer( texture, x, y, width, height ) {
  665. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height );
  666. }
  667. initTimestampQuery( renderContext, descriptor ) {
  668. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  669. const renderContextData = this.get( renderContext );
  670. if ( ! renderContextData.timeStampQuerySet ) {
  671. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  672. // beginning and one for the end of compute pass execution.
  673. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  674. const timestampWrites = {
  675. querySet: timeStampQuerySet,
  676. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  677. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  678. };
  679. Object.assign( descriptor, {
  680. timestampWrites,
  681. } );
  682. renderContextData.timeStampQuerySet = timeStampQuerySet;
  683. }
  684. }
  685. // timestamp utils
  686. prepareTimestampBuffer( renderContext, encoder ) {
  687. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  688. const renderContextData = this.get( renderContext );
  689. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  690. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  691. renderContextData.currentTimestampQueryBuffers = {
  692. resolveBuffer: this.device.createBuffer( {
  693. label: 'timestamp resolve buffer',
  694. size: size,
  695. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  696. } ),
  697. resultBuffer: this.device.createBuffer( {
  698. label: 'timestamp result buffer',
  699. size: size,
  700. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  701. } ),
  702. isMappingPending: false,
  703. };
  704. }
  705. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  706. if ( isMappingPending === true ) return;
  707. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  708. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  709. }
  710. async resolveTimestampAsync( renderContext, type = 'render' ) {
  711. if ( ! this.hasFeature( GPUFeatureName.TimestampQuery ) || ! this.trackTimestamp ) return;
  712. const renderContextData = this.get( renderContext );
  713. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  714. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  715. if ( isMappingPending === true ) return;
  716. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  717. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  718. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  719. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  720. this.renderer.info.updateTimestamp( type, duration );
  721. resultBuffer.unmap();
  722. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  723. } );
  724. }
  725. // node builder
  726. createNodeBuilder( object, renderer ) {
  727. return new WGSLNodeBuilder( object, renderer );
  728. }
  729. // program
  730. createProgram( program ) {
  731. const programGPU = this.get( program );
  732. programGPU.module = {
  733. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  734. entryPoint: 'main'
  735. };
  736. }
  737. destroyProgram( program ) {
  738. this.delete( program );
  739. }
  740. // pipelines
  741. createRenderPipeline( renderObject, promises ) {
  742. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  743. }
  744. createComputePipeline( computePipeline, bindings ) {
  745. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  746. }
  747. createBundleEncoder( renderContext, renderObject ) {
  748. return this.pipelineUtils.createBundleEncoder( renderContext, renderObject );
  749. }
  750. // bindings
  751. createBindings( bindGroup ) {
  752. this.bindingUtils.createBindings( bindGroup );
  753. }
  754. updateBindings( bindGroup ) {
  755. this.bindingUtils.createBindings( bindGroup );
  756. }
  757. updateBinding( binding ) {
  758. this.bindingUtils.updateBinding( binding );
  759. }
  760. // attributes
  761. createIndexAttribute( attribute ) {
  762. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  763. }
  764. createAttribute( attribute ) {
  765. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  766. }
  767. createStorageAttribute( attribute ) {
  768. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  769. }
  770. updateAttribute( attribute ) {
  771. this.attributeUtils.updateAttribute( attribute );
  772. }
  773. destroyAttribute( attribute ) {
  774. this.attributeUtils.destroyAttribute( attribute );
  775. }
  776. // canvas
  777. updateSize() {
  778. this.colorBuffer = this.textureUtils.getColorBuffer();
  779. this.defaultRenderPassdescriptor = null;
  780. }
  781. // utils public
  782. getMaxAnisotropy() {
  783. return 16;
  784. }
  785. hasFeature( name ) {
  786. return this.device.features.has( name );
  787. }
  788. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  789. let dstX = 0;
  790. let dstY = 0;
  791. let srcX = 0;
  792. let srcY = 0;
  793. let srcWidth = srcTexture.image.width;
  794. let srcHeight = srcTexture.image.height;
  795. if ( srcRegion !== null ) {
  796. srcX = srcRegion.x;
  797. srcY = srcRegion.y;
  798. srcWidth = srcRegion.width;
  799. srcHeight = srcRegion.height;
  800. }
  801. if ( dstPosition !== null ) {
  802. dstX = dstPosition.x;
  803. dstY = dstPosition.y;
  804. }
  805. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  806. const sourceGPU = this.get( srcTexture ).texture;
  807. const destinationGPU = this.get( dstTexture ).texture;
  808. encoder.copyTextureToTexture(
  809. {
  810. texture: sourceGPU,
  811. mipLevel: level,
  812. origin: { x: srcX, y: srcY, z: 0 }
  813. },
  814. {
  815. texture: destinationGPU,
  816. mipLevel: level,
  817. origin: { x: dstX, y: dstY, z: 0 }
  818. },
  819. [
  820. srcWidth,
  821. srcHeight
  822. ]
  823. );
  824. this.device.queue.submit( [ encoder.finish() ] );
  825. }
  826. copyFramebufferToTexture( texture, renderContext ) {
  827. const renderContextData = this.get( renderContext );
  828. const { encoder, descriptor } = renderContextData;
  829. let sourceGPU = null;
  830. if ( renderContext.renderTarget ) {
  831. if ( texture.isDepthTexture ) {
  832. sourceGPU = this.get( renderContext.depthTexture ).texture;
  833. } else {
  834. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  835. }
  836. } else {
  837. if ( texture.isDepthTexture ) {
  838. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  839. } else {
  840. sourceGPU = this.context.getCurrentTexture();
  841. }
  842. }
  843. const destinationGPU = this.get( texture ).texture;
  844. if ( sourceGPU.format !== destinationGPU.format ) {
  845. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  846. return;
  847. }
  848. renderContextData.currentPass.end();
  849. encoder.copyTextureToTexture(
  850. {
  851. texture: sourceGPU,
  852. origin: { x: 0, y: 0, z: 0 }
  853. },
  854. {
  855. texture: destinationGPU
  856. },
  857. [
  858. texture.image.width,
  859. texture.image.height
  860. ]
  861. );
  862. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  863. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  864. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  865. }
  866. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  867. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  868. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  869. renderContextData.currentSets = { attributes: {} };
  870. }
  871. }
  872. export default WebGPUBackend;
粤ICP备19079148号