BsTexture.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsCorePrerequisites.h"
  5. #include "BsResource.h"
  6. #include "BsHardwareBuffer.h"
  7. #include "BsPixelUtil.h"
  8. #include "BsTextureView.h"
  9. namespace BansheeEngine
  10. {
  11. /** @addtogroup Resources
  12. * @{
  13. */
  14. /** Flags that describe how is a texture used. */
  15. enum TextureUsage
  16. {
  17. TU_STATIC = GBU_STATIC, /**< A regular texture that is not often or ever updated from the CPU. */
  18. TU_DYNAMIC = GBU_DYNAMIC, /**< A regular texture that is often updated by the CPU. */
  19. TU_RENDERTARGET = 0x200, /**< Texture that can be rendered to by the GPU. */
  20. TU_DEPTHSTENCIL = 0x400, /**< Texture used as a depth/stencil buffer by the GPU. */
  21. TU_LOADSTORE = 0x800, /**< Texture that allows load/store operations from the GPU program. */
  22. TU_CPUCACHED = 0x1000, /**< Ensures all texture data will also be cached in system memory. */
  23. TU_DEFAULT = TU_STATIC
  24. };
  25. /** Available texture types. */
  26. enum TextureType
  27. {
  28. TEX_TYPE_1D = 1, /**< One dimensional texture. Just a row of pixels. */
  29. TEX_TYPE_2D = 2, /**< Two dimensional texture. */
  30. TEX_TYPE_3D = 3, /**< Three dimensional texture. */
  31. TEX_TYPE_CUBE_MAP = 4 /**< Texture consisting out of six 2D textures describing an inside of a cube. Allows special sampling. */
  32. };
  33. /** Texture mipmap options. */
  34. enum TextureMipmap
  35. {
  36. MIP_UNLIMITED = 0x7FFFFFFF /**< Create all mip maps down to 1x1. */
  37. };
  38. /** Properties of a Texture. Shared between sim and core thread versions of a Texture. */
  39. class BS_CORE_EXPORT TextureProperties
  40. {
  41. public:
  42. TextureProperties();
  43. TextureProperties(TextureType textureType, UINT32 width, UINT32 height, UINT32 depth, UINT32 numMipmaps,
  44. PixelFormat format, int usage, bool hwGamma, UINT32 multisampleCount, UINT32 numArraySlices);
  45. /** Gets the type of texture. */
  46. TextureType getTextureType() const { return mTextureType; }
  47. /**
  48. * Gets the number of mipmaps to be used for this texture. This number excludes the top level map (which is always
  49. * assumed to be present).
  50. */
  51. UINT32 getNumMipmaps() const {return mNumMipmaps;}
  52. /** Gets whether this texture will be set up so that on sampling it, hardware gamma correction is applied. */
  53. bool isHardwareGammaEnabled() const { return mHwGamma; }
  54. /** Gets the number of samples used for multisampling (0 if multisampling is not used). */
  55. UINT32 getMultisampleCount() const { return mMultisampleCount; }
  56. /** Returns the height of the texture. */
  57. UINT32 getHeight() const { return mHeight; }
  58. /** Returns the width of the texture. */
  59. UINT32 getWidth() const { return mWidth; }
  60. /** Returns the depth of the texture (only applicable for 3D textures). */
  61. UINT32 getDepth() const { return mDepth; }
  62. /** Returns texture usage (TextureUsage) of this texture. */
  63. int getUsage() const { return mUsage; }
  64. /** Returns the pixel format for the texture surface. */
  65. PixelFormat getFormat() const { return mFormat; }
  66. /** Returns true if the texture has an alpha layer. */
  67. bool hasAlpha() const;
  68. /** Returns the number of faces this texture has. */
  69. UINT32 getNumFaces() const;
  70. /** Returns the number of array slices of the texture (if the texture is an array texture). */
  71. UINT32 getNumArraySlices() const { return mNumArraySlices; }
  72. /**
  73. * Maps a sub-resource index to an exact face and mip level. Sub-resource indexes are used when reading or writing
  74. * to the resource.
  75. *
  76. * @note
  77. * Sub-resource index is only valid for the instance it was created on. You cannot use a sub-resource index from a
  78. * different texture and expect to get valid result. Modifying the resource so the number of sub-resources changes
  79. * invalidates all sub-resource indexes.
  80. */
  81. void mapFromSubresourceIdx(UINT32 subresourceIdx, UINT32& face, UINT32& mip) const;
  82. /**
  83. * Map a face and a mip level to a sub-resource index you can use for updating or reading a specific sub-resource.
  84. *
  85. * @note
  86. * Generated sub-resource index is only valid for the instance it was created on. Modifying the resource so the
  87. * number of sub-resources changes, invalidates all sub-resource indexes.
  88. */
  89. UINT32 mapToSubresourceIdx(UINT32 face, UINT32 mip) const;
  90. /**
  91. * Allocates a buffer you may use for storage when reading or writing a sub-resource. You need to allocate such a
  92. * buffer if you are calling readSubresource().
  93. *
  94. * You can retrieve a sub-resource index by calling mapToSubresourceIdx().
  95. *
  96. * @note Thread safe.
  97. */
  98. SPtr<PixelData> allocateSubresourceBuffer(UINT32 subresourceIdx) const;
  99. protected:
  100. friend class TextureRTTI;
  101. UINT32 mHeight;
  102. UINT32 mWidth;
  103. UINT32 mDepth;
  104. UINT32 mNumArraySlices;
  105. UINT32 mNumMipmaps;
  106. bool mHwGamma;
  107. UINT32 mMultisampleCount;
  108. TextureType mTextureType;
  109. PixelFormat mFormat;
  110. int mUsage;
  111. };
  112. /**
  113. * Abstract class representing a texture. Specific render systems have their own Texture implementations. Internally
  114. * represented as one or more surfaces with pixels in a certain number of dimensions, backed by a hardware buffer.
  115. *
  116. * @note Sim thread.
  117. */
  118. class BS_CORE_EXPORT Texture : public Resource
  119. {
  120. public:
  121. /**
  122. * Updates the texture with new data. The actual write will be queued for later execution on the core thread.
  123. * Provided data buffer will be locked until the operation completes.
  124. *
  125. * @param[in] accessor Accessor to queue the operation on.
  126. * @param[in] subresourceIdx Index of the subresource to write. Retrieved from
  127. * TextureProperties::mapToSubresourceIdx().
  128. * @param[in] data Pixel data to write. User must ensure it is in format and size compatible with
  129. * the texture.
  130. * @param[in] discardEntireBuffer When true the existing contents of the resource you are updating will be
  131. * discarded. This can make the operation faster. Resources with certain buffer
  132. * types might require this flag to be in a specific state otherwise the operation
  133. * will fail.
  134. * @return Async operation object you can use to track operation completion.
  135. */
  136. AsyncOp writeSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const SPtr<PixelData>& data,
  137. bool discardEntireBuffer);
  138. /**
  139. * Reads internal texture data to the provided previously allocated buffer. The read is queued for execution on the
  140. * core thread and not executed immediately. Provided data buffer will be locked until the operation completes.
  141. *
  142. * @param[in] accessor Accessor to queue the operation on.
  143. * @param[in] subresourceIdx Index of the subresource to read. Retrieved from
  144. * TextureProperties::mapToSubresourceIdx().
  145. * @param[out] data Pre-allocated buffer of proper size and format where data will be read to. You
  146. * can use TextureProperties::allocateSubresourceBuffer() to allocate a valid
  147. * buffer.
  148. * @return Async operation object you can use to track operation completion.
  149. *
  150. * @see TextureCore::readSubresource
  151. */
  152. AsyncOp readSubresource(CoreAccessor& accessor, UINT32 subresourceIdx, const SPtr<PixelData>& data);
  153. /**
  154. * Reads data from the cached system memory texture buffer into the provided buffer.
  155. *
  156. * @param[out] dest Previously allocated buffer to read data into.
  157. * @param[in] mipLevel (optional) Mipmap level to read from.
  158. * @param[in] face (optional) Texture face to read from.
  159. *
  160. * @note
  161. * The data read is the cached texture data. Any data written to the texture from the GPU or core thread will not
  162. * be reflected in this data. Use readSubresource() if you require those changes.
  163. * @note
  164. * The texture must have been created with TU_CPUCACHED usage otherwise this method will not return any data.
  165. */
  166. void readData(PixelData& dest, UINT32 mipLevel = 0, UINT32 face = 0);
  167. /** Returns properties that contain information about the texture. */
  168. const TextureProperties& getProperties() const { return mProperties; }
  169. /** Retrieves a core implementation of a texture usable only from the core thread. */
  170. SPtr<TextureCore> getCore() const;
  171. /************************************************************************/
  172. /* STATICS */
  173. /************************************************************************/
  174. /**
  175. * Creates a new empty texture.
  176. *
  177. * @param[in] texType Type of the texture.
  178. * @param[in] width Width of the texture in pixels.
  179. * @param[in] height Height of the texture in pixels.
  180. * @param[in] depth Depth of the texture in pixels (Must be 1 for 2D textures).
  181. * @param[in] numMips Number of mip-maps the texture has. This number excludes the full resolution map.
  182. * @param[in] format Format of the pixels.
  183. * @param[in] usage Describes how we plan on using the texture in the pipeline.
  184. * @param[in] hwGammaCorrection If true the texture data is assumed to have been gamma corrected and will be
  185. * converted back to linear space when sampled on GPU.
  186. * @param[in] multisampleCount If higher than 1, texture containing multiple samples per pixel is created.
  187. * @param[in] numArraySlices Number of texture slices to create if creating a texture array. Ignored for
  188. * 3D textures.
  189. */
  190. static HTexture create(TextureType texType, UINT32 width, UINT32 height, UINT32 depth,
  191. int numMips, PixelFormat format, int usage = TU_DEFAULT,
  192. bool hwGammaCorrection = false, UINT32 multisampleCount = 0, UINT32 numArraySlices = 1);
  193. /**
  194. * Creates a new empty texture.
  195. *
  196. * @param[in] texType Type of the texture.
  197. * @param[in] width Width of the texture in pixels.
  198. * @param[in] height Height of the texture in pixels.
  199. * @param[in] numMips Number of mip-maps the texture has. This number excludes the full resolution map.
  200. * @param[in] format Format of the pixels.
  201. * @param[in] usage Describes planned texture use.
  202. * @param[in] hwGammaCorrection If true the texture data is assumed to have been gamma corrected and will be
  203. * converted back to linear space when sampled on GPU.
  204. * @param[in] multisampleCount If higher than 1, texture containing multiple samples per pixel is created.
  205. * @param[in] numArraySlices Number of texture slices to create if creating a texture array. Ignored for
  206. * 3D textures.
  207. */
  208. static HTexture create(TextureType texType, UINT32 width, UINT32 height, int numMips,
  209. PixelFormat format, int usage = TU_DEFAULT,
  210. bool hwGammaCorrection = false, UINT32 multisampleCount = 0, UINT32 numArraySlices = 1);
  211. /**
  212. * Creates a new 2D or 3D texture initialized using the provided pixel data. Texture will not have any mipmaps.
  213. *
  214. * @param[in] pixelData Data to initialize the texture width.
  215. * @param[in] usage Describes planned texture use.
  216. * @param[in] hwGammaCorrection If true the texture data is assumed to have been gamma corrected and will be
  217. * converted back to linear space when sampled on GPU.
  218. */
  219. static HTexture create(const SPtr<PixelData>& pixelData, int usage = TU_DEFAULT, bool hwGammaCorrection = false);
  220. /** @name Internal
  221. * @{
  222. */
  223. /**
  224. * @copydoc create(TextureType, UINT32, UINT32, UINT32, int, PixelFormat, int, bool, UINT32, UINT32)
  225. *
  226. * @note Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
  227. */
  228. static SPtr<Texture> _createPtr(TextureType texType, UINT32 width, UINT32 height, UINT32 depth,
  229. int numMips, PixelFormat format, int usage = TU_DEFAULT,
  230. bool hwGammaCorrection = false, UINT32 multisampleCount = 0, UINT32 numArraySlices = 1);
  231. /**
  232. * @copydoc create(TextureType, UINT32, UINT32, int, PixelFormat, int, bool, UINT32, UINT32)
  233. *
  234. * @note Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
  235. */
  236. static SPtr<Texture> _createPtr(TextureType texType, UINT32 width, UINT32 height, int numMips,
  237. PixelFormat format, int usage = TU_DEFAULT, bool hwGammaCorrection = false, UINT32 multisampleCount = 0,
  238. UINT32 numArraySlices = 1);
  239. /**
  240. * @copydoc create(const SPtr<PixelData>&, int, bool)
  241. *
  242. * @note Internal method. Creates a texture pointer without a handle. Use create() for normal usage.
  243. */
  244. static SPtr<Texture> _createPtr(const SPtr<PixelData>& pixelData, int usage = TU_DEFAULT, bool hwGammaCorrection = false);
  245. /** @} */
  246. protected:
  247. friend class TextureManager;
  248. Texture(TextureType textureType, UINT32 width, UINT32 height, UINT32 depth, UINT32 numMipmaps,
  249. PixelFormat format, int usage, bool hwGamma, UINT32 multisampleCount, UINT32 numArraySlices);
  250. Texture(const SPtr<PixelData>& pixelData, int usage, bool hwGamma);
  251. /** @copydoc Resource::initialize */
  252. void initialize() override;
  253. /** @copydoc CoreObject::createCore */
  254. SPtr<CoreObjectCore> createCore() const override;
  255. /** Calculates the size of the texture, in bytes. */
  256. UINT32 calculateSize() const;
  257. /**
  258. * Creates buffers used for caching of CPU texture data.
  259. *
  260. * @note Make sure to initialize all texture properties before calling this.
  261. */
  262. void createCPUBuffers();
  263. /** Updates the cached CPU buffers with new data. */
  264. void updateCPUBuffers(UINT32 subresourceIdx, const PixelData& data);
  265. protected:
  266. Vector<SPtr<PixelData>> mCPUSubresourceData;
  267. TextureProperties mProperties;
  268. mutable SPtr<PixelData> mInitData;
  269. /************************************************************************/
  270. /* SERIALIZATION */
  271. /************************************************************************/
  272. public:
  273. Texture(); // Serialization only
  274. friend class TextureRTTI;
  275. static RTTITypeBase* getRTTIStatic();
  276. virtual RTTITypeBase* getRTTI() const override;
  277. };
  278. /** @} */
  279. /** @addtogroup Resources-Internal
  280. * @{
  281. */
  282. /**
  283. * Core thread version of a Texture.
  284. *
  285. * @note Core thread.
  286. */
  287. class BS_CORE_EXPORT TextureCore : public CoreObjectCore
  288. {
  289. public:
  290. TextureCore(TextureType textureType, UINT32 width, UINT32 height, UINT32 depth, UINT32 numMipmaps,
  291. PixelFormat format, int usage, bool hwGamma, UINT32 multisampleCount, UINT32 numArraySlices,
  292. const SPtr<PixelData>& initData);
  293. virtual ~TextureCore() {}
  294. /** @copydoc CoreObjectCore::initialize */
  295. virtual void initialize() override;
  296. /**
  297. * Updates a part of the texture with the provided data.
  298. *
  299. * @param[in] subresourceIdx Index of the subresource to update, if the texture has more than one.
  300. * @param[in] data Data to update the texture with.
  301. * @param[in] discardEntireBuffer When true the existing contents of the resource you are updating will be
  302. * discarded. This can make the operation faster. Resources with certain buffer
  303. * types might require this flag to be in a specific state otherwise the operation
  304. * will fail.
  305. */
  306. virtual void writeSubresource(UINT32 subresourceIdx, const PixelData& data, bool discardEntireBuffer);
  307. /**
  308. * Reads a part of the current resource into the provided @p data parameter. Data buffer needs to be pre-allocated.
  309. *
  310. * @param[in] subresourceIdx Index of the subresource to update, if the texture has more than one.
  311. * @param[out] data Buffer that will receive the data. Should be allocated with
  312. * allocateSubresourceBuffer() to ensure it is of valid type and size.
  313. */
  314. virtual void readSubresource(UINT32 subresourceIdx, PixelData& data);
  315. /**
  316. * Locks the buffer for reading or writing.
  317. *
  318. * @param[in] options Options for controlling what you may do with the locked data.
  319. * @param[in] mipLevel (optional) Mipmap level to lock.
  320. * @param[in] face (optional) Texture face to lock.
  321. * @return Pointer to the buffer data. Only valid until you call unlock().
  322. *
  323. * @note
  324. * If you are just reading or writing one block of data use readData()/writeData() methods as they can be much faster
  325. * in certain situations.
  326. */
  327. PixelData lock(GpuLockOptions options, UINT32 mipLevel = 0, UINT32 face = 0);
  328. /**
  329. * Unlocks a previously locked buffer. After the buffer is unlocked, any data returned by lock becomes invalid.
  330. *
  331. * @see lock()
  332. */
  333. void unlock();
  334. /**
  335. * Copies the contents a subresource in this texture to another texture. Texture format and size of the subresource
  336. * must match.
  337. *
  338. * You are allowed to copy from a multisampled to non-multisampled surface, which will resolve the multisampled
  339. * surface before copying.
  340. *
  341. * @param[in] srcSubresourceIdx Index of the subresource to copy from.
  342. * @param[in] destSubresourceIdx Index of the subresource to copy to.
  343. * @param[in] target Texture that contains the destination subresource.
  344. */
  345. void copy(UINT32 srcSubresourceIdx, UINT32 destSubresourceIdx, const SPtr<TextureCore>& target);
  346. /**
  347. * Reads data from the texture buffer into the provided buffer.
  348. *
  349. * @param[out] dest Previously allocated buffer to read data into.
  350. * @param[in] mipLevel (optional) Mipmap level to read from.
  351. * @param[in] face (optional) Texture face to read from.
  352. */
  353. virtual void readData(PixelData& dest, UINT32 mipLevel = 0, UINT32 face = 0) = 0;
  354. /**
  355. * Writes data from the provided buffer into the texture buffer.
  356. *
  357. * @param[in] src Buffer to retrieve the data from.
  358. * @param[in] mipLevel (optional) Mipmap level to write into.
  359. * @param[in] face (optional) Texture face to write into.
  360. * @param[in] discardWholeBuffer (optional) If true any existing texture data will be discard. This can improve
  361. * performance of the write operation.
  362. */
  363. virtual void writeData(const PixelData& src, UINT32 mipLevel = 0, UINT32 face = 0, bool discardWholeBuffer = false) = 0;
  364. /**
  365. * Returns true if the texture can be bound to a shader.
  366. *
  367. * @note This is only false for some rare special cases (for example AA render texture in DX9). Internal method.
  368. */
  369. virtual bool isBindableAsShaderResource() const { return true; }
  370. /** Returns properties that contain information about the texture. */
  371. const TextureProperties& getProperties() const { return mProperties; }
  372. /************************************************************************/
  373. /* STATICS */
  374. /************************************************************************/
  375. /** @copydoc Texture::create(TextureType, UINT32, UINT32, UINT32, int, PixelFormat, int, bool, UINT32, UINT32) */
  376. static SPtr<TextureCore> create(TextureType texType, UINT32 width, UINT32 height, UINT32 depth,
  377. int numMips, PixelFormat format, int usage = TU_DEFAULT,
  378. bool hwGammaCorrection = false, UINT32 multisampleCount = 0, UINT32 numArraySlices = 1);
  379. /** @copydoc Texture::create(TextureType, UINT32, UINT32, int, PixelFormat, int, bool, UINT32, UINT32) */
  380. static SPtr<TextureCore> create(TextureType texType, UINT32 width, UINT32 height, int numMips,
  381. PixelFormat format, int usage = TU_DEFAULT,
  382. bool hwGammaCorrection = false, UINT32 multisampleCount = 0, UINT32 numArraySlices = 1);
  383. /** @copydoc Texture::create(const SPtr<PixelData>&, int, bool) */
  384. static SPtr<TextureCore> create(const SPtr<PixelData>& pixelData, int usage = TU_DEFAULT, bool hwGammaCorrection = false);
  385. /************************************************************************/
  386. /* TEXTURE VIEW */
  387. /************************************************************************/
  388. /**
  389. * Requests a texture view for the specified mip and array ranges. Returns an existing view of one for the specified
  390. * ranges already exists, otherwise creates a new one. You must release all views by calling releaseView() when done.
  391. *
  392. * @note Core thread only.
  393. */
  394. static SPtr<TextureView> requestView(const SPtr<TextureCore>& texture, UINT32 mostDetailMip, UINT32 numMips,
  395. UINT32 firstArraySlice, UINT32 numArraySlices, GpuViewUsage usage);
  396. /**
  397. * Releases the view. View won't actually get destroyed until all references to it are released.
  398. *
  399. * @note Core thread only.
  400. */
  401. static void releaseView(const SPtr<TextureView>& view);
  402. /** Returns a plain white texture. */
  403. static SPtr<TextureCore> WHITE;
  404. /** Returns a plain black texture. */
  405. static SPtr<TextureCore> BLACK;
  406. /** Returns a plain normal map texture with normal pointing up (in Y direction). */
  407. static SPtr<TextureCore> NORMAL;
  408. protected:
  409. /** @copydoc lock */
  410. virtual PixelData lockImpl(GpuLockOptions options, UINT32 mipLevel = 0, UINT32 face = 0) = 0;
  411. /** @copydoc unlock */
  412. virtual void unlockImpl() = 0;
  413. /**
  414. * API specific implementation of copy().
  415. *
  416. * @param[in] srcFace Face index to copy from.
  417. * @param[in] srcMipLevel Mip level to copy from.
  418. * @param[in] destFace Face index to copy to.
  419. * @param[in] destMipLevel Mip level to copy to.
  420. * @param[in] target Texture to copy to.
  421. */
  422. virtual void copyImpl(UINT32 srcFace, UINT32 srcMipLevel, UINT32 destFace, UINT32 destMipLevel,
  423. const SPtr<TextureCore>& target) = 0;
  424. /************************************************************************/
  425. /* TEXTURE VIEW */
  426. /************************************************************************/
  427. /** Creates a new empty/undefined texture view. */
  428. virtual SPtr<TextureView> createView(const SPtr<TextureCore>& texture, const TEXTURE_VIEW_DESC& desc);
  429. /**
  430. * Releases all internal texture view references. Views won't get destroyed if there are external references still
  431. * held.
  432. */
  433. void clearBufferViews();
  434. /** Holds a single texture view with a usage reference count. */
  435. struct TextureViewReference
  436. {
  437. TextureViewReference(SPtr<TextureView> _view)
  438. :view(_view), refCount(0)
  439. { }
  440. SPtr<TextureView> view;
  441. UINT32 refCount;
  442. };
  443. UnorderedMap<TEXTURE_VIEW_DESC, TextureViewReference*, TextureView::HashFunction, TextureView::EqualFunction> mTextureViews;
  444. TextureProperties mProperties;
  445. SPtr<PixelData> mInitData;
  446. };
  447. /** @} */
  448. }