WebGPUBackend.js 63 KB

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