1
0

WebGPUBackend.js 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458
  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. import WebGPUTimestampQueryPool from './utils/WebGPUTimestampQueryPool.js';
  14. import { warnOnce } from '../../utils.js';
  15. import { ColorManagement } from '../../math/ColorManagement.js';
  16. /**
  17. * A backend implementation targeting WebGPU.
  18. *
  19. * @private
  20. * @augments Backend
  21. */
  22. class WebGPUBackend extends Backend {
  23. /**
  24. * WebGPUBackend options.
  25. *
  26. * @typedef {Object} WebGPUBackend~Options
  27. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  28. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  29. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  30. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  31. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  32. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  33. * @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.
  34. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  35. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  36. * @property {string} [powerPreference=undefined] - The power preference.
  37. * @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.
  38. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  39. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  40. */
  41. /**
  42. * Constructs a new WebGPU backend.
  43. *
  44. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  45. */
  46. constructor( parameters = {} ) {
  47. super( parameters );
  48. /**
  49. * This flag can be used for type testing.
  50. *
  51. * @type {boolean}
  52. * @readonly
  53. * @default true
  54. */
  55. this.isWebGPUBackend = true;
  56. // some parameters require default values other than "undefined"
  57. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  58. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  59. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  60. /**
  61. * Indicates whether the backend is in compatibility mode or not.
  62. * @type {boolean}
  63. * @default false
  64. */
  65. this.compatibilityMode = this.parameters.compatibilityMode;
  66. /**
  67. * A reference to the device.
  68. *
  69. * @type {?GPUDevice}
  70. * @default null
  71. */
  72. this.device = null;
  73. /**
  74. * A reference to the context.
  75. *
  76. * @type {?GPUCanvasContext}
  77. * @default null
  78. */
  79. this.context = null;
  80. /**
  81. * A reference to the color attachment of the default framebuffer.
  82. *
  83. * @type {?GPUTexture}
  84. * @default null
  85. */
  86. this.colorBuffer = null;
  87. /**
  88. * A reference to the default render pass descriptor.
  89. *
  90. * @type {?Object}
  91. * @default null
  92. */
  93. this.defaultRenderPassdescriptor = null;
  94. /**
  95. * A reference to a backend module holding common utility functions.
  96. *
  97. * @type {WebGPUUtils}
  98. */
  99. this.utils = new WebGPUUtils( this );
  100. /**
  101. * A reference to a backend module holding shader attribute-related
  102. * utility functions.
  103. *
  104. * @type {WebGPUAttributeUtils}
  105. */
  106. this.attributeUtils = new WebGPUAttributeUtils( this );
  107. /**
  108. * A reference to a backend module holding shader binding-related
  109. * utility functions.
  110. *
  111. * @type {WebGPUBindingUtils}
  112. */
  113. this.bindingUtils = new WebGPUBindingUtils( this );
  114. /**
  115. * A reference to a backend module holding shader pipeline-related
  116. * utility functions.
  117. *
  118. * @type {WebGPUPipelineUtils}
  119. */
  120. this.pipelineUtils = new WebGPUPipelineUtils( this );
  121. /**
  122. * A reference to a backend module holding shader texture-related
  123. * utility functions.
  124. *
  125. * @type {WebGPUTextureUtils}
  126. */
  127. this.textureUtils = new WebGPUTextureUtils( this );
  128. /**
  129. * A map that manages the resolve buffers for occlusion queries.
  130. *
  131. * @type {Map<number,GPUBuffer>}
  132. */
  133. this.occludedResolveCache = new Map();
  134. }
  135. /**
  136. * Initializes the backend so it is ready for usage.
  137. *
  138. * @async
  139. * @param {Renderer} renderer - The renderer.
  140. * @return {Promise} A Promise that resolves when the backend has been initialized.
  141. */
  142. async init( renderer ) {
  143. await super.init( renderer );
  144. //
  145. const parameters = this.parameters;
  146. // create the device if it is not passed with parameters
  147. let device;
  148. if ( parameters.device === undefined ) {
  149. const adapterOptions = {
  150. powerPreference: parameters.powerPreference,
  151. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  152. };
  153. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  154. if ( adapter === null ) {
  155. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  156. }
  157. // feature support
  158. const features = Object.values( GPUFeatureName );
  159. const supportedFeatures = [];
  160. for ( const name of features ) {
  161. if ( adapter.features.has( name ) ) {
  162. supportedFeatures.push( name );
  163. }
  164. }
  165. const deviceDescriptor = {
  166. requiredFeatures: supportedFeatures,
  167. requiredLimits: parameters.requiredLimits
  168. };
  169. device = await adapter.requestDevice( deviceDescriptor );
  170. } else {
  171. device = parameters.device;
  172. }
  173. device.lost.then( ( info ) => {
  174. const deviceLossInfo = {
  175. api: 'WebGPU',
  176. message: info.message || 'Unknown reason',
  177. reason: info.reason || null,
  178. originalEvent: info
  179. };
  180. renderer.onDeviceLost( deviceLossInfo );
  181. } );
  182. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  183. this.device = device;
  184. this.context = context;
  185. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  186. const toneMappingMode = ColorManagement.getToneMappingMode( this.renderer.outputColorSpace );
  187. this.context.configure( {
  188. device: this.device,
  189. format: this.utils.getPreferredCanvasFormat(),
  190. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  191. alphaMode: alphaMode,
  192. toneMapping: {
  193. mode: toneMappingMode
  194. }
  195. } );
  196. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  197. this.updateSize();
  198. }
  199. /**
  200. * The coordinate system of the backend.
  201. *
  202. * @type {number}
  203. * @readonly
  204. */
  205. get coordinateSystem() {
  206. return WebGPUCoordinateSystem;
  207. }
  208. /**
  209. * This method performs a readback operation by moving buffer data from
  210. * a storage buffer attribute from the GPU to the CPU.
  211. *
  212. * @async
  213. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  214. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  215. */
  216. async getArrayBufferAsync( attribute ) {
  217. return await this.attributeUtils.getArrayBufferAsync( attribute );
  218. }
  219. /**
  220. * Returns the backend's rendering context.
  221. *
  222. * @return {GPUCanvasContext} The rendering context.
  223. */
  224. getContext() {
  225. return this.context;
  226. }
  227. /**
  228. * Returns the default render pass descriptor.
  229. *
  230. * In WebGPU, the default framebuffer must be configured
  231. * like custom framebuffers so the backend needs a render
  232. * pass descriptor even when rendering directly to screen.
  233. *
  234. * @private
  235. * @return {Object} The render pass descriptor.
  236. */
  237. _getDefaultRenderPassDescriptor() {
  238. let descriptor = this.defaultRenderPassdescriptor;
  239. if ( descriptor === null ) {
  240. const renderer = this.renderer;
  241. descriptor = {
  242. colorAttachments: [ {
  243. view: null
  244. } ],
  245. };
  246. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  247. descriptor.depthStencilAttachment = {
  248. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  249. };
  250. }
  251. const colorAttachment = descriptor.colorAttachments[ 0 ];
  252. if ( this.renderer.samples > 0 ) {
  253. colorAttachment.view = this.colorBuffer.createView();
  254. } else {
  255. colorAttachment.resolveTarget = undefined;
  256. }
  257. this.defaultRenderPassdescriptor = descriptor;
  258. }
  259. const colorAttachment = descriptor.colorAttachments[ 0 ];
  260. if ( this.renderer.samples > 0 ) {
  261. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  262. } else {
  263. colorAttachment.view = this.context.getCurrentTexture().createView();
  264. }
  265. return descriptor;
  266. }
  267. /**
  268. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  269. *
  270. * @param {RenderContext} renderContext - The render context.
  271. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  272. *
  273. * @private
  274. */
  275. _isRenderCameraDepthArray( renderContext ) {
  276. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  277. }
  278. /**
  279. * Returns the render pass descriptor for the given render context.
  280. *
  281. * @private
  282. * @param {RenderContext} renderContext - The render context.
  283. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  284. * @return {Object} The render pass descriptor.
  285. */
  286. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  287. const renderTarget = renderContext.renderTarget;
  288. const renderTargetData = this.get( renderTarget );
  289. let descriptors = renderTargetData.descriptors;
  290. if ( descriptors === undefined ||
  291. renderTargetData.width !== renderTarget.width ||
  292. renderTargetData.height !== renderTarget.height ||
  293. renderTargetData.dimensions !== renderTarget.dimensions ||
  294. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  295. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  296. renderTargetData.samples !== renderTarget.samples
  297. ) {
  298. descriptors = {};
  299. renderTargetData.descriptors = descriptors;
  300. // dispose
  301. const onDispose = () => {
  302. renderTarget.removeEventListener( 'dispose', onDispose );
  303. this.delete( renderTarget );
  304. };
  305. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  306. renderTarget.addEventListener( 'dispose', onDispose );
  307. }
  308. }
  309. const cacheKey = renderContext.getCacheKey();
  310. let descriptorBase = descriptors[ cacheKey ];
  311. if ( descriptorBase === undefined ) {
  312. const textures = renderContext.textures;
  313. const textureViews = [];
  314. let sliceIndex;
  315. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  316. for ( let i = 0; i < textures.length; i ++ ) {
  317. const textureData = this.get( textures[ i ] );
  318. const viewDescriptor = {
  319. label: `colorAttachment_${ i }`,
  320. baseMipLevel: renderContext.activeMipmapLevel,
  321. mipLevelCount: 1,
  322. baseArrayLayer: renderContext.activeCubeFace,
  323. arrayLayerCount: 1,
  324. dimension: GPUTextureViewDimension.TwoD
  325. };
  326. if ( renderTarget.isRenderTarget3D ) {
  327. sliceIndex = renderContext.activeCubeFace;
  328. viewDescriptor.baseArrayLayer = 0;
  329. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  330. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  331. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  332. if ( isRenderCameraDepthArray === true ) {
  333. const cameras = renderContext.camera.cameras;
  334. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  335. const layerViewDescriptor = {
  336. ...viewDescriptor,
  337. baseArrayLayer: layer,
  338. arrayLayerCount: 1,
  339. dimension: GPUTextureViewDimension.TwoD
  340. };
  341. const textureView = textureData.texture.createView( layerViewDescriptor );
  342. textureViews.push( {
  343. view: textureView,
  344. resolveTarget: undefined,
  345. depthSlice: undefined
  346. } );
  347. }
  348. } else {
  349. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  350. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  351. }
  352. }
  353. if ( isRenderCameraDepthArray !== true ) {
  354. const textureView = textureData.texture.createView( viewDescriptor );
  355. let view, resolveTarget;
  356. if ( textureData.msaaTexture !== undefined ) {
  357. view = textureData.msaaTexture.createView();
  358. resolveTarget = textureView;
  359. } else {
  360. view = textureView;
  361. resolveTarget = undefined;
  362. }
  363. textureViews.push( {
  364. view,
  365. resolveTarget,
  366. depthSlice: sliceIndex
  367. } );
  368. }
  369. }
  370. descriptorBase = { textureViews };
  371. if ( renderContext.depth ) {
  372. const depthTextureData = this.get( renderContext.depthTexture );
  373. const options = {};
  374. if ( renderContext.depthTexture.isArrayTexture ) {
  375. options.dimension = GPUTextureViewDimension.TwoD;
  376. options.arrayLayerCount = 1;
  377. options.baseArrayLayer = renderContext.activeCubeFace;
  378. }
  379. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  380. }
  381. descriptors[ cacheKey ] = descriptorBase;
  382. renderTargetData.width = renderTarget.width;
  383. renderTargetData.height = renderTarget.height;
  384. renderTargetData.samples = renderTarget.samples;
  385. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  386. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  387. renderTargetData.dimensions = renderTarget.dimensions;
  388. }
  389. const descriptor = {
  390. colorAttachments: []
  391. };
  392. // Apply dynamic properties to cached views
  393. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  394. const viewInfo = descriptorBase.textureViews[ i ];
  395. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  396. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  397. clearValue = colorAttachmentsConfig.clearValue;
  398. }
  399. descriptor.colorAttachments.push( {
  400. view: viewInfo.view,
  401. depthSlice: viewInfo.depthSlice,
  402. resolveTarget: viewInfo.resolveTarget,
  403. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  404. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  405. clearValue: clearValue
  406. } );
  407. }
  408. if ( descriptorBase.depthStencilView ) {
  409. descriptor.depthStencilAttachment = {
  410. view: descriptorBase.depthStencilView
  411. };
  412. }
  413. return descriptor;
  414. }
  415. /**
  416. * This method is executed at the beginning of a render call and prepares
  417. * the WebGPU state for upcoming render calls
  418. *
  419. * @param {RenderContext} renderContext - The render context.
  420. */
  421. beginRender( renderContext ) {
  422. const renderContextData = this.get( renderContext );
  423. const device = this.device;
  424. const occlusionQueryCount = renderContext.occlusionQueryCount;
  425. let occlusionQuerySet;
  426. if ( occlusionQueryCount > 0 ) {
  427. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  428. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  429. // Get a reference to the array of objects with queries. The renderContextData property
  430. // can be changed by another render pass before the buffer.mapAsyc() completes.
  431. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  432. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  433. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  434. //
  435. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  436. renderContextData.occlusionQuerySet = occlusionQuerySet;
  437. renderContextData.occlusionQueryIndex = 0;
  438. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  439. renderContextData.lastOcclusionObject = null;
  440. }
  441. let descriptor;
  442. if ( renderContext.textures === null ) {
  443. descriptor = this._getDefaultRenderPassDescriptor();
  444. } else {
  445. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  446. }
  447. this.initTimestampQuery( renderContext, descriptor );
  448. descriptor.occlusionQuerySet = occlusionQuerySet;
  449. const depthStencilAttachment = descriptor.depthStencilAttachment;
  450. if ( renderContext.textures !== null ) {
  451. const colorAttachments = descriptor.colorAttachments;
  452. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  453. const colorAttachment = colorAttachments[ i ];
  454. if ( renderContext.clearColor ) {
  455. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  456. colorAttachment.loadOp = GPULoadOp.Clear;
  457. } else {
  458. colorAttachment.loadOp = GPULoadOp.Load;
  459. }
  460. colorAttachment.storeOp = GPUStoreOp.Store;
  461. }
  462. } else {
  463. const colorAttachment = descriptor.colorAttachments[ 0 ];
  464. if ( renderContext.clearColor ) {
  465. colorAttachment.clearValue = renderContext.clearColorValue;
  466. colorAttachment.loadOp = GPULoadOp.Clear;
  467. } else {
  468. colorAttachment.loadOp = GPULoadOp.Load;
  469. }
  470. colorAttachment.storeOp = GPUStoreOp.Store;
  471. }
  472. //
  473. if ( renderContext.depth ) {
  474. if ( renderContext.clearDepth ) {
  475. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  476. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  477. } else {
  478. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  479. }
  480. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  481. }
  482. if ( renderContext.stencil ) {
  483. if ( renderContext.clearStencil ) {
  484. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  485. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  486. } else {
  487. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  488. }
  489. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  490. }
  491. //
  492. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  493. // shadow arrays - prepare bundle encoders for each camera in an array camera
  494. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  495. const cameras = renderContext.camera.cameras;
  496. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  497. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  498. } else {
  499. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  500. }
  501. // Create bundle encoders for each layer
  502. renderContextData.bundleEncoders = [];
  503. renderContextData.bundleSets = [];
  504. // Create separate bundle encoders for each camera in the array
  505. for ( let i = 0; i < cameras.length; i ++ ) {
  506. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  507. renderContext,
  508. 'renderBundleArrayCamera_' + i
  509. );
  510. // Initialize state tracking for this bundle
  511. const bundleSets = {
  512. attributes: {},
  513. bindingGroups: [],
  514. pipeline: null,
  515. index: null
  516. };
  517. renderContextData.bundleEncoders.push( bundleEncoder );
  518. renderContextData.bundleSets.push( bundleSets );
  519. }
  520. // We'll complete the bundles in finishRender
  521. renderContextData.currentPass = null;
  522. } else {
  523. const currentPass = encoder.beginRenderPass( descriptor );
  524. renderContextData.currentPass = currentPass;
  525. if ( renderContext.viewport ) {
  526. this.updateViewport( renderContext );
  527. }
  528. if ( renderContext.scissor ) {
  529. const { x, y, width, height } = renderContext.scissorValue;
  530. currentPass.setScissorRect( x, y, width, height );
  531. }
  532. }
  533. //
  534. renderContextData.descriptor = descriptor;
  535. renderContextData.encoder = encoder;
  536. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  537. renderContextData.renderBundles = [];
  538. }
  539. /**
  540. * This method creates layer descriptors for each camera in an array camera
  541. * to prepare for rendering to a depth array texture.
  542. *
  543. * @param {RenderContext} renderContext - The render context.
  544. * @param {Object} renderContextData - The render context data.
  545. * @param {Object} descriptor - The render pass descriptor.
  546. * @param {ArrayCamera} cameras - The array camera.
  547. *
  548. * @private
  549. */
  550. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  551. const depthStencilAttachment = descriptor.depthStencilAttachment;
  552. renderContextData.layerDescriptors = [];
  553. const depthTextureData = this.get( renderContext.depthTexture );
  554. if ( ! depthTextureData.viewCache ) {
  555. depthTextureData.viewCache = [];
  556. }
  557. for ( let i = 0; i < cameras.length; i ++ ) {
  558. const layerDescriptor = {
  559. ...descriptor,
  560. colorAttachments: [ {
  561. ...descriptor.colorAttachments[ 0 ],
  562. view: descriptor.colorAttachments[ i ].view
  563. } ]
  564. };
  565. if ( descriptor.depthStencilAttachment ) {
  566. const layerIndex = i;
  567. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  568. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  569. dimension: GPUTextureViewDimension.TwoD,
  570. baseArrayLayer: i,
  571. arrayLayerCount: 1
  572. } );
  573. }
  574. layerDescriptor.depthStencilAttachment = {
  575. view: depthTextureData.viewCache[ layerIndex ],
  576. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  577. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  578. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  579. };
  580. if ( renderContext.stencil ) {
  581. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  582. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  583. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  584. }
  585. } else {
  586. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  587. }
  588. renderContextData.layerDescriptors.push( layerDescriptor );
  589. }
  590. }
  591. /**
  592. * This method updates the layer descriptors for each camera in an array camera
  593. * to prepare for rendering to a depth array texture.
  594. *
  595. * @param {RenderContext} renderContext - The render context.
  596. * @param {Object} renderContextData - The render context data.
  597. * @param {ArrayCamera} cameras - The array camera.
  598. *
  599. */
  600. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  601. for ( let i = 0; i < cameras.length; i ++ ) {
  602. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  603. if ( layerDescriptor.depthStencilAttachment ) {
  604. const depthAttachment = layerDescriptor.depthStencilAttachment;
  605. if ( renderContext.depth ) {
  606. if ( renderContext.clearDepth ) {
  607. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  608. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  609. } else {
  610. depthAttachment.depthLoadOp = GPULoadOp.Load;
  611. }
  612. }
  613. if ( renderContext.stencil ) {
  614. if ( renderContext.clearStencil ) {
  615. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  616. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  617. } else {
  618. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  619. }
  620. }
  621. }
  622. }
  623. }
  624. /**
  625. * This method is executed at the end of a render call and finalizes work
  626. * after draw calls.
  627. *
  628. * @param {RenderContext} renderContext - The render context.
  629. */
  630. finishRender( renderContext ) {
  631. const renderContextData = this.get( renderContext );
  632. const occlusionQueryCount = renderContext.occlusionQueryCount;
  633. if ( renderContextData.renderBundles.length > 0 ) {
  634. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  635. }
  636. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  637. renderContextData.currentPass.endOcclusionQuery();
  638. }
  639. // shadow arrays - Execute bundles for each layer
  640. const encoder = renderContextData.encoder;
  641. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  642. const bundles = [];
  643. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  644. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  645. bundles.push( bundleEncoder.finish() );
  646. }
  647. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  648. if ( i < bundles.length ) {
  649. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  650. const renderPass = encoder.beginRenderPass( layerDescriptor );
  651. if ( renderContext.viewport ) {
  652. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  653. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  654. }
  655. if ( renderContext.scissor ) {
  656. const { x, y, width, height } = renderContext.scissorValue;
  657. renderPass.setScissorRect( x, y, width, height );
  658. }
  659. renderPass.executeBundles( [ bundles[ i ] ] );
  660. renderPass.end();
  661. }
  662. }
  663. } else if ( renderContextData.currentPass ) {
  664. renderContextData.currentPass.end();
  665. }
  666. if ( occlusionQueryCount > 0 ) {
  667. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  668. //
  669. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  670. if ( queryResolveBuffer === undefined ) {
  671. queryResolveBuffer = this.device.createBuffer(
  672. {
  673. size: bufferSize,
  674. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  675. }
  676. );
  677. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  678. }
  679. //
  680. const readBuffer = this.device.createBuffer(
  681. {
  682. size: bufferSize,
  683. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  684. }
  685. );
  686. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  687. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  688. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  689. renderContextData.occlusionQueryBuffer = readBuffer;
  690. //
  691. this.resolveOccludedAsync( renderContext );
  692. }
  693. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  694. //
  695. if ( renderContext.textures !== null ) {
  696. const textures = renderContext.textures;
  697. for ( let i = 0; i < textures.length; i ++ ) {
  698. const texture = textures[ i ];
  699. if ( texture.generateMipmaps === true ) {
  700. this.textureUtils.generateMipmaps( texture );
  701. }
  702. }
  703. }
  704. }
  705. /**
  706. * Returns `true` if the given 3D object is fully occluded by other
  707. * 3D objects in the scene.
  708. *
  709. * @param {RenderContext} renderContext - The render context.
  710. * @param {Object3D} object - The 3D object to test.
  711. * @return {boolean} Whether the 3D object is fully occluded or not.
  712. */
  713. isOccluded( renderContext, object ) {
  714. const renderContextData = this.get( renderContext );
  715. return renderContextData.occluded && renderContextData.occluded.has( object );
  716. }
  717. /**
  718. * This method processes the result of occlusion queries and writes it
  719. * into render context data.
  720. *
  721. * @async
  722. * @param {RenderContext} renderContext - The render context.
  723. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  724. */
  725. async resolveOccludedAsync( renderContext ) {
  726. const renderContextData = this.get( renderContext );
  727. // handle occlusion query results
  728. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  729. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  730. const occluded = new WeakSet();
  731. renderContextData.currentOcclusionQueryObjects = null;
  732. renderContextData.currentOcclusionQueryBuffer = null;
  733. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  734. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  735. const results = new BigUint64Array( buffer );
  736. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  737. if ( results[ i ] === BigInt( 0 ) ) {
  738. occluded.add( currentOcclusionQueryObjects[ i ] );
  739. }
  740. }
  741. currentOcclusionQueryBuffer.destroy();
  742. renderContextData.occluded = occluded;
  743. }
  744. }
  745. /**
  746. * Updates the viewport with the values from the given render context.
  747. *
  748. * @param {RenderContext} renderContext - The render context.
  749. */
  750. updateViewport( renderContext ) {
  751. const { currentPass } = this.get( renderContext );
  752. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  753. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  754. }
  755. /**
  756. * Returns the clear color and alpha into a single
  757. * color object.
  758. *
  759. * @return {Color4} The clear color.
  760. */
  761. getClearColor() {
  762. const clearColor = super.getClearColor();
  763. // only premultiply alpha when alphaMode is "premultiplied"
  764. if ( this.renderer.alpha === true ) {
  765. clearColor.r *= clearColor.a;
  766. clearColor.g *= clearColor.a;
  767. clearColor.b *= clearColor.a;
  768. }
  769. return clearColor;
  770. }
  771. /**
  772. * Performs a clear operation.
  773. *
  774. * @param {boolean} color - Whether the color buffer should be cleared or not.
  775. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  776. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  777. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  778. */
  779. clear( color, depth, stencil, renderTargetContext = null ) {
  780. const device = this.device;
  781. const renderer = this.renderer;
  782. let colorAttachments = [];
  783. let depthStencilAttachment;
  784. let clearValue;
  785. let supportsDepth;
  786. let supportsStencil;
  787. if ( color ) {
  788. const clearColor = this.getClearColor();
  789. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  790. }
  791. if ( renderTargetContext === null ) {
  792. supportsDepth = renderer.depth;
  793. supportsStencil = renderer.stencil;
  794. const descriptor = this._getDefaultRenderPassDescriptor();
  795. if ( color ) {
  796. colorAttachments = descriptor.colorAttachments;
  797. const colorAttachment = colorAttachments[ 0 ];
  798. colorAttachment.clearValue = clearValue;
  799. colorAttachment.loadOp = GPULoadOp.Clear;
  800. colorAttachment.storeOp = GPUStoreOp.Store;
  801. }
  802. if ( supportsDepth || supportsStencil ) {
  803. depthStencilAttachment = descriptor.depthStencilAttachment;
  804. }
  805. } else {
  806. supportsDepth = renderTargetContext.depth;
  807. supportsStencil = renderTargetContext.stencil;
  808. const clearConfig = {
  809. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  810. clearValue: color ? clearValue : undefined
  811. };
  812. if ( supportsDepth ) {
  813. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  814. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  815. clearConfig.depthStoreOp = GPUStoreOp.Store;
  816. }
  817. if ( supportsStencil ) {
  818. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  819. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  820. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  821. }
  822. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  823. colorAttachments = descriptor.colorAttachments;
  824. depthStencilAttachment = descriptor.depthStencilAttachment;
  825. }
  826. if ( supportsDepth && depthStencilAttachment ) {
  827. if ( depth ) {
  828. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  829. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  830. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  831. } else {
  832. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  833. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  834. }
  835. }
  836. //
  837. if ( supportsStencil && depthStencilAttachment ) {
  838. if ( stencil ) {
  839. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  840. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  841. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  842. } else {
  843. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  844. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  845. }
  846. }
  847. //
  848. const encoder = device.createCommandEncoder( { label: 'clear' } );
  849. const currentPass = encoder.beginRenderPass( {
  850. colorAttachments,
  851. depthStencilAttachment
  852. } );
  853. currentPass.end();
  854. device.queue.submit( [ encoder.finish() ] );
  855. }
  856. // compute
  857. /**
  858. * This method is executed at the beginning of a compute call and
  859. * prepares the state for upcoming compute tasks.
  860. *
  861. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  862. */
  863. beginCompute( computeGroup ) {
  864. const groupGPU = this.get( computeGroup );
  865. const descriptor = {
  866. label: 'computeGroup_' + computeGroup.id
  867. };
  868. this.initTimestampQuery( 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( 'THREE.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. return [
  1181. material.transparent, material.blending, material.premultipliedAlpha,
  1182. material.blendSrc, material.blendDst, material.blendEquation,
  1183. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  1184. material.colorWrite,
  1185. material.depthWrite, material.depthTest, material.depthFunc,
  1186. material.stencilWrite, material.stencilFunc,
  1187. material.stencilFail, material.stencilZFail, material.stencilZPass,
  1188. material.stencilFuncMask, material.stencilWriteMask,
  1189. material.side,
  1190. utils.getSampleCountRenderContext( renderContext ),
  1191. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  1192. utils.getPrimitiveTopology( object, material ),
  1193. renderObject.getGeometryCacheKey(),
  1194. renderObject.clippingContextCacheKey
  1195. ].join();
  1196. }
  1197. // textures
  1198. /**
  1199. * Creates a GPU sampler for the given texture.
  1200. *
  1201. * @param {Texture} texture - The texture to create the sampler for.
  1202. */
  1203. createSampler( texture ) {
  1204. this.textureUtils.createSampler( texture );
  1205. }
  1206. /**
  1207. * Destroys the GPU sampler for the given texture.
  1208. *
  1209. * @param {Texture} texture - The texture to destroy the sampler for.
  1210. */
  1211. destroySampler( texture ) {
  1212. this.textureUtils.destroySampler( texture );
  1213. }
  1214. /**
  1215. * Creates a default texture for the given texture that can be used
  1216. * as a placeholder until the actual texture is ready for usage.
  1217. *
  1218. * @param {Texture} texture - The texture to create a default texture for.
  1219. */
  1220. createDefaultTexture( texture ) {
  1221. this.textureUtils.createDefaultTexture( texture );
  1222. }
  1223. /**
  1224. * Defines a texture on the GPU for the given texture object.
  1225. *
  1226. * @param {Texture} texture - The texture.
  1227. * @param {Object} [options={}] - Optional configuration parameter.
  1228. */
  1229. createTexture( texture, options ) {
  1230. this.textureUtils.createTexture( texture, options );
  1231. }
  1232. /**
  1233. * Uploads the updated texture data to the GPU.
  1234. *
  1235. * @param {Texture} texture - The texture.
  1236. * @param {Object} [options={}] - Optional configuration parameter.
  1237. */
  1238. updateTexture( texture, options ) {
  1239. this.textureUtils.updateTexture( texture, options );
  1240. }
  1241. /**
  1242. * Generates mipmaps for the given texture.
  1243. *
  1244. * @param {Texture} texture - The texture.
  1245. */
  1246. generateMipmaps( texture ) {
  1247. this.textureUtils.generateMipmaps( texture );
  1248. }
  1249. /**
  1250. * Destroys the GPU data for the given texture object.
  1251. *
  1252. * @param {Texture} texture - The texture.
  1253. */
  1254. destroyTexture( texture ) {
  1255. this.textureUtils.destroyTexture( texture );
  1256. }
  1257. /**
  1258. * Returns texture data as a typed array.
  1259. *
  1260. * @async
  1261. * @param {Texture} texture - The texture to copy.
  1262. * @param {number} x - The x coordinate of the copy origin.
  1263. * @param {number} y - The y coordinate of the copy origin.
  1264. * @param {number} width - The width of the copy.
  1265. * @param {number} height - The height of the copy.
  1266. * @param {number} faceIndex - The face index.
  1267. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  1268. */
  1269. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  1270. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  1271. }
  1272. /**
  1273. * Inits a time stamp query for the given render context.
  1274. *
  1275. * @param {RenderContext} renderContext - The render context.
  1276. * @param {Object} descriptor - The query descriptor.
  1277. */
  1278. initTimestampQuery( renderContext, descriptor ) {
  1279. if ( ! this.trackTimestamp ) return;
  1280. const type = renderContext.isComputeNode ? 'compute' : 'render';
  1281. if ( ! this.timestampQueryPool[ type ] ) {
  1282. // TODO: Variable maxQueries?
  1283. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  1284. }
  1285. const timestampQueryPool = this.timestampQueryPool[ type ];
  1286. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  1287. descriptor.timestampWrites = {
  1288. querySet: timestampQueryPool.querySet,
  1289. beginningOfPassWriteIndex: baseOffset,
  1290. endOfPassWriteIndex: baseOffset + 1,
  1291. };
  1292. }
  1293. // node builder
  1294. /**
  1295. * Returns a node builder for the given render object.
  1296. *
  1297. * @param {RenderObject} object - The render object.
  1298. * @param {Renderer} renderer - The renderer.
  1299. * @return {WGSLNodeBuilder} The node builder.
  1300. */
  1301. createNodeBuilder( object, renderer ) {
  1302. return new WGSLNodeBuilder( object, renderer );
  1303. }
  1304. // program
  1305. /**
  1306. * Creates a shader program from the given programmable stage.
  1307. *
  1308. * @param {ProgrammableStage} program - The programmable stage.
  1309. */
  1310. createProgram( program ) {
  1311. const programGPU = this.get( program );
  1312. programGPU.module = {
  1313. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  1314. entryPoint: 'main'
  1315. };
  1316. }
  1317. /**
  1318. * Destroys the shader program of the given programmable stage.
  1319. *
  1320. * @param {ProgrammableStage} program - The programmable stage.
  1321. */
  1322. destroyProgram( program ) {
  1323. this.delete( program );
  1324. }
  1325. // pipelines
  1326. /**
  1327. * Creates a render pipeline for the given render object.
  1328. *
  1329. * @param {RenderObject} renderObject - The render object.
  1330. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  1331. */
  1332. createRenderPipeline( renderObject, promises ) {
  1333. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  1334. }
  1335. /**
  1336. * Creates a compute pipeline for the given compute node.
  1337. *
  1338. * @param {ComputePipeline} computePipeline - The compute pipeline.
  1339. * @param {Array<BindGroup>} bindings - The bindings.
  1340. */
  1341. createComputePipeline( computePipeline, bindings ) {
  1342. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  1343. }
  1344. /**
  1345. * Prepares the state for encoding render bundles.
  1346. *
  1347. * @param {RenderContext} renderContext - The render context.
  1348. */
  1349. beginBundle( renderContext ) {
  1350. const renderContextData = this.get( renderContext );
  1351. renderContextData._currentPass = renderContextData.currentPass;
  1352. renderContextData._currentSets = renderContextData.currentSets;
  1353. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  1354. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  1355. }
  1356. /**
  1357. * After processing render bundles this method finalizes related work.
  1358. *
  1359. * @param {RenderContext} renderContext - The render context.
  1360. * @param {RenderBundle} bundle - The render bundle.
  1361. */
  1362. finishBundle( renderContext, bundle ) {
  1363. const renderContextData = this.get( renderContext );
  1364. const bundleEncoder = renderContextData.currentPass;
  1365. const bundleGPU = bundleEncoder.finish();
  1366. this.get( bundle ).bundleGPU = bundleGPU;
  1367. // restore render pass state
  1368. renderContextData.currentSets = renderContextData._currentSets;
  1369. renderContextData.currentPass = renderContextData._currentPass;
  1370. }
  1371. /**
  1372. * Adds a render bundle to the render context data.
  1373. *
  1374. * @param {RenderContext} renderContext - The render context.
  1375. * @param {RenderBundle} bundle - The render bundle to add.
  1376. */
  1377. addBundle( renderContext, bundle ) {
  1378. const renderContextData = this.get( renderContext );
  1379. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  1380. }
  1381. // bindings
  1382. /**
  1383. * Creates bindings from the given bind group definition.
  1384. *
  1385. * @param {BindGroup} bindGroup - The bind group.
  1386. * @param {Array<BindGroup>} bindings - Array of bind groups.
  1387. * @param {number} cacheIndex - The cache index.
  1388. * @param {number} version - The version.
  1389. */
  1390. createBindings( bindGroup, bindings, cacheIndex, version ) {
  1391. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  1392. }
  1393. /**
  1394. * Updates the given bind group definition.
  1395. *
  1396. * @param {BindGroup} bindGroup - The bind group.
  1397. * @param {Array<BindGroup>} bindings - Array of bind groups.
  1398. * @param {number} cacheIndex - The cache index.
  1399. * @param {number} version - The version.
  1400. */
  1401. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  1402. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  1403. }
  1404. /**
  1405. * Updates a buffer binding.
  1406. *
  1407. * @param {Buffer} binding - The buffer binding to update.
  1408. */
  1409. updateBinding( binding ) {
  1410. this.bindingUtils.updateBinding( binding );
  1411. }
  1412. // attributes
  1413. /**
  1414. * Creates the buffer of an indexed shader attribute.
  1415. *
  1416. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  1417. */
  1418. createIndexAttribute( attribute ) {
  1419. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  1420. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  1421. usage |= GPUBufferUsage.STORAGE;
  1422. }
  1423. this.attributeUtils.createAttribute( attribute, usage );
  1424. }
  1425. /**
  1426. * Creates the GPU buffer of a shader attribute.
  1427. *
  1428. * @param {BufferAttribute} attribute - The buffer attribute.
  1429. */
  1430. createAttribute( attribute ) {
  1431. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1432. }
  1433. /**
  1434. * Creates the GPU buffer of a storage attribute.
  1435. *
  1436. * @param {BufferAttribute} attribute - The buffer attribute.
  1437. */
  1438. createStorageAttribute( attribute ) {
  1439. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1440. }
  1441. /**
  1442. * Creates the GPU buffer of an indirect storage attribute.
  1443. *
  1444. * @param {BufferAttribute} attribute - The buffer attribute.
  1445. */
  1446. createIndirectStorageAttribute( attribute ) {
  1447. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  1448. }
  1449. /**
  1450. * Updates the GPU buffer of a shader attribute.
  1451. *
  1452. * @param {BufferAttribute} attribute - The buffer attribute to update.
  1453. */
  1454. updateAttribute( attribute ) {
  1455. this.attributeUtils.updateAttribute( attribute );
  1456. }
  1457. /**
  1458. * Destroys the GPU buffer of a shader attribute.
  1459. *
  1460. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  1461. */
  1462. destroyAttribute( attribute ) {
  1463. this.attributeUtils.destroyAttribute( attribute );
  1464. }
  1465. // canvas
  1466. /**
  1467. * Triggers an update of the default render pass descriptor.
  1468. */
  1469. updateSize() {
  1470. this.colorBuffer = this.textureUtils.getColorBuffer();
  1471. this.defaultRenderPassdescriptor = null;
  1472. }
  1473. // utils public
  1474. /**
  1475. * Returns the maximum anisotropy texture filtering value.
  1476. *
  1477. * @return {number} The maximum anisotropy texture filtering value.
  1478. */
  1479. getMaxAnisotropy() {
  1480. return 16;
  1481. }
  1482. /**
  1483. * Checks if the given feature is supported by the backend.
  1484. *
  1485. * @param {string} name - The feature's name.
  1486. * @return {boolean} Whether the feature is supported or not.
  1487. */
  1488. hasFeature( name ) {
  1489. return this.device.features.has( name );
  1490. }
  1491. /**
  1492. * Copies data of the given source texture to the given destination texture.
  1493. *
  1494. * @param {Texture} srcTexture - The source texture.
  1495. * @param {Texture} dstTexture - The destination texture.
  1496. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  1497. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  1498. * @param {number} [srcLevel=0] - The mipmap level to copy.
  1499. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  1500. */
  1501. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  1502. let dstX = 0;
  1503. let dstY = 0;
  1504. let dstZ = 0;
  1505. let srcX = 0;
  1506. let srcY = 0;
  1507. let srcZ = 0;
  1508. let srcWidth = srcTexture.image.width;
  1509. let srcHeight = srcTexture.image.height;
  1510. let srcDepth = 1;
  1511. if ( srcRegion !== null ) {
  1512. if ( srcRegion.isBox3 === true ) {
  1513. srcX = srcRegion.min.x;
  1514. srcY = srcRegion.min.y;
  1515. srcZ = srcRegion.min.z;
  1516. srcWidth = srcRegion.max.x - srcRegion.min.x;
  1517. srcHeight = srcRegion.max.y - srcRegion.min.y;
  1518. srcDepth = srcRegion.max.z - srcRegion.min.z;
  1519. } else {
  1520. // Assume it's a Box2
  1521. srcX = srcRegion.min.x;
  1522. srcY = srcRegion.min.y;
  1523. srcWidth = srcRegion.max.x - srcRegion.min.x;
  1524. srcHeight = srcRegion.max.y - srcRegion.min.y;
  1525. srcDepth = 1;
  1526. }
  1527. }
  1528. if ( dstPosition !== null ) {
  1529. dstX = dstPosition.x;
  1530. dstY = dstPosition.y;
  1531. dstZ = dstPosition.z || 0;
  1532. }
  1533. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  1534. const sourceGPU = this.get( srcTexture ).texture;
  1535. const destinationGPU = this.get( dstTexture ).texture;
  1536. encoder.copyTextureToTexture(
  1537. {
  1538. texture: sourceGPU,
  1539. mipLevel: srcLevel,
  1540. origin: { x: srcX, y: srcY, z: srcZ }
  1541. },
  1542. {
  1543. texture: destinationGPU,
  1544. mipLevel: dstLevel,
  1545. origin: { x: dstX, y: dstY, z: dstZ }
  1546. },
  1547. [
  1548. srcWidth,
  1549. srcHeight,
  1550. srcDepth
  1551. ]
  1552. );
  1553. this.device.queue.submit( [ encoder.finish() ] );
  1554. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  1555. this.textureUtils.generateMipmaps( dstTexture );
  1556. }
  1557. }
  1558. /**
  1559. * Copies the current bound framebuffer to the given texture.
  1560. *
  1561. * @param {Texture} texture - The destination texture.
  1562. * @param {RenderContext} renderContext - The render context.
  1563. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  1564. */
  1565. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  1566. const renderContextData = this.get( renderContext );
  1567. let sourceGPU = null;
  1568. if ( renderContext.renderTarget ) {
  1569. if ( texture.isDepthTexture ) {
  1570. sourceGPU = this.get( renderContext.depthTexture ).texture;
  1571. } else {
  1572. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  1573. }
  1574. } else {
  1575. if ( texture.isDepthTexture ) {
  1576. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  1577. } else {
  1578. sourceGPU = this.context.getCurrentTexture();
  1579. }
  1580. }
  1581. const destinationGPU = this.get( texture ).texture;
  1582. if ( sourceGPU.format !== destinationGPU.format ) {
  1583. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  1584. return;
  1585. }
  1586. let encoder;
  1587. if ( renderContextData.currentPass ) {
  1588. renderContextData.currentPass.end();
  1589. encoder = renderContextData.encoder;
  1590. } else {
  1591. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  1592. }
  1593. encoder.copyTextureToTexture(
  1594. {
  1595. texture: sourceGPU,
  1596. origin: [ rectangle.x, rectangle.y, 0 ],
  1597. },
  1598. {
  1599. texture: destinationGPU
  1600. },
  1601. [
  1602. rectangle.z,
  1603. rectangle.w
  1604. ]
  1605. );
  1606. if ( renderContextData.currentPass ) {
  1607. const { descriptor } = renderContextData;
  1608. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  1609. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  1610. }
  1611. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  1612. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  1613. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  1614. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  1615. if ( renderContext.viewport ) {
  1616. this.updateViewport( renderContext );
  1617. }
  1618. if ( renderContext.scissor ) {
  1619. const { x, y, width, height } = renderContext.scissorValue;
  1620. renderContextData.currentPass.setScissorRect( x, y, width, height );
  1621. }
  1622. } else {
  1623. this.device.queue.submit( [ encoder.finish() ] );
  1624. }
  1625. if ( texture.generateMipmaps ) {
  1626. this.textureUtils.generateMipmaps( texture );
  1627. }
  1628. }
  1629. }
  1630. export default WebGPUBackend;
粤ICP备19079148号