WebGPUTextures.js 13 KB

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