WebGPUTextures.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. import { GPUTextureFormat, GPUAddressMode, GPUFilterMode, GPUTextureDimension } from './constants.js';
  2. import { CubeTexture, Texture, NearestFilter, NearestMipmapNearestFilter, NearestMipmapLinearFilter, LinearFilter, RepeatWrapping, MirroredRepeatWrapping,
  3. RGBFormat, RGBAFormat, RedFormat, RGFormat, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, UnsignedByteType, FloatType, HalfFloatType, sRGBEncoding
  4. } from 'three';
  5. import WebGPUTextureUtils from './WebGPUTextureUtils.js';
  6. class WebGPUTextures {
  7. constructor( device, properties, info ) {
  8. this.device = device;
  9. this.properties = properties;
  10. this.info = info;
  11. this.defaultTexture = null;
  12. this.defaultCubeTexture = null;
  13. this.defaultSampler = null;
  14. this.samplerCache = new Map();
  15. this.utils = null;
  16. }
  17. getDefaultSampler() {
  18. if ( this.defaultSampler === null ) {
  19. this.defaultSampler = this.device.createSampler( {} );
  20. }
  21. return this.defaultSampler;
  22. }
  23. getDefaultTexture() {
  24. if ( this.defaultTexture === null ) {
  25. const texture = new Texture();
  26. texture.minFilter = NearestFilter;
  27. texture.magFilter = NearestFilter;
  28. this._uploadTexture( texture );
  29. this.defaultTexture = this.getTextureGPU( texture );
  30. }
  31. return this.defaultTexture;
  32. }
  33. getDefaultCubeTexture() {
  34. if ( this.defaultCubeTexture === null ) {
  35. const texture = new CubeTexture();
  36. texture.minFilter = NearestFilter;
  37. texture.magFilter = NearestFilter;
  38. this._uploadTexture( texture );
  39. this.defaultCubeTexture = this.getTextureGPU( texture );
  40. }
  41. return this.defaultCubeTexture;
  42. }
  43. getTextureGPU( texture ) {
  44. const textureProperties = this.properties.get( texture );
  45. return textureProperties.textureGPU;
  46. }
  47. getSampler( texture ) {
  48. const textureProperties = this.properties.get( texture );
  49. return textureProperties.samplerGPU;
  50. }
  51. updateTexture( texture ) {
  52. let needsUpdate = false;
  53. const textureProperties = this.properties.get( texture );
  54. if ( texture.version > 0 && textureProperties.version !== texture.version ) {
  55. const image = texture.image;
  56. if ( image === undefined ) {
  57. console.warn( 'THREE.WebGPURenderer: Texture marked for update but image is undefined.' );
  58. } else if ( image.complete === false ) {
  59. console.warn( 'THREE.WebGPURenderer: Texture marked for update but image is incomplete.' );
  60. } else {
  61. // texture init
  62. if ( textureProperties.initialized === undefined ) {
  63. textureProperties.initialized = true;
  64. const disposeCallback = onTextureDispose.bind( this );
  65. textureProperties.disposeCallback = disposeCallback;
  66. texture.addEventListener( 'dispose', disposeCallback );
  67. this.info.memory.textures ++;
  68. }
  69. //
  70. needsUpdate = this._uploadTexture( texture );
  71. }
  72. }
  73. // if the texture is used for RTT, it's necessary to init it once so the binding
  74. // group's resource definition points to the respective GPUTexture
  75. if ( textureProperties.initializedRTT === false ) {
  76. textureProperties.initializedRTT = true;
  77. needsUpdate = true;
  78. }
  79. return needsUpdate;
  80. }
  81. updateSampler( texture ) {
  82. const array = [];
  83. array.push( texture.wrapS );
  84. array.push( texture.wrapT );
  85. array.push( texture.wrapR );
  86. array.push( texture.magFilter );
  87. array.push( texture.minFilter );
  88. array.push( texture.anisotropy );
  89. const key = array.join();
  90. let samplerGPU = this.samplerCache.get( key );
  91. if ( samplerGPU === undefined ) {
  92. samplerGPU = this.device.createSampler( {
  93. addressModeU: this._convertAddressMode( texture.wrapS ),
  94. addressModeV: this._convertAddressMode( texture.wrapT ),
  95. addressModeW: this._convertAddressMode( texture.wrapR ),
  96. magFilter: this._convertFilterMode( texture.magFilter ),
  97. minFilter: this._convertFilterMode( texture.minFilter ),
  98. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  99. maxAnisotropy: texture.anisotropy
  100. } );
  101. this.samplerCache.set( key, samplerGPU );
  102. }
  103. const textureProperties = this.properties.get( texture );
  104. textureProperties.samplerGPU = samplerGPU;
  105. }
  106. initRenderTarget( renderTarget ) {
  107. const properties = this.properties;
  108. const renderTargetProperties = properties.get( renderTarget );
  109. if ( renderTargetProperties.initialized === undefined ) {
  110. const device = this.device;
  111. const width = renderTarget.width;
  112. const height = renderTarget.height;
  113. const colorTextureFormat = this._getFormat( renderTarget.texture );
  114. const colorTextureGPU = device.createTexture( {
  115. size: {
  116. width: width,
  117. height: height,
  118. depthOrArrayLayers: 1
  119. },
  120. format: colorTextureFormat,
  121. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  122. } );
  123. this.info.memory.textures ++;
  124. renderTargetProperties.colorTextureGPU = colorTextureGPU;
  125. renderTargetProperties.colorTextureFormat = colorTextureFormat;
  126. // When the ".texture" or ".depthTexture" property of a render target is used as a map,
  127. // the renderer has to find the respective GPUTexture objects to setup the bind groups.
  128. // Since it's not possible to see just from a texture object whether it belongs to a render
  129. // target or not, we need the initializedRTT flag.
  130. const textureProperties = properties.get( renderTarget.texture );
  131. textureProperties.textureGPU = colorTextureGPU;
  132. textureProperties.initializedRTT = false;
  133. if ( renderTarget.depthBuffer === true ) {
  134. const depthTextureFormat = GPUTextureFormat.Depth24PlusStencil8; // @TODO: Make configurable
  135. const depthTextureGPU = device.createTexture( {
  136. size: {
  137. width: width,
  138. height: height,
  139. depthOrArrayLayers: 1
  140. },
  141. format: depthTextureFormat,
  142. usage: GPUTextureUsage.RENDER_ATTACHMENT
  143. } );
  144. this.info.memory.textures ++;
  145. renderTargetProperties.depthTextureGPU = depthTextureGPU;
  146. renderTargetProperties.depthTextureFormat = depthTextureFormat;
  147. if ( renderTarget.depthTexture !== null ) {
  148. const depthTextureProperties = properties.get( renderTarget.depthTexture );
  149. depthTextureProperties.textureGPU = depthTextureGPU;
  150. depthTextureProperties.initializedRTT = false;
  151. }
  152. }
  153. //
  154. const disposeCallback = onRenderTargetDispose.bind( this );
  155. renderTargetProperties.disposeCallback = disposeCallback;
  156. renderTarget.addEventListener( 'dispose', disposeCallback );
  157. //
  158. renderTargetProperties.initialized = true;
  159. }
  160. }
  161. dispose() {
  162. this.samplerCache.clear();
  163. }
  164. _convertAddressMode( value ) {
  165. let addressMode = GPUAddressMode.ClampToEdge;
  166. if ( value === RepeatWrapping ) {
  167. addressMode = GPUAddressMode.Repeat;
  168. } else if ( value === MirroredRepeatWrapping ) {
  169. addressMode = GPUAddressMode.MirrorRepeat;
  170. }
  171. return addressMode;
  172. }
  173. _convertFilterMode( value ) {
  174. let filterMode = GPUFilterMode.Linear;
  175. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  176. filterMode = GPUFilterMode.Nearest;
  177. }
  178. return filterMode;
  179. }
  180. _uploadTexture( texture ) {
  181. let needsUpdate = false;
  182. const device = this.device;
  183. const image = texture.image;
  184. const textureProperties = this.properties.get( texture );
  185. const { width, height, depth } = this._getSize( texture );
  186. const needsMipmaps = this._needsMipmaps( texture );
  187. const dimension = this._getDimension( texture );
  188. const mipLevelCount = this._getMipLevelCount( texture, width, height, needsMipmaps );
  189. const format = this._getFormat( texture );
  190. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST;
  191. if ( needsMipmaps === true ) {
  192. // current mipmap generation requires RENDER_ATTACHMENT
  193. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  194. }
  195. const textureGPUDescriptor = {
  196. size: {
  197. width: width,
  198. height: height,
  199. depthOrArrayLayers: depth,
  200. },
  201. mipLevelCount: mipLevelCount,
  202. sampleCount: 1,
  203. dimension: dimension,
  204. format: format,
  205. usage: usage
  206. };
  207. // texture creation
  208. let textureGPU = textureProperties.textureGPU;
  209. if ( textureGPU === undefined ) {
  210. textureGPU = device.createTexture( textureGPUDescriptor );
  211. textureProperties.textureGPU = textureGPU;
  212. needsUpdate = true;
  213. }
  214. // transfer texture data
  215. if ( texture.isDataTexture || texture.isDataTexture2DArray || texture.isDataTexture3D ) {
  216. this._copyBufferToTexture( image, format, textureGPU );
  217. if ( needsMipmaps === true ) this._generateMipmaps( textureGPU, textureGPUDescriptor );
  218. } else if ( texture.isCompressedTexture ) {
  219. this._copyCompressedBufferToTexture( texture.mipmaps, format, textureGPU );
  220. } else if ( texture.isCubeTexture ) {
  221. this._copyCubeMapToTexture( image, texture, textureGPU );
  222. } else {
  223. if ( image !== undefined ) {
  224. // assume HTMLImageElement, HTMLCanvasElement or ImageBitmap
  225. this._getImageBitmap( image, texture ).then( imageBitmap => {
  226. this._copyExternalImageToTexture( imageBitmap, textureGPU );
  227. if ( needsMipmaps === true ) this._generateMipmaps( textureGPU, textureGPUDescriptor );
  228. } );
  229. }
  230. }
  231. textureProperties.version = texture.version;
  232. return needsUpdate;
  233. }
  234. _copyBufferToTexture( image, format, textureGPU ) {
  235. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  236. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  237. const data = image.data;
  238. const bytesPerTexel = this._getBytesPerTexel( format );
  239. const bytesPerRow = Math.ceil( image.width * bytesPerTexel / 256 ) * 256;
  240. this.device.queue.writeTexture(
  241. {
  242. texture: textureGPU,
  243. mipLevel: 0
  244. },
  245. data,
  246. {
  247. offset: 0,
  248. bytesPerRow
  249. },
  250. {
  251. width: image.width,
  252. height: image.height,
  253. depthOrArrayLayers: ( image.depth !== undefined ) ? image.depth : 1
  254. } );
  255. }
  256. _copyCubeMapToTexture( images, texture, textureGPU ) {
  257. for ( let i = 0; i < images.length; i ++ ) {
  258. const image = images[ i ];
  259. this._getImageBitmap( image, texture ).then( imageBitmap => {
  260. this._copyExternalImageToTexture( imageBitmap, textureGPU, { x: 0, y: 0, z: i } );
  261. } );
  262. }
  263. }
  264. _copyExternalImageToTexture( image, textureGPU, origin = { x: 0, y: 0, z: 0 } ) {
  265. this.device.queue.copyExternalImageToTexture(
  266. {
  267. source: image
  268. }, {
  269. texture: textureGPU,
  270. mipLevel: 0,
  271. origin: origin
  272. }, {
  273. width: image.width,
  274. height: image.height,
  275. depthOrArrayLayers: 1
  276. }
  277. );
  278. }
  279. _copyCompressedBufferToTexture( mipmaps, format, textureGPU ) {
  280. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  281. const blockData = this._getBlockData( format );
  282. for ( let i = 0; i < mipmaps.length; i ++ ) {
  283. const mipmap = mipmaps[ i ];
  284. const width = mipmap.width;
  285. const height = mipmap.height;
  286. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  287. this.device.queue.writeTexture(
  288. {
  289. texture: textureGPU,
  290. mipLevel: i
  291. },
  292. mipmap.data,
  293. {
  294. offset: 0,
  295. bytesPerRow
  296. },
  297. {
  298. width: Math.ceil( width / blockData.width ) * blockData.width,
  299. height: Math.ceil( height / blockData.width ) * blockData.width,
  300. depthOrArrayLayers: 1,
  301. } );
  302. }
  303. }
  304. _generateMipmaps( textureGPU, textureGPUDescriptor ) {
  305. if ( this.utils === null ) {
  306. this.utils = new WebGPUTextureUtils( this.device ); // only create this helper if necessary
  307. }
  308. this.utils.generateMipmaps( textureGPU, textureGPUDescriptor );
  309. }
  310. _getBlockData( format ) {
  311. // this method is only relevant for compressed texture formats
  312. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  313. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  314. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  315. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  316. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  317. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  318. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  319. }
  320. _getBytesPerTexel( format ) {
  321. if ( format === GPUTextureFormat.R8Unorm ) return 1;
  322. if ( format === GPUTextureFormat.R16Float ) return 2;
  323. if ( format === GPUTextureFormat.RG8Unorm ) return 2;
  324. if ( format === GPUTextureFormat.RG16Float ) return 4;
  325. if ( format === GPUTextureFormat.R32Float ) return 4;
  326. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return 4;
  327. if ( format === GPUTextureFormat.RG32Float ) return 8;
  328. if ( format === GPUTextureFormat.RGBA16Float ) return 8;
  329. if ( format === GPUTextureFormat.RGBA32Float ) return 16;
  330. }
  331. _getDimension( texture ) {
  332. let dimension;
  333. if ( texture.isDataTexture3D ) {
  334. dimension = GPUTextureDimension.ThreeD;
  335. } else {
  336. dimension = GPUTextureDimension.TwoD;
  337. }
  338. return dimension;
  339. }
  340. _getFormat( texture ) {
  341. const format = texture.format;
  342. const type = texture.type;
  343. const encoding = texture.encoding;
  344. let formatGPU;
  345. switch ( format ) {
  346. case RGBA_S3TC_DXT1_Format:
  347. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  348. break;
  349. case RGBA_S3TC_DXT3_Format:
  350. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  351. break;
  352. case RGBA_S3TC_DXT5_Format:
  353. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  354. break;
  355. case RGBFormat:
  356. case RGBAFormat:
  357. switch ( type ) {
  358. case UnsignedByteType:
  359. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  360. break;
  361. case HalfFloatType:
  362. formatGPU = GPUTextureFormat.RGBA16Float;
  363. break;
  364. case FloatType:
  365. formatGPU = GPUTextureFormat.RGBA32Float;
  366. break;
  367. default:
  368. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  369. }
  370. break;
  371. case RedFormat:
  372. switch ( type ) {
  373. case UnsignedByteType:
  374. formatGPU = GPUTextureFormat.R8Unorm;
  375. break;
  376. case HalfFloatType:
  377. formatGPU = GPUTextureFormat.R16Float;
  378. break;
  379. case FloatType:
  380. formatGPU = GPUTextureFormat.R32Float;
  381. break;
  382. default:
  383. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  384. }
  385. break;
  386. case RGFormat:
  387. switch ( type ) {
  388. case UnsignedByteType:
  389. formatGPU = GPUTextureFormat.RG8Unorm;
  390. break;
  391. case HalfFloatType:
  392. formatGPU = GPUTextureFormat.RG16Float;
  393. break;
  394. case FloatType:
  395. formatGPU = GPUTextureFormat.RG32Float;
  396. break;
  397. default:
  398. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  399. }
  400. break;
  401. default:
  402. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  403. }
  404. return formatGPU;
  405. }
  406. _getImageBitmap( image, texture ) {
  407. const width = image.width;
  408. const height = image.height;
  409. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  410. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ) {
  411. const options = {};
  412. options.imageOrientation = ( texture.flipY === true ) ? 'flipY' : 'none';
  413. options.premultiplyAlpha = ( texture.premultiplyAlpha === true ) ? 'premultiply' : 'default';
  414. return createImageBitmap( image, 0, 0, width, height, options );
  415. } else {
  416. // assume ImageBitmap
  417. return Promise.resolve( image );
  418. }
  419. }
  420. _getMipLevelCount( texture, width, height, needsMipmaps ) {
  421. let mipLevelCount;
  422. if ( texture.isCompressedTexture ) {
  423. mipLevelCount = texture.mipmaps.length;
  424. } else if ( needsMipmaps === true ) {
  425. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  426. } else {
  427. mipLevelCount = 1; // a texture without mipmaps has a base mip (mipLevel 0)
  428. }
  429. return mipLevelCount;
  430. }
  431. _getSize( texture ) {
  432. const image = texture.image;
  433. let width, height, depth;
  434. if ( texture.isCubeTexture ) {
  435. width = ( image.length > 0 ) ? image[ 0 ].width : 1;
  436. height = ( image.length > 0 ) ? image[ 0 ].height : 1;
  437. depth = 6; // one image for each side of the cube map
  438. } else if ( image !== undefined ) {
  439. width = image.width;
  440. height = image.height;
  441. depth = ( image.depth !== undefined ) ? image.depth : 1;
  442. } else {
  443. width = height = depth = 1;
  444. }
  445. return { width, height, depth };
  446. }
  447. _needsMipmaps( texture ) {
  448. return ( texture.isCompressedTexture !== true ) && ( texture.generateMipmaps === true ) && ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter );
  449. }
  450. }
  451. function onRenderTargetDispose( event ) {
  452. const renderTarget = event.target;
  453. const properties = this.properties;
  454. const renderTargetProperties = properties.get( renderTarget );
  455. renderTarget.removeEventListener( 'dispose', renderTargetProperties.disposeCallback );
  456. renderTargetProperties.colorTextureGPU.destroy();
  457. properties.remove( renderTarget.texture );
  458. this.info.memory.textures --;
  459. if ( renderTarget.depthBuffer === true ) {
  460. renderTargetProperties.depthTextureGPU.destroy();
  461. this.info.memory.textures --;
  462. if ( renderTarget.depthTexture !== null ) {
  463. properties.remove( renderTarget.depthTexture );
  464. }
  465. }
  466. properties.remove( renderTarget );
  467. }
  468. function onTextureDispose( event ) {
  469. const texture = event.target;
  470. const textureProperties = this.properties.get( texture );
  471. textureProperties.textureGPU.destroy();
  472. texture.removeEventListener( 'dispose', textureProperties.disposeCallback );
  473. this.properties.remove( texture );
  474. this.info.memory.textures --;
  475. }
  476. export default WebGPUTextures;