WebGPUTextures.js 18 KB

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