WebGPUTextures.js 15 KB

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