WebGPUTextures.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. import { GPUTextureFormat, GPUAddressMode, GPUFilterMode } from './constants.js';
  2. import { 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.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. getTextureGPU( texture ) {
  33. const textureProperties = this.properties.get( texture );
  34. return textureProperties.textureGPU;
  35. }
  36. getSampler( texture ) {
  37. const textureProperties = this.properties.get( texture );
  38. return textureProperties.samplerGPU;
  39. }
  40. updateTexture( texture ) {
  41. let forceUpdate = false;
  42. const textureProperties = this.properties.get( texture );
  43. if ( texture.version > 0 && textureProperties.version !== texture.version ) {
  44. const image = texture.image;
  45. if ( image === undefined ) {
  46. console.warn( 'THREE.WebGPURenderer: Texture marked for update but image is undefined.' );
  47. } else if ( image.complete === false ) {
  48. console.warn( 'THREE.WebGPURenderer: Texture marked for update but image is incomplete.' );
  49. } else {
  50. // texture init
  51. if ( textureProperties.initialized === undefined ) {
  52. textureProperties.initialized = true;
  53. const disposeCallback = onTextureDispose.bind( this );
  54. textureProperties.disposeCallback = disposeCallback;
  55. texture.addEventListener( 'dispose', disposeCallback );
  56. this.info.memory.textures ++;
  57. }
  58. // texture creation
  59. if ( textureProperties.textureGPU !== undefined ) {
  60. // @TODO: Avoid calling of destroy() in certain scenarios. When only the contents of a texture
  61. // are updated, a buffer upload should be sufficient. However, if the user changes
  62. // the dimensions of the texture, format or usage, a new instance of GPUTexture is required.
  63. textureProperties.textureGPU.destroy();
  64. }
  65. textureProperties.textureGPU = this._createTexture( texture );
  66. textureProperties.version = texture.version;
  67. forceUpdate = true;
  68. }
  69. }
  70. // if the texture is used for RTT, it's necessary to init it once so the binding
  71. // group's resource definition points to the respective GPUTexture
  72. if ( textureProperties.initializedRTT === false ) {
  73. textureProperties.initializedRTT = true;
  74. forceUpdate = true;
  75. }
  76. return forceUpdate;
  77. }
  78. updateSampler( texture ) {
  79. const array = [];
  80. array.push( texture.wrapS );
  81. array.push( texture.wrapT );
  82. array.push( texture.wrapR );
  83. array.push( texture.magFilter );
  84. array.push( texture.minFilter );
  85. array.push( texture.anisotropy );
  86. const key = array.join();
  87. let samplerGPU = this.samplerCache.get( key );
  88. if ( samplerGPU === undefined ) {
  89. samplerGPU = this.device.createSampler( {
  90. addressModeU: this._convertAddressMode( texture.wrapS ),
  91. addressModeV: this._convertAddressMode( texture.wrapT ),
  92. addressModeW: this._convertAddressMode( texture.wrapR ),
  93. magFilter: this._convertFilterMode( texture.magFilter ),
  94. minFilter: this._convertFilterMode( texture.minFilter ),
  95. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  96. maxAnisotropy: texture.anisotropy
  97. } );
  98. this.samplerCache.set( key, samplerGPU );
  99. }
  100. const textureProperties = this.properties.get( texture );
  101. textureProperties.samplerGPU = samplerGPU;
  102. }
  103. initRenderTarget( renderTarget ) {
  104. const properties = this.properties;
  105. const renderTargetProperties = properties.get( renderTarget );
  106. if ( renderTargetProperties.initialized === undefined ) {
  107. const device = this.device;
  108. const width = renderTarget.width;
  109. const height = renderTarget.height;
  110. const colorTextureGPU = device.createTexture( {
  111. size: {
  112. width: width,
  113. height: height,
  114. depth: 1
  115. },
  116. format: GPUTextureFormat.BRGA8Unorm, // @TODO: Make configurable
  117. usage: GPUTextureUsage.OUTPUT_ATTACHMENT | GPUTextureUsage.SAMPLED
  118. } );
  119. renderTargetProperties.colorTextureGPU = colorTextureGPU;
  120. // When the ".texture" or ".depthTexture" property of a render target is used as a map,
  121. // the renderer has to find the respective GPUTexture objects to setup the bind groups.
  122. // Since it's not possible to see just from a texture object whether it belongs to a render
  123. // target or not, we need the initializedRTT flag.
  124. const textureProperties = properties.get( renderTarget.texture );
  125. textureProperties.textureGPU = colorTextureGPU;
  126. textureProperties.initializedRTT = false;
  127. if ( renderTarget.depthBuffer === true ) {
  128. const depthTextureGPU = device.createTexture( {
  129. size: {
  130. width: width,
  131. height: height,
  132. depth: 1
  133. },
  134. format: GPUTextureFormat.Depth24PlusStencil8, // @TODO: Make configurable
  135. usage: GPUTextureUsage.OUTPUT_ATTACHMENT
  136. } );
  137. renderTargetProperties.depthTextureGPU = depthTextureGPU;
  138. if ( renderTarget.depthTexture !== null ) {
  139. const depthTextureProperties = properties.get( renderTarget.depthTexture );
  140. depthTextureProperties.textureGPU = depthTextureGPU;
  141. depthTextureProperties.initializedRTT = false;
  142. }
  143. }
  144. //
  145. const disposeCallback = onRenderTargetDispose.bind( this );
  146. renderTargetProperties.disposeCallback = disposeCallback;
  147. renderTarget.addEventListener( 'dispose', disposeCallback );
  148. //
  149. renderTargetProperties.initialized = true;
  150. }
  151. }
  152. dispose() {
  153. this.samplerCache.clear();
  154. }
  155. _convertAddressMode( value ) {
  156. let addressMode = GPUAddressMode.ClampToEdge;
  157. if ( value === RepeatWrapping ) {
  158. addressMode = GPUAddressMode.Repeat;
  159. } else if ( value === MirroredRepeatWrapping ) {
  160. addressMode = GPUAddressMode.MirrorRepeat;
  161. }
  162. return addressMode;
  163. }
  164. _convertFilterMode( value ) {
  165. let filterMode = GPUFilterMode.Linear;
  166. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  167. filterMode = GPUFilterMode.Nearest;
  168. }
  169. return filterMode;
  170. }
  171. _convertFormat( format, type ) {
  172. let formatGPU;
  173. switch ( format ) {
  174. case RGBA_S3TC_DXT1_Format:
  175. formatGPU = GPUTextureFormat.BC1RGBAUnorm;
  176. break;
  177. case RGBA_S3TC_DXT3_Format:
  178. formatGPU = GPUTextureFormat.BC2RGBAUnorm;
  179. break;
  180. case RGBA_S3TC_DXT5_Format:
  181. formatGPU = GPUTextureFormat.BC3RGBAUnorm;
  182. break;
  183. case RGBFormat:
  184. case RGBAFormat:
  185. switch ( type ) {
  186. case UnsignedByteType:
  187. formatGPU = GPUTextureFormat.RGBA8Unorm;
  188. break;
  189. case FloatType:
  190. formatGPU = GPUTextureFormat.RGBA32Float;
  191. break;
  192. case HalfFloatType:
  193. formatGPU = GPUTextureFormat.RGBA16Float;
  194. break;
  195. default:
  196. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  197. }
  198. break;
  199. default:
  200. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  201. }
  202. return formatGPU;
  203. }
  204. _createTexture( texture ) {
  205. const device = this.device;
  206. const image = texture.image;
  207. const width = ( image !== undefined ) ? image.width : 1;
  208. const height = ( image !== undefined ) ? image.height : 1;
  209. const format = this._convertFormat( texture.format, texture.type );
  210. const needsMipmaps = this._needsMipmaps( texture );
  211. let mipLevelCount;
  212. let usage = GPUTextureUsage.SAMPLED | GPUTextureUsage.COPY_DST;
  213. if ( texture.isCompressedTexture ) {
  214. mipLevelCount = texture.mipmaps.length;
  215. } else {
  216. if ( needsMipmaps === true ) {
  217. mipLevelCount = this._getMipLevelCount( width, height );
  218. // current mipmap generation requires OUTPUT_ATTACHMENT
  219. usage |= GPUTextureUsage.OUTPUT_ATTACHMENT;
  220. }
  221. }
  222. // texture creation
  223. const textureGPUDescriptor = {
  224. size: {
  225. width: width,
  226. height: height,
  227. depth: 1,
  228. },
  229. format: format,
  230. usage: usage,
  231. mipLevelCount: mipLevelCount
  232. };
  233. const textureGPU = device.createTexture( textureGPUDescriptor );
  234. // transfer texture data
  235. if ( texture.isDataTexture ) {
  236. this._copyBufferToTexture( image, format, textureGPU );
  237. } else if ( texture.isCompressedTexture ) {
  238. this._copyCompressedTextureDataToTexture( texture.mipmaps, format, textureGPU );
  239. } else {
  240. // convert HTML iamges and canvas elements to ImageBitmap before copy
  241. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  242. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ) {
  243. const options = {};
  244. options.imageOrientation = ( texture.flipY === true ) ? 'flipY' : 'none';
  245. options.premultiplyAlpha = ( texture.premultiplyAlpha === true ) ? 'premultiply' : 'default';
  246. createImageBitmap( image, 0, 0, width, height, options ).then( imageBitmap => {
  247. this._copyImageBitmapToTexture( imageBitmap, textureGPU, needsMipmaps, textureGPUDescriptor );
  248. } );
  249. } else {
  250. if ( image !== undefined ) {
  251. // assuming ImageBitmap. Directly start copy operation of the contents of ImageBitmap into the destination texture
  252. this._copyImageBitmapToTexture( image, textureGPU, needsMipmaps, textureGPUDescriptor );
  253. }
  254. }
  255. }
  256. return textureGPU;
  257. }
  258. _copyBufferToTexture( image, format, textureGPU ) {
  259. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  260. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  261. const data = image.data;
  262. const bytesPerTexel = this._getBytesPerTexel( format );
  263. const bytesPerRow = Math.ceil( image.width * bytesPerTexel / 256 ) * 256;
  264. this.device.defaultQueue.writeTexture(
  265. {
  266. texture: textureGPU,
  267. mipLevel: 0 // @TODO: Support mipmaps
  268. },
  269. data,
  270. {
  271. offset: 0,
  272. bytesPerRow
  273. },
  274. {
  275. width: image.width,
  276. height: image.height,
  277. depth: 1
  278. } );
  279. }
  280. _copyImageBitmapToTexture( imageBitmap, textureGPU, needsMipmaps, textureGPUDescriptor ) {
  281. const device = this.device;
  282. device.defaultQueue.copyImageBitmapToTexture(
  283. {
  284. imageBitmap: imageBitmap
  285. }, {
  286. texture: textureGPU
  287. }, {
  288. width: imageBitmap.width,
  289. height: imageBitmap.height,
  290. depth: 1
  291. }
  292. );
  293. if ( needsMipmaps === true ) {
  294. if ( this.utils === null ) {
  295. this.utils = new WebGPUTextureUtils( this.device, this.glslang ); // only create this helper if necessary
  296. }
  297. this.utils.generateMipmaps( imageBitmap, textureGPU, textureGPUDescriptor );
  298. }
  299. }
  300. _copyCompressedTextureDataToTexture( mipmaps, format, textureGPU ) {
  301. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  302. const blockData = this._getBlockData( format );
  303. for ( let i = 0; i < mipmaps.length; i ++ ) {
  304. const mipmap = mipmaps[ i ];
  305. const width = mipmap.width;
  306. const height = mipmap.height;
  307. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  308. this.device.defaultQueue.writeTexture(
  309. {
  310. texture: textureGPU,
  311. mipLevel: i
  312. },
  313. mipmap.data,
  314. {
  315. offset: 0,
  316. bytesPerRow
  317. },
  318. {
  319. width: Math.ceil( width / blockData.width ) * blockData.width,
  320. height: Math.ceil( height / blockData.width ) * blockData.width,
  321. depth: 1,
  322. } );
  323. }
  324. }
  325. _getBlockData( format ) {
  326. if ( format === GPUTextureFormat.BC1RGBAUnorm ) return { byteLength: 8, width: 4, height: 4 };
  327. if ( format === GPUTextureFormat.BC2RGBAUnorm ) return { byteLength: 16, width: 4, height: 4 };
  328. if ( format === GPUTextureFormat.BC3RGBAUnorm ) return { byteLength: 16, width: 4, height: 4 };
  329. }
  330. _getBytesPerTexel( format ) {
  331. if ( format === GPUTextureFormat.RGBA8Unorm ) return 4;
  332. if ( format === GPUTextureFormat.RGBA16Float ) return 8;
  333. if ( format === GPUTextureFormat.RGBA32Float ) return 16;
  334. }
  335. _getMipLevelCount( width, height ) {
  336. return Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  337. }
  338. _needsMipmaps( texture ) {
  339. return ( texture.isCompressedTexture !== true ) && ( texture.generateMipmaps === true ) && ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter );
  340. }
  341. }
  342. function onRenderTargetDispose( event ) {
  343. const renderTarget = event.target;
  344. const properties = this.properties;
  345. const renderTargetProperties = properties.get( renderTarget );
  346. renderTarget.removeEventListener( 'dispose', renderTargetProperties.disposeCallback );
  347. renderTargetProperties.colorTextureGPU.destroy();
  348. properties.remove( renderTarget.texture );
  349. if ( renderTarget.depthBuffer === true ) {
  350. renderTargetProperties.depthTextureGPU.destroy();
  351. if ( renderTarget.depthTexture !== null ) {
  352. properties.remove( renderTarget.depthTexture );
  353. }
  354. }
  355. properties.remove( renderTarget );
  356. }
  357. function onTextureDispose( event ) {
  358. const texture = event.target;
  359. const textureProperties = this.properties.get( texture );
  360. textureProperties.textureGPU.destroy();
  361. texture.removeEventListener( 'dispose', textureProperties.disposeCallback );
  362. this.properties.remove( texture );
  363. this.info.memory.textures --;
  364. }
  365. export default WebGPUTextures;