WebGPUTextures.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. import { GPUTextureFormat, GPUAddressMode, GPUFilterMode } from './constants.js';
  2. import { CubeTexture, Texture, NearestFilter, NearestMipmapNearestFilter, NearestMipmapLinearFilter, LinearFilter, RepeatWrapping, MirroredRepeatWrapping,
  3. RGBFormat, RGBAFormat, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, UnsignedByteType, FloatType, HalfFloatType, sRGBEncoding
  4. } from '../../../../build/three.module.js';
  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. depth: 1
  126. },
  127. format: colorTextureFormat,
  128. usage: GPUTextureUsage.OUTPUT_ATTACHMENT | GPUTextureUsage.SAMPLED
  129. } );
  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. depth: 1
  146. },
  147. format: depthTextureFormat,
  148. usage: GPUTextureUsage.OUTPUT_ATTACHMENT
  149. } );
  150. renderTargetProperties.depthTextureGPU = depthTextureGPU;
  151. renderTargetProperties.depthTextureFormat = depthTextureFormat;
  152. if ( renderTarget.depthTexture !== null ) {
  153. const depthTextureProperties = properties.get( renderTarget.depthTexture );
  154. depthTextureProperties.textureGPU = depthTextureGPU;
  155. depthTextureProperties.initializedRTT = false;
  156. }
  157. }
  158. //
  159. const disposeCallback = onRenderTargetDispose.bind( this );
  160. renderTargetProperties.disposeCallback = disposeCallback;
  161. renderTarget.addEventListener( 'dispose', disposeCallback );
  162. //
  163. renderTargetProperties.initialized = true;
  164. }
  165. }
  166. dispose() {
  167. this.samplerCache.clear();
  168. }
  169. _convertAddressMode( value ) {
  170. let addressMode = GPUAddressMode.ClampToEdge;
  171. if ( value === RepeatWrapping ) {
  172. addressMode = GPUAddressMode.Repeat;
  173. } else if ( value === MirroredRepeatWrapping ) {
  174. addressMode = GPUAddressMode.MirrorRepeat;
  175. }
  176. return addressMode;
  177. }
  178. _convertFilterMode( value ) {
  179. let filterMode = GPUFilterMode.Linear;
  180. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  181. filterMode = GPUFilterMode.Nearest;
  182. }
  183. return filterMode;
  184. }
  185. _createTexture( texture ) {
  186. const device = this.device;
  187. const image = texture.image;
  188. const { width, height, depth } = this._getSize( texture );
  189. const needsMipmaps = this._needsMipmaps( texture );
  190. const mipLevelCount = this._getMipLevelCount( texture, width, height, needsMipmaps );
  191. const format = this._getFormat( texture );
  192. let usage = GPUTextureUsage.SAMPLED | GPUTextureUsage.COPY_DST;
  193. if ( needsMipmaps === true ) {
  194. // current mipmap generation requires OUTPUT_ATTACHMENT
  195. usage |= GPUTextureUsage.OUTPUT_ATTACHMENT;
  196. }
  197. // texture creation
  198. const textureGPUDescriptor = {
  199. size: {
  200. width: width,
  201. height: height,
  202. depth: depth,
  203. },
  204. mipLevelCount: mipLevelCount,
  205. sampleCount: 1,
  206. format: format,
  207. usage: usage
  208. };
  209. const textureGPU = device.createTexture( textureGPUDescriptor );
  210. // transfer texture data
  211. if ( texture.isDataTexture ) {
  212. this._copyBufferToTexture( image, format, textureGPU );
  213. if ( needsMipmaps === true ) this._generateMipmaps( textureGPU, textureGPUDescriptor );
  214. } else if ( texture.isCompressedTexture ) {
  215. this._copyCompressedBufferToTexture( texture.mipmaps, format, textureGPU );
  216. } else if ( texture.isCubeTexture ) {
  217. this._copyCubeMapToTexture( image, texture, textureGPU );
  218. } else {
  219. if ( image !== undefined ) {
  220. // assume HTMLImageElement, HTMLCanvasElement or ImageBitmap
  221. this._getImageBitmap( image, texture ).then( imageBitmap => {
  222. this._copyImageBitmapToTexture( imageBitmap, textureGPU );
  223. if ( needsMipmaps === true ) this._generateMipmaps( textureGPU, textureGPUDescriptor );
  224. } );
  225. }
  226. }
  227. return textureGPU;
  228. }
  229. _copyBufferToTexture( image, format, textureGPU ) {
  230. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  231. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  232. const data = image.data;
  233. const bytesPerTexel = this._getBytesPerTexel( format );
  234. const bytesPerRow = Math.ceil( image.width * bytesPerTexel / 256 ) * 256;
  235. this.device.defaultQueue.writeTexture(
  236. {
  237. texture: textureGPU,
  238. mipLevel: 0
  239. },
  240. data,
  241. {
  242. offset: 0,
  243. bytesPerRow
  244. },
  245. {
  246. width: image.width,
  247. height: image.height,
  248. depth: 1
  249. } );
  250. }
  251. _copyCubeMapToTexture( images, texture, textureGPU ) {
  252. for ( let i = 0; i < images.length; i ++ ) {
  253. const image = images[ i ];
  254. this._getImageBitmap( image, texture ).then( imageBitmap => {
  255. this._copyImageBitmapToTexture( imageBitmap, textureGPU, { x: 0, y: 0, z: i } );
  256. } );
  257. }
  258. }
  259. _copyImageBitmapToTexture( image, textureGPU, origin = { x: 0, y: 0, z: 0 } ) {
  260. this.device.defaultQueue.copyImageBitmapToTexture(
  261. {
  262. imageBitmap: image
  263. }, {
  264. texture: textureGPU,
  265. mipLevel: 0,
  266. origin: origin
  267. }, {
  268. width: image.width,
  269. height: image.height,
  270. depth: 1
  271. }
  272. );
  273. }
  274. _copyCompressedBufferToTexture( mipmaps, format, textureGPU ) {
  275. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  276. const blockData = this._getBlockData( format );
  277. for ( let i = 0; i < mipmaps.length; i ++ ) {
  278. const mipmap = mipmaps[ i ];
  279. const width = mipmap.width;
  280. const height = mipmap.height;
  281. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  282. this.device.defaultQueue.writeTexture(
  283. {
  284. texture: textureGPU,
  285. mipLevel: i
  286. },
  287. mipmap.data,
  288. {
  289. offset: 0,
  290. bytesPerRow
  291. },
  292. {
  293. width: Math.ceil( width / blockData.width ) * blockData.width,
  294. height: Math.ceil( height / blockData.width ) * blockData.width,
  295. depth: 1,
  296. } );
  297. }
  298. }
  299. _generateMipmaps( textureGPU, textureGPUDescriptor ) {
  300. if ( this.utils === null ) {
  301. this.utils = new WebGPUTextureUtils( this.device, this.glslang ); // only create this helper if necessary
  302. }
  303. this.utils.generateMipmaps( textureGPU, textureGPUDescriptor );
  304. }
  305. _getBlockData( format ) {
  306. // this method is only relevant for compressed texture formats
  307. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  308. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  309. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  310. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  311. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  312. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  313. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  314. }
  315. _getBytesPerTexel( format ) {
  316. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return 4;
  317. if ( format === GPUTextureFormat.RGBA16Float ) return 8;
  318. if ( format === GPUTextureFormat.RGBA32Float ) return 16;
  319. }
  320. _getFormat( texture ) {
  321. const format = texture.format;
  322. const type = texture.type;
  323. const encoding = texture.encoding;
  324. let formatGPU;
  325. switch ( format ) {
  326. case RGBA_S3TC_DXT1_Format:
  327. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  328. break;
  329. case RGBA_S3TC_DXT3_Format:
  330. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  331. break;
  332. case RGBA_S3TC_DXT5_Format:
  333. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  334. break;
  335. case RGBFormat:
  336. case RGBAFormat:
  337. switch ( type ) {
  338. case UnsignedByteType:
  339. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  340. break;
  341. case FloatType:
  342. formatGPU = GPUTextureFormat.RGBA32Float;
  343. break;
  344. case HalfFloatType:
  345. formatGPU = GPUTextureFormat.RGBA16Float;
  346. break;
  347. default:
  348. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  349. }
  350. break;
  351. default:
  352. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  353. }
  354. return formatGPU;
  355. }
  356. _getImageBitmap( image, texture ) {
  357. const width = image.width;
  358. const height = image.height;
  359. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  360. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ) {
  361. const options = {};
  362. options.imageOrientation = ( texture.flipY === true ) ? 'flipY' : 'none';
  363. options.premultiplyAlpha = ( texture.premultiplyAlpha === true ) ? 'premultiply' : 'default';
  364. return createImageBitmap( image, 0, 0, width, height, options );
  365. } else {
  366. // assume ImageBitmap
  367. return Promise.resolve( image );
  368. }
  369. }
  370. _getMipLevelCount( texture, width, height, needsMipmaps ) {
  371. let mipLevelCount;
  372. if ( texture.isCompressedTexture ) {
  373. mipLevelCount = texture.mipmaps.length;
  374. } else if ( needsMipmaps === true ) {
  375. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  376. } else {
  377. mipLevelCount = 1; // a texture without mipmaps has a base mip (mipLevel 0)
  378. }
  379. return mipLevelCount;
  380. }
  381. _getSize( texture ) {
  382. const image = texture.image;
  383. let width, height, depth;
  384. if ( texture.isCubeTexture ) {
  385. width = ( image.length > 0 ) ? image[ 0 ].width : 1;
  386. height = ( image.length > 0 ) ? image[ 0 ].height : 1;
  387. depth = 6; // one image for each side of the cube map
  388. } else {
  389. width = ( image !== undefined ) ? image.width : 1;
  390. height = ( image !== undefined ) ? image.height : 1;
  391. depth = 1;
  392. }
  393. return { width, height, depth };
  394. }
  395. _needsMipmaps( texture ) {
  396. return ( texture.isCompressedTexture !== true ) && ( texture.generateMipmaps === true ) && ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter );
  397. }
  398. }
  399. function onRenderTargetDispose( event ) {
  400. const renderTarget = event.target;
  401. const properties = this.properties;
  402. const renderTargetProperties = properties.get( renderTarget );
  403. renderTarget.removeEventListener( 'dispose', renderTargetProperties.disposeCallback );
  404. renderTargetProperties.colorTextureGPU.destroy();
  405. properties.remove( renderTarget.texture );
  406. if ( renderTarget.depthBuffer === true ) {
  407. renderTargetProperties.depthTextureGPU.destroy();
  408. if ( renderTarget.depthTexture !== null ) {
  409. properties.remove( renderTarget.depthTexture );
  410. }
  411. }
  412. properties.remove( renderTarget );
  413. }
  414. function onTextureDispose( event ) {
  415. const texture = event.target;
  416. const textureProperties = this.properties.get( texture );
  417. textureProperties.textureGPU.destroy();
  418. texture.removeEventListener( 'dispose', textureProperties.disposeCallback );
  419. this.properties.remove( texture );
  420. this.info.memory.textures --;
  421. }
  422. export default WebGPUTextures;