WebGPUBackend.js 78 KB

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