WebGPUBackend.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  1. /*// debugger tools
  2. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  3. //*/
  4. import { GPUFeatureName, 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. * A backend implementation targeting WebGPU.
  15. *
  16. * @private
  17. * @augments Backend
  18. */
  19. class WebGPUBackend extends Backend {
  20. /**
  21. * Constructs a new WebGPU backend.
  22. *
  23. * @param {Object} parameters - The configuration parameter.
  24. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  25. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  26. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  27. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  28. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  29. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  30. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  31. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  32. * @param {String} [parameters.powerPreference=undefined] - The power preference.
  33. * @param {Object} [parameters.requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  34. * @param {GPUDevice} [parameters.device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  35. */
  36. constructor( parameters = {} ) {
  37. super( parameters );
  38. /**
  39. * This flag can be used for type testing.
  40. *
  41. * @type {Boolean}
  42. * @readonly
  43. * @default true
  44. */
  45. this.isWebGPUBackend = true;
  46. // some parameters require default values other than "undefined"
  47. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  48. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  49. /**
  50. * Whether to track timestamps with a Timestamp Query API or not.
  51. *
  52. * @type {Boolean}
  53. * @default false
  54. */
  55. this.trackTimestamp = ( parameters.trackTimestamp === true );
  56. /**
  57. * A reference to the device.
  58. *
  59. * @type {GPUDevice?}
  60. * @default null
  61. */
  62. this.device = null;
  63. /**
  64. * A reference to the context.
  65. *
  66. * @type {GPUCanvasContext?}
  67. * @default null
  68. */
  69. this.context = null;
  70. /**
  71. * A reference to the color attachment of the default framebuffer.
  72. *
  73. * @type {GPUTexture?}
  74. * @default null
  75. */
  76. this.colorBuffer = null;
  77. /**
  78. * A reference to the default render pass descriptor.
  79. *
  80. * @type {Object?}
  81. * @default null
  82. */
  83. this.defaultRenderPassdescriptor = null;
  84. /**
  85. * A reference to a backend module holding common utility functions.
  86. *
  87. * @type {WebGPUUtils}
  88. */
  89. this.utils = new WebGPUUtils( this );
  90. /**
  91. * A reference to a backend module holding shader attribute-related
  92. * utility functions.
  93. *
  94. * @type {WebGPUAttributeUtils}
  95. */
  96. this.attributeUtils = new WebGPUAttributeUtils( this );
  97. /**
  98. * A reference to a backend module holding shader binding-related
  99. * utility functions.
  100. *
  101. * @type {WebGPUBindingUtils}
  102. */
  103. this.bindingUtils = new WebGPUBindingUtils( this );
  104. /**
  105. * A reference to a backend module holding shader pipeline-related
  106. * utility functions.
  107. *
  108. * @type {WebGPUPipelineUtils}
  109. */
  110. this.pipelineUtils = new WebGPUPipelineUtils( this );
  111. /**
  112. * A reference to a backend module holding shader texture-related
  113. * utility functions.
  114. *
  115. * @type {WebGPUTextureUtils}
  116. */
  117. this.textureUtils = new WebGPUTextureUtils( this );
  118. /**
  119. * A map that manages the resolve buffers for occlusion queries.
  120. *
  121. * @type {Map<Number,GPUBuffer>}
  122. */
  123. this.occludedResolveCache = new Map();
  124. }
  125. /**
  126. * Initializes the backend so it is ready for usage.
  127. *
  128. * @async
  129. * @param {Renderer} renderer - The renderer.
  130. * @return {Promise} A Promise that resolves when the backend has been initialized.
  131. */
  132. async init( renderer ) {
  133. await super.init( renderer );
  134. //
  135. const parameters = this.parameters;
  136. // create the device if it is not passed with parameters
  137. let device;
  138. if ( parameters.device === undefined ) {
  139. const adapterOptions = {
  140. powerPreference: parameters.powerPreference
  141. };
  142. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  143. if ( adapter === null ) {
  144. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  145. }
  146. // feature support
  147. const features = Object.values( GPUFeatureName );
  148. const supportedFeatures = [];
  149. for ( const name of features ) {
  150. if ( adapter.features.has( name ) ) {
  151. supportedFeatures.push( name );
  152. }
  153. }
  154. const deviceDescriptor = {
  155. requiredFeatures: supportedFeatures,
  156. requiredLimits: parameters.requiredLimits
  157. };
  158. device = await adapter.requestDevice( deviceDescriptor );
  159. } else {
  160. device = parameters.device;
  161. }
  162. device.lost.then( ( info ) => {
  163. const deviceLossInfo = {
  164. api: 'WebGPU',
  165. message: info.message || 'Unknown reason',
  166. reason: info.reason || null,
  167. originalEvent: info
  168. };
  169. renderer.onDeviceLost( deviceLossInfo );
  170. } );
  171. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  172. this.device = device;
  173. this.context = context;
  174. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  175. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  176. this.context.configure( {
  177. device: this.device,
  178. format: this.utils.getPreferredCanvasFormat(),
  179. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  180. alphaMode: alphaMode
  181. } );
  182. this.updateSize();
  183. }
  184. /**
  185. * The coordinate system of the backend.
  186. *
  187. * @type {Number}
  188. * @readonly
  189. */
  190. get coordinateSystem() {
  191. return WebGPUCoordinateSystem;
  192. }
  193. /**
  194. * This method performs a readback operation by moving buffer data from
  195. * a storage buffer attribute from the GPU to the CPU.
  196. *
  197. * @async
  198. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  199. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  200. */
  201. async getArrayBufferAsync( attribute ) {
  202. return await this.attributeUtils.getArrayBufferAsync( attribute );
  203. }
  204. /**
  205. * Returns the backend's rendering context.
  206. *
  207. * @return {GPUCanvasContext} The rendering context.
  208. */
  209. getContext() {
  210. return this.context;
  211. }
  212. /**
  213. * Returns the default render pass descriptor.
  214. *
  215. * In WebGPU, the default framebuffer must be configured
  216. * like custom framebuffers so the backend needs a render
  217. * pass descriptor even when rendering directly to screen.
  218. *
  219. * @private
  220. * @return {Object} The render pass descriptor.
  221. */
  222. _getDefaultRenderPassDescriptor() {
  223. let descriptor = this.defaultRenderPassdescriptor;
  224. if ( descriptor === null ) {
  225. const renderer = this.renderer;
  226. descriptor = {
  227. colorAttachments: [ {
  228. view: null
  229. } ],
  230. };
  231. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  232. descriptor.depthStencilAttachment = {
  233. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  234. };
  235. }
  236. const colorAttachment = descriptor.colorAttachments[ 0 ];
  237. if ( this.renderer.samples > 0 ) {
  238. colorAttachment.view = this.colorBuffer.createView();
  239. } else {
  240. colorAttachment.resolveTarget = undefined;
  241. }
  242. this.defaultRenderPassdescriptor = descriptor;
  243. }
  244. const colorAttachment = descriptor.colorAttachments[ 0 ];
  245. if ( this.renderer.samples > 0 ) {
  246. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  247. } else {
  248. colorAttachment.view = this.context.getCurrentTexture().createView();
  249. }
  250. return descriptor;
  251. }
  252. /**
  253. * Returns the render pass descriptor for the given render context.
  254. *
  255. * @private
  256. * @param {RenderContext} renderContext - The render context.
  257. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  258. * @return {Object} The render pass descriptor.
  259. */
  260. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  261. const renderTarget = renderContext.renderTarget;
  262. const renderTargetData = this.get( renderTarget );
  263. let descriptors = renderTargetData.descriptors;
  264. if ( descriptors === undefined ||
  265. renderTargetData.width !== renderTarget.width ||
  266. renderTargetData.height !== renderTarget.height ||
  267. renderTargetData.dimensions !== renderTarget.dimensions ||
  268. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  269. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  270. renderTargetData.samples !== renderTarget.samples ||
  271. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  272. ) {
  273. descriptors = {};
  274. renderTargetData.descriptors = descriptors;
  275. // dispose
  276. const onDispose = () => {
  277. renderTarget.removeEventListener( 'dispose', onDispose );
  278. this.delete( renderTarget );
  279. };
  280. renderTarget.addEventListener( 'dispose', onDispose );
  281. }
  282. const cacheKey = renderContext.getCacheKey();
  283. let descriptor = descriptors[ cacheKey ];
  284. if ( descriptor === undefined ) {
  285. const textures = renderContext.textures;
  286. const colorAttachments = [];
  287. let sliceIndex;
  288. for ( let i = 0; i < textures.length; i ++ ) {
  289. const textureData = this.get( textures[ i ] );
  290. const viewDescriptor = {
  291. label: `colorAttachment_${ i }`,
  292. baseMipLevel: renderContext.activeMipmapLevel,
  293. mipLevelCount: 1,
  294. baseArrayLayer: renderContext.activeCubeFace,
  295. arrayLayerCount: 1,
  296. dimension: GPUTextureViewDimension.TwoD
  297. };
  298. if ( renderTarget.isRenderTarget3D ) {
  299. sliceIndex = renderContext.activeCubeFace;
  300. viewDescriptor.baseArrayLayer = 0;
  301. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  302. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  303. } else if ( renderTarget.isRenderTargetArray ) {
  304. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  305. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  306. }
  307. const textureView = textureData.texture.createView( viewDescriptor );
  308. let view, resolveTarget;
  309. if ( textureData.msaaTexture !== undefined ) {
  310. view = textureData.msaaTexture.createView();
  311. resolveTarget = textureView;
  312. } else {
  313. view = textureView;
  314. resolveTarget = undefined;
  315. }
  316. colorAttachments.push( {
  317. view,
  318. depthSlice: sliceIndex,
  319. resolveTarget,
  320. loadOp: GPULoadOp.Load,
  321. storeOp: GPUStoreOp.Store,
  322. ...colorAttachmentsConfig
  323. } );
  324. }
  325. descriptor = {
  326. colorAttachments,
  327. };
  328. if ( renderContext.depth ) {
  329. const depthTextureData = this.get( renderContext.depthTexture );
  330. const depthStencilAttachment = {
  331. view: depthTextureData.texture.createView()
  332. };
  333. descriptor.depthStencilAttachment = depthStencilAttachment;
  334. }
  335. descriptors[ cacheKey ] = descriptor;
  336. renderTargetData.width = renderTarget.width;
  337. renderTargetData.height = renderTarget.height;
  338. renderTargetData.samples = renderTarget.samples;
  339. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  340. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  341. renderTargetData.dimensions = renderTarget.dimensions;
  342. renderTargetData.depthSlice = sliceIndex;
  343. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  344. }
  345. return descriptor;
  346. }
  347. /**
  348. * This method is executed at the beginning of a render call and prepares
  349. * the WebGPU state for upcoming render calls
  350. *
  351. * @param {RenderContext} renderContext - The render context.
  352. */
  353. beginRender( renderContext ) {
  354. const renderContextData = this.get( renderContext );
  355. const device = this.device;
  356. const occlusionQueryCount = renderContext.occlusionQueryCount;
  357. let occlusionQuerySet;
  358. if ( occlusionQueryCount > 0 ) {
  359. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  360. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  361. // Get a reference to the array of objects with queries. The renderContextData property
  362. // can be changed by another render pass before the buffer.mapAsyc() completes.
  363. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  364. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  365. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  366. //
  367. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  368. renderContextData.occlusionQuerySet = occlusionQuerySet;
  369. renderContextData.occlusionQueryIndex = 0;
  370. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  371. renderContextData.lastOcclusionObject = null;
  372. }
  373. let descriptor;
  374. if ( renderContext.textures === null ) {
  375. descriptor = this._getDefaultRenderPassDescriptor();
  376. } else {
  377. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  378. }
  379. this.initTimestampQuery( renderContext, descriptor );
  380. descriptor.occlusionQuerySet = occlusionQuerySet;
  381. const depthStencilAttachment = descriptor.depthStencilAttachment;
  382. if ( renderContext.textures !== null ) {
  383. const colorAttachments = descriptor.colorAttachments;
  384. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  385. const colorAttachment = colorAttachments[ i ];
  386. if ( renderContext.clearColor ) {
  387. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  388. colorAttachment.loadOp = GPULoadOp.Clear;
  389. colorAttachment.storeOp = GPUStoreOp.Store;
  390. } else {
  391. colorAttachment.loadOp = GPULoadOp.Load;
  392. colorAttachment.storeOp = GPUStoreOp.Store;
  393. }
  394. }
  395. } else {
  396. const colorAttachment = descriptor.colorAttachments[ 0 ];
  397. if ( renderContext.clearColor ) {
  398. colorAttachment.clearValue = renderContext.clearColorValue;
  399. colorAttachment.loadOp = GPULoadOp.Clear;
  400. colorAttachment.storeOp = GPUStoreOp.Store;
  401. } else {
  402. colorAttachment.loadOp = GPULoadOp.Load;
  403. colorAttachment.storeOp = GPUStoreOp.Store;
  404. }
  405. }
  406. //
  407. if ( renderContext.depth ) {
  408. if ( renderContext.clearDepth ) {
  409. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  410. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  411. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  412. } else {
  413. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  414. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  415. }
  416. }
  417. if ( renderContext.stencil ) {
  418. if ( renderContext.clearStencil ) {
  419. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  420. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  421. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  422. } else {
  423. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  424. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  425. }
  426. }
  427. //
  428. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  429. const currentPass = encoder.beginRenderPass( descriptor );
  430. //
  431. renderContextData.descriptor = descriptor;
  432. renderContextData.encoder = encoder;
  433. renderContextData.currentPass = currentPass;
  434. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  435. renderContextData.renderBundles = [];
  436. //
  437. if ( renderContext.viewport ) {
  438. this.updateViewport( renderContext );
  439. }
  440. if ( renderContext.scissor ) {
  441. const { x, y, width, height } = renderContext.scissorValue;
  442. currentPass.setScissorRect( x, y, width, height );
  443. }
  444. }
  445. /**
  446. * This method is executed at the end of a render call and finalizes work
  447. * after draw calls.
  448. *
  449. * @param {RenderContext} renderContext - The render context.
  450. */
  451. finishRender( renderContext ) {
  452. const renderContextData = this.get( renderContext );
  453. const occlusionQueryCount = renderContext.occlusionQueryCount;
  454. if ( renderContextData.renderBundles.length > 0 ) {
  455. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  456. }
  457. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  458. renderContextData.currentPass.endOcclusionQuery();
  459. }
  460. renderContextData.currentPass.end();
  461. if ( occlusionQueryCount > 0 ) {
  462. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  463. //
  464. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  465. if ( queryResolveBuffer === undefined ) {
  466. queryResolveBuffer = this.device.createBuffer(
  467. {
  468. size: bufferSize,
  469. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  470. }
  471. );
  472. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  473. }
  474. //
  475. const readBuffer = this.device.createBuffer(
  476. {
  477. size: bufferSize,
  478. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  479. }
  480. );
  481. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  482. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  483. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  484. renderContextData.occlusionQueryBuffer = readBuffer;
  485. //
  486. this.resolveOccludedAsync( renderContext );
  487. }
  488. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  489. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  490. //
  491. if ( renderContext.textures !== null ) {
  492. const textures = renderContext.textures;
  493. for ( let i = 0; i < textures.length; i ++ ) {
  494. const texture = textures[ i ];
  495. if ( texture.generateMipmaps === true ) {
  496. this.textureUtils.generateMipmaps( texture );
  497. }
  498. }
  499. }
  500. }
  501. /**
  502. * Returns `true` if the given 3D object is fully occluded by other
  503. * 3D objects in the scene.
  504. *
  505. * @param {RenderContext} renderContext - The render context.
  506. * @param {Object3D} object - The 3D object to test.
  507. * @return {Boolean} Whether the 3D object is fully occluded or not.
  508. */
  509. isOccluded( renderContext, object ) {
  510. const renderContextData = this.get( renderContext );
  511. return renderContextData.occluded && renderContextData.occluded.has( object );
  512. }
  513. /**
  514. * This method processes the result of occlusion queries and writes it
  515. * into render context data.
  516. *
  517. * @async
  518. * @param {RenderContext} renderContext - The render context.
  519. */
  520. async resolveOccludedAsync( renderContext ) {
  521. const renderContextData = this.get( renderContext );
  522. // handle occlusion query results
  523. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  524. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  525. const occluded = new WeakSet();
  526. renderContextData.currentOcclusionQueryObjects = null;
  527. renderContextData.currentOcclusionQueryBuffer = null;
  528. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  529. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  530. const results = new BigUint64Array( buffer );
  531. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  532. if ( results[ i ] !== BigInt( 0 ) ) {
  533. occluded.add( currentOcclusionQueryObjects[ i ] );
  534. }
  535. }
  536. currentOcclusionQueryBuffer.destroy();
  537. renderContextData.occluded = occluded;
  538. }
  539. }
  540. /**
  541. * Updates the viewport with the values from the given render context.
  542. *
  543. * @param {RenderContext} renderContext - The render context.
  544. */
  545. updateViewport( renderContext ) {
  546. const { currentPass } = this.get( renderContext );
  547. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  548. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  549. }
  550. /**
  551. * Performs a clear operation.
  552. *
  553. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  554. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  555. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  556. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  557. */
  558. clear( color, depth, stencil, renderTargetContext = null ) {
  559. const device = this.device;
  560. const renderer = this.renderer;
  561. let colorAttachments = [];
  562. let depthStencilAttachment;
  563. let clearValue;
  564. let supportsDepth;
  565. let supportsStencil;
  566. if ( color ) {
  567. const clearColor = this.getClearColor();
  568. if ( this.renderer.alpha === true ) {
  569. // premultiply alpha
  570. const a = clearColor.a;
  571. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  572. } else {
  573. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  574. }
  575. }
  576. if ( renderTargetContext === null ) {
  577. supportsDepth = renderer.depth;
  578. supportsStencil = renderer.stencil;
  579. const descriptor = this._getDefaultRenderPassDescriptor();
  580. if ( color ) {
  581. colorAttachments = descriptor.colorAttachments;
  582. const colorAttachment = colorAttachments[ 0 ];
  583. colorAttachment.clearValue = clearValue;
  584. colorAttachment.loadOp = GPULoadOp.Clear;
  585. colorAttachment.storeOp = GPUStoreOp.Store;
  586. }
  587. if ( supportsDepth || supportsStencil ) {
  588. depthStencilAttachment = descriptor.depthStencilAttachment;
  589. }
  590. } else {
  591. supportsDepth = renderTargetContext.depth;
  592. supportsStencil = renderTargetContext.stencil;
  593. if ( color ) {
  594. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear } );
  595. colorAttachments = descriptor.colorAttachments;
  596. }
  597. if ( supportsDepth || supportsStencil ) {
  598. const depthTextureData = this.get( renderTargetContext.depthTexture );
  599. depthStencilAttachment = {
  600. view: depthTextureData.texture.createView()
  601. };
  602. }
  603. }
  604. //
  605. if ( supportsDepth ) {
  606. if ( depth ) {
  607. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  608. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  609. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  610. } else {
  611. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  612. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  613. }
  614. }
  615. //
  616. if ( supportsStencil ) {
  617. if ( stencil ) {
  618. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  619. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  620. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  621. } else {
  622. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  623. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  624. }
  625. }
  626. //
  627. const encoder = device.createCommandEncoder( { label: 'clear' } );
  628. const currentPass = encoder.beginRenderPass( {
  629. colorAttachments,
  630. depthStencilAttachment
  631. } );
  632. currentPass.end();
  633. device.queue.submit( [ encoder.finish() ] );
  634. }
  635. // compute
  636. /**
  637. * This method is executed at the beginning of a compute call and
  638. * prepares the state for upcoming compute tasks.
  639. *
  640. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  641. */
  642. beginCompute( computeGroup ) {
  643. const groupGPU = this.get( computeGroup );
  644. const descriptor = {
  645. label: 'computeGroup_' + computeGroup.id
  646. };
  647. this.initTimestampQuery( computeGroup, descriptor );
  648. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  649. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  650. }
  651. /**
  652. * Executes a compute command for the given compute node.
  653. *
  654. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  655. * @param {Node} computeNode - The compute node.
  656. * @param {Array<BindGroup>} bindings - The bindings.
  657. * @param {ComputePipeline} pipeline - The compute pipeline.
  658. */
  659. compute( computeGroup, computeNode, bindings, pipeline ) {
  660. const { passEncoderGPU } = this.get( computeGroup );
  661. // pipeline
  662. const pipelineGPU = this.get( pipeline ).pipeline;
  663. passEncoderGPU.setPipeline( pipelineGPU );
  664. // bind groups
  665. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  666. const bindGroup = bindings[ i ];
  667. const bindingsData = this.get( bindGroup );
  668. passEncoderGPU.setBindGroup( i, bindingsData.group );
  669. }
  670. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  671. const computeNodeData = this.get( computeNode );
  672. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  673. const { dispatchSize } = computeNodeData;
  674. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  675. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  676. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  677. } else {
  678. dispatchSize.x = computeNode.dispatchCount;
  679. }
  680. passEncoderGPU.dispatchWorkgroups(
  681. dispatchSize.x,
  682. dispatchSize.y,
  683. dispatchSize.z
  684. );
  685. }
  686. /**
  687. * This method is executed at the end of a compute call and
  688. * finalizes work after compute tasks.
  689. *
  690. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  691. */
  692. finishCompute( computeGroup ) {
  693. const groupData = this.get( computeGroup );
  694. groupData.passEncoderGPU.end();
  695. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  696. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  697. }
  698. /**
  699. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  700. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  701. *
  702. * @async
  703. * @return {Promise} A Promise that resolves when synchronization has been finished.
  704. */
  705. async waitForGPU() {
  706. await this.device.queue.onSubmittedWorkDone();
  707. }
  708. // render object
  709. /**
  710. * Executes a draw command for the given render object.
  711. *
  712. * @param {RenderObject} renderObject - The render object to draw.
  713. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  714. */
  715. draw( renderObject, info ) {
  716. const { object, context, pipeline } = renderObject;
  717. const bindings = renderObject.getBindings();
  718. const renderContextData = this.get( context );
  719. const pipelineGPU = this.get( pipeline ).pipeline;
  720. const currentSets = renderContextData.currentSets;
  721. const passEncoderGPU = renderContextData.currentPass;
  722. const drawParams = renderObject.getDrawParameters();
  723. if ( drawParams === null ) return;
  724. // pipeline
  725. if ( currentSets.pipeline !== pipelineGPU ) {
  726. passEncoderGPU.setPipeline( pipelineGPU );
  727. currentSets.pipeline = pipelineGPU;
  728. }
  729. // bind groups
  730. const currentBindingGroups = currentSets.bindingGroups;
  731. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  732. const bindGroup = bindings[ i ];
  733. const bindingsData = this.get( bindGroup );
  734. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  735. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  736. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  737. }
  738. }
  739. // attributes
  740. const index = renderObject.getIndex();
  741. const hasIndex = ( index !== null );
  742. // index
  743. if ( hasIndex === true ) {
  744. if ( currentSets.index !== index ) {
  745. const buffer = this.get( index ).buffer;
  746. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  747. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  748. currentSets.index = index;
  749. }
  750. }
  751. // vertex buffers
  752. const vertexBuffers = renderObject.getVertexBuffers();
  753. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  754. const vertexBuffer = vertexBuffers[ i ];
  755. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  756. const buffer = this.get( vertexBuffer ).buffer;
  757. passEncoderGPU.setVertexBuffer( i, buffer );
  758. currentSets.attributes[ i ] = vertexBuffer;
  759. }
  760. }
  761. // occlusion queries - handle multiple consecutive draw calls for an object
  762. if ( renderContextData.occlusionQuerySet !== undefined ) {
  763. const lastObject = renderContextData.lastOcclusionObject;
  764. if ( lastObject !== object ) {
  765. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  766. passEncoderGPU.endOcclusionQuery();
  767. renderContextData.occlusionQueryIndex ++;
  768. }
  769. if ( object.occlusionTest === true ) {
  770. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  771. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  772. }
  773. renderContextData.lastOcclusionObject = object;
  774. }
  775. }
  776. // draw
  777. if ( object.isBatchedMesh === true ) {
  778. const starts = object._multiDrawStarts;
  779. const counts = object._multiDrawCounts;
  780. const drawCount = object._multiDrawCount;
  781. const drawInstances = object._multiDrawInstances;
  782. for ( let i = 0; i < drawCount; i ++ ) {
  783. const count = drawInstances ? drawInstances[ i ] : 1;
  784. const firstInstance = count > 1 ? 0 : i;
  785. if ( hasIndex === true ) {
  786. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  787. } else {
  788. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  789. }
  790. }
  791. } else if ( hasIndex === true ) {
  792. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  793. const indirect = renderObject.getIndirect();
  794. if ( indirect !== null ) {
  795. const buffer = this.get( indirect ).buffer;
  796. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  797. } else {
  798. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  799. }
  800. info.update( object, indexCount, instanceCount );
  801. } else {
  802. const { vertexCount, instanceCount, firstVertex } = drawParams;
  803. const indirect = renderObject.getIndirect();
  804. if ( indirect !== null ) {
  805. const buffer = this.get( indirect ).buffer;
  806. passEncoderGPU.drawIndirect( buffer, 0 );
  807. } else {
  808. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  809. }
  810. info.update( object, vertexCount, instanceCount );
  811. }
  812. }
  813. // cache key
  814. /**
  815. * Returns `true` if the render pipeline requires an update.
  816. *
  817. * @param {RenderObject} renderObject - The render object.
  818. * @return {Boolean} Whether the render pipeline requires an update or not.
  819. */
  820. needsRenderUpdate( renderObject ) {
  821. const data = this.get( renderObject );
  822. const { object, material } = renderObject;
  823. const utils = this.utils;
  824. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  825. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  826. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  827. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  828. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  829. let needsUpdate = false;
  830. if ( data.material !== material || data.materialVersion !== material.version ||
  831. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  832. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  833. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  834. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  835. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  836. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  837. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  838. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  839. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  840. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  841. data.primitiveTopology !== primitiveTopology ||
  842. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  843. ) {
  844. data.material = material; data.materialVersion = material.version;
  845. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  846. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  847. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  848. data.colorWrite = material.colorWrite;
  849. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  850. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  851. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  852. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  853. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  854. data.sampleCount = sampleCount;
  855. data.colorSpace = colorSpace;
  856. data.colorFormat = colorFormat;
  857. data.depthStencilFormat = depthStencilFormat;
  858. data.primitiveTopology = primitiveTopology;
  859. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  860. needsUpdate = true;
  861. }
  862. return needsUpdate;
  863. }
  864. /**
  865. * Returns a cache key that is used to identify render pipelines.
  866. *
  867. * @param {RenderObject} renderObject - The render object.
  868. * @return {String} The cache key.
  869. */
  870. getRenderCacheKey( renderObject ) {
  871. const { object, material } = renderObject;
  872. const utils = this.utils;
  873. const renderContext = renderObject.context;
  874. return [
  875. material.transparent, material.blending, material.premultipliedAlpha,
  876. material.blendSrc, material.blendDst, material.blendEquation,
  877. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  878. material.colorWrite,
  879. material.depthWrite, material.depthTest, material.depthFunc,
  880. material.stencilWrite, material.stencilFunc,
  881. material.stencilFail, material.stencilZFail, material.stencilZPass,
  882. material.stencilFuncMask, material.stencilWriteMask,
  883. material.side,
  884. utils.getSampleCountRenderContext( renderContext ),
  885. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  886. utils.getPrimitiveTopology( object, material ),
  887. renderObject.getGeometryCacheKey(),
  888. renderObject.clippingContextCacheKey
  889. ].join();
  890. }
  891. // textures
  892. /**
  893. * Creates a GPU sampler for the given texture.
  894. *
  895. * @param {Texture} texture - The texture to create the sampler for.
  896. */
  897. createSampler( texture ) {
  898. this.textureUtils.createSampler( texture );
  899. }
  900. /**
  901. * Destroys the GPU sampler for the given texture.
  902. *
  903. * @param {Texture} texture - The texture to destroy the sampler for.
  904. */
  905. destroySampler( texture ) {
  906. this.textureUtils.destroySampler( texture );
  907. }
  908. /**
  909. * Creates a default texture for the given texture that can be used
  910. * as a placeholder until the actual texture is ready for usage.
  911. *
  912. * @param {Texture} texture - The texture to create a default texture for.
  913. */
  914. createDefaultTexture( texture ) {
  915. this.textureUtils.createDefaultTexture( texture );
  916. }
  917. /**
  918. * Defines a texture on the GPU for the given texture object.
  919. *
  920. * @param {Texture} texture - The texture.
  921. * @param {Object} [options={}] - Optional configuration parameter.
  922. */
  923. createTexture( texture, options ) {
  924. this.textureUtils.createTexture( texture, options );
  925. }
  926. /**
  927. * Uploads the updated texture data to the GPU.
  928. *
  929. * @param {Texture} texture - The texture.
  930. * @param {Object} [options={}] - Optional configuration parameter.
  931. */
  932. updateTexture( texture, options ) {
  933. this.textureUtils.updateTexture( texture, options );
  934. }
  935. /**
  936. * Generates mipmaps for the given texture.
  937. *
  938. * @param {Texture} texture - The texture.
  939. */
  940. generateMipmaps( texture ) {
  941. this.textureUtils.generateMipmaps( texture );
  942. }
  943. /**
  944. * Destroys the GPU data for the given texture object.
  945. *
  946. * @param {Texture} texture - The texture.
  947. */
  948. destroyTexture( texture ) {
  949. this.textureUtils.destroyTexture( texture );
  950. }
  951. /**
  952. * Returns texture data as a typed array.
  953. *
  954. * @async
  955. * @param {Texture} texture - The texture to copy.
  956. * @param {Number} x - The x coordinate of the copy origin.
  957. * @param {Number} y - The y coordinate of the copy origin.
  958. * @param {Number} width - The width of the copy.
  959. * @param {Number} height - The height of the copy.
  960. * @param {Number} faceIndex - The face index.
  961. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  962. */
  963. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  964. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  965. }
  966. /**
  967. * Inits a time stamp query for the given render context.
  968. *
  969. * @param {RenderContext} renderContext - The render context.
  970. * @param {Object} descriptor - The query descriptor.
  971. */
  972. initTimestampQuery( renderContext, descriptor ) {
  973. if ( ! this.trackTimestamp ) return;
  974. const renderContextData = this.get( renderContext );
  975. if ( ! renderContextData.timestampQuerySet ) {
  976. const type = renderContext.isComputeNode ? 'compute' : 'render';
  977. const timestampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  978. const timestampWrites = {
  979. querySet: timestampQuerySet,
  980. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  981. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  982. };
  983. Object.assign( descriptor, { timestampWrites } );
  984. renderContextData.timestampQuerySet = timestampQuerySet;
  985. }
  986. }
  987. /**
  988. * Prepares the timestamp buffer.
  989. *
  990. * @param {RenderContext} renderContext - The render context.
  991. * @param {GPUCommandEncoder} encoder - The command encoder.
  992. */
  993. prepareTimestampBuffer( renderContext, encoder ) {
  994. if ( ! this.trackTimestamp ) return;
  995. const renderContextData = this.get( renderContext );
  996. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  997. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  998. renderContextData.currentTimestampQueryBuffers = {
  999. resolveBuffer: this.device.createBuffer( {
  1000. label: 'timestamp resolve buffer',
  1001. size: size,
  1002. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  1003. } ),
  1004. resultBuffer: this.device.createBuffer( {
  1005. label: 'timestamp result buffer',
  1006. size: size,
  1007. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  1008. } )
  1009. };
  1010. }
  1011. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  1012. encoder.resolveQuerySet( renderContextData.timestampQuerySet, 0, 2, resolveBuffer, 0 );
  1013. if ( resultBuffer.mapState === 'unmapped' ) {
  1014. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  1015. }
  1016. }
  1017. /**
  1018. * Resolves the time stamp for the given render context and type.
  1019. *
  1020. * @async
  1021. * @param {RenderContext} renderContext - The render context.
  1022. * @param {String} type - The render context.
  1023. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  1024. */
  1025. async resolveTimestampAsync( renderContext, type = 'render' ) {
  1026. if ( ! this.trackTimestamp ) return;
  1027. const renderContextData = this.get( renderContext );
  1028. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  1029. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  1030. if ( resultBuffer.mapState === 'unmapped' ) {
  1031. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  1032. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  1033. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  1034. this.renderer.info.updateTimestamp( type, duration );
  1035. resultBuffer.unmap();
  1036. } );
  1037. }
  1038. }
  1039. // node builder
  1040. /**
  1041. * Returns a node builder for the given render object.
  1042. *
  1043. * @param {RenderObject} object - The render object.
  1044. * @param {Renderer} renderer - The renderer.
  1045. * @return {WGSLNodeBuilder} The node builder.
  1046. */
  1047. createNodeBuilder( object, renderer ) {
  1048. return new WGSLNodeBuilder( object, renderer );
  1049. }
  1050. // program
  1051. /**
  1052. * Creates a shader program from the given programmable stage.
  1053. *
  1054. * @param {ProgrammableStage} program - The programmable stage.
  1055. */
  1056. createProgram( program ) {
  1057. const programGPU = this.get( program );
  1058. programGPU.module = {
  1059. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  1060. entryPoint: 'main'
  1061. };
  1062. }
  1063. /**
  1064. * Destroys the shader program of the given programmable stage.
  1065. *
  1066. * @param {ProgrammableStage} program - The programmable stage.
  1067. */
  1068. destroyProgram( program ) {
  1069. this.delete( program );
  1070. }
  1071. // pipelines
  1072. /**
  1073. * Creates a render pipeline for the given render object.
  1074. *
  1075. * @param {RenderObject} renderObject - The render object.
  1076. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  1077. */
  1078. createRenderPipeline( renderObject, promises ) {
  1079. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  1080. }
  1081. /**
  1082. * Creates a compute pipeline for the given compute node.
  1083. *
  1084. * @param {ComputePipeline} computePipeline - The compute pipeline.
  1085. * @param {Array<BindGroup>} bindings - The bindings.
  1086. */
  1087. createComputePipeline( computePipeline, bindings ) {
  1088. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  1089. }
  1090. /**
  1091. * Prepares the state for encoding render bundles.
  1092. *
  1093. * @param {RenderContext} renderContext - The render context.
  1094. */
  1095. beginBundle( renderContext ) {
  1096. const renderContextData = this.get( renderContext );
  1097. renderContextData._currentPass = renderContextData.currentPass;
  1098. renderContextData._currentSets = renderContextData.currentSets;
  1099. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  1100. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  1101. }
  1102. /**
  1103. * After processing render bundles this method finalizes related work.
  1104. *
  1105. * @param {RenderContext} renderContext - The render context.
  1106. * @param {RenderBundle} bundle - The render bundle.
  1107. */
  1108. finishBundle( renderContext, bundle ) {
  1109. const renderContextData = this.get( renderContext );
  1110. const bundleEncoder = renderContextData.currentPass;
  1111. const bundleGPU = bundleEncoder.finish();
  1112. this.get( bundle ).bundleGPU = bundleGPU;
  1113. // restore render pass state
  1114. renderContextData.currentSets = renderContextData._currentSets;
  1115. renderContextData.currentPass = renderContextData._currentPass;
  1116. }
  1117. /**
  1118. * Adds a render bundle to the render context data.
  1119. *
  1120. * @param {RenderContext} renderContext - The render context.
  1121. * @param {RenderBundle} bundle - The render bundle to add.
  1122. */
  1123. addBundle( renderContext, bundle ) {
  1124. const renderContextData = this.get( renderContext );
  1125. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  1126. }
  1127. // bindings
  1128. /**
  1129. * Creates bindings from the given bind group definition.
  1130. *
  1131. * @param {BindGroup} bindGroup - The bind group.
  1132. * @param {Array<BindGroup>} bindings - Array of bind groups.
  1133. * @param {Number} cacheIndex - The cache index.
  1134. * @param {Number} version - The version.
  1135. */
  1136. createBindings( bindGroup, bindings, cacheIndex, version ) {
  1137. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  1138. }
  1139. /**
  1140. * Updates the given bind group definition.
  1141. *
  1142. * @param {BindGroup} bindGroup - The bind group.
  1143. * @param {Array<BindGroup>} bindings - Array of bind groups.
  1144. * @param {Number} cacheIndex - The cache index.
  1145. * @param {Number} version - The version.
  1146. */
  1147. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  1148. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  1149. }
  1150. /**
  1151. * Updates a buffer binding.
  1152. *
  1153. * @param {Buffer} binding - The buffer binding to update.
  1154. */
  1155. updateBinding( binding ) {
  1156. this.bindingUtils.updateBinding( binding );
  1157. }
  1158. // attributes
  1159. /**
  1160. * Creates the buffer of an indexed shader attribute.
  1161. *
  1162. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  1163. */
  1164. createIndexAttribute( attribute ) {
  1165. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1166. }
  1167. /**
  1168. * Creates the GPU buffer of a shader attribute.
  1169. *
  1170. * @param {BufferAttribute} attribute - The buffer attribute.
  1171. */
  1172. createAttribute( attribute ) {
  1173. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1174. }
  1175. /**
  1176. * Creates the GPU buffer of a storage attribute.
  1177. *
  1178. * @param {BufferAttribute} attribute - The buffer attribute.
  1179. */
  1180. createStorageAttribute( attribute ) {
  1181. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1182. }
  1183. /**
  1184. * Creates the GPU buffer of an indirect storage attribute.
  1185. *
  1186. * @param {BufferAttribute} attribute - The buffer attribute.
  1187. */
  1188. createIndirectStorageAttribute( attribute ) {
  1189. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1190. }
  1191. /**
  1192. * Updates the GPU buffer of a shader attribute.
  1193. *
  1194. * @param {BufferAttribute} attribute - The buffer attribute to update.
  1195. */
  1196. updateAttribute( attribute ) {
  1197. this.attributeUtils.updateAttribute( attribute );
  1198. }
  1199. /**
  1200. * Destroys the GPU buffer of a shader attribute.
  1201. *
  1202. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  1203. */
  1204. destroyAttribute( attribute ) {
  1205. this.attributeUtils.destroyAttribute( attribute );
  1206. }
  1207. // canvas
  1208. /**
  1209. * Triggers an update of the default render pass descriptor.
  1210. */
  1211. updateSize() {
  1212. this.colorBuffer = this.textureUtils.getColorBuffer();
  1213. this.defaultRenderPassdescriptor = null;
  1214. }
  1215. // utils public
  1216. /**
  1217. * Returns the maximum anisotropy texture filtering value.
  1218. *
  1219. * @return {Number} The maximum anisotropy texture filtering value.
  1220. */
  1221. getMaxAnisotropy() {
  1222. return 16;
  1223. }
  1224. /**
  1225. * Checks if the given feature is supported by the backend.
  1226. *
  1227. * @param {String} name - The feature's name.
  1228. * @return {Boolean} Whether the feature is supported or not.
  1229. */
  1230. hasFeature( name ) {
  1231. return this.device.features.has( name );
  1232. }
  1233. /**
  1234. * Copies data of the given source texture to the given destination texture.
  1235. *
  1236. * @param {Texture} srcTexture - The source texture.
  1237. * @param {Texture} dstTexture - The destination texture.
  1238. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  1239. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  1240. * @param {Number} [level=0] - The mip level to copy.
  1241. */
  1242. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  1243. let dstX = 0;
  1244. let dstY = 0;
  1245. let dstLayer = 0;
  1246. let srcX = 0;
  1247. let srcY = 0;
  1248. let srcLayer = 0;
  1249. let srcWidth = srcTexture.image.width;
  1250. let srcHeight = srcTexture.image.height;
  1251. if ( srcRegion !== null ) {
  1252. srcX = srcRegion.x;
  1253. srcY = srcRegion.y;
  1254. srcLayer = srcRegion.z || 0;
  1255. srcWidth = srcRegion.width;
  1256. srcHeight = srcRegion.height;
  1257. }
  1258. if ( dstPosition !== null ) {
  1259. dstX = dstPosition.x;
  1260. dstY = dstPosition.y;
  1261. dstLayer = dstPosition.z || 0;
  1262. }
  1263. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  1264. const sourceGPU = this.get( srcTexture ).texture;
  1265. const destinationGPU = this.get( dstTexture ).texture;
  1266. encoder.copyTextureToTexture(
  1267. {
  1268. texture: sourceGPU,
  1269. mipLevel: level,
  1270. origin: { x: srcX, y: srcY, z: srcLayer }
  1271. },
  1272. {
  1273. texture: destinationGPU,
  1274. mipLevel: level,
  1275. origin: { x: dstX, y: dstY, z: dstLayer }
  1276. },
  1277. [
  1278. srcWidth,
  1279. srcHeight,
  1280. 1
  1281. ]
  1282. );
  1283. this.device.queue.submit( [ encoder.finish() ] );
  1284. }
  1285. /**
  1286. * Copies the current bound framebuffer to the given texture.
  1287. *
  1288. * @param {Texture} texture - The destination texture.
  1289. * @param {RenderContext} renderContext - The render context.
  1290. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  1291. */
  1292. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  1293. const renderContextData = this.get( renderContext );
  1294. let sourceGPU = null;
  1295. if ( renderContext.renderTarget ) {
  1296. if ( texture.isDepthTexture ) {
  1297. sourceGPU = this.get( renderContext.depthTexture ).texture;
  1298. } else {
  1299. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  1300. }
  1301. } else {
  1302. if ( texture.isDepthTexture ) {
  1303. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  1304. } else {
  1305. sourceGPU = this.context.getCurrentTexture();
  1306. }
  1307. }
  1308. const destinationGPU = this.get( texture ).texture;
  1309. if ( sourceGPU.format !== destinationGPU.format ) {
  1310. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  1311. return;
  1312. }
  1313. let encoder;
  1314. if ( renderContextData.currentPass ) {
  1315. renderContextData.currentPass.end();
  1316. encoder = renderContextData.encoder;
  1317. } else {
  1318. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  1319. }
  1320. encoder.copyTextureToTexture(
  1321. {
  1322. texture: sourceGPU,
  1323. origin: [ rectangle.x, rectangle.y, 0 ],
  1324. },
  1325. {
  1326. texture: destinationGPU
  1327. },
  1328. [
  1329. rectangle.z,
  1330. rectangle.w
  1331. ]
  1332. );
  1333. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  1334. if ( renderContextData.currentPass ) {
  1335. const { descriptor } = renderContextData;
  1336. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  1337. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  1338. }
  1339. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  1340. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  1341. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  1342. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  1343. if ( renderContext.viewport ) {
  1344. this.updateViewport( renderContext );
  1345. }
  1346. if ( renderContext.scissor ) {
  1347. const { x, y, width, height } = renderContext.scissorValue;
  1348. renderContextData.currentPass.setScissorRect( x, y, width, height );
  1349. }
  1350. } else {
  1351. this.device.queue.submit( [ encoder.finish() ] );
  1352. }
  1353. }
  1354. }
  1355. export default WebGPUBackend;
粤ICP备19079148号