WebGPUTextures.js 18 KB

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