1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
|
/* Copyright (C) 2022 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef INCLUDED_TEXTUREMANAGER
#define INCLUDED_TEXTUREMANAGER
#include "graphics/Texture.h"
#include "lib/file/vfs/vfs.h"
#include "lib/tex/tex.h"
#include "renderer/backend/IDevice.h"
#include "renderer/backend/IDeviceCommandContext.h"
#include "renderer/backend/ITexture.h"
#include <memory>
class CTextureProperties;
class CTextureManagerImpl;
/**
* Texture manager with asynchronous loading and automatic DDS conversion/compression.
*
* Input textures can be any format. They will be converted to DDS using settings defined
* in files named "texture.xml", in the same directory as the texture and in its parent
* directories. See CTextureConverter for the XML syntax. The DDS file will be cached
* for faster loading in the future.
*
* Typically the graphics code will initialise many textures at the start of the game,
* mostly for off-screen objects, by calling CreateTexture().
* Loading texture data may be very slow (especially if it needs to be converted
* to DDS), and we don't want the game to become unresponsive.
* CreateTexture therefore returns an object immediately, without loading the
* texture. If the object is never used then the data will never be loaded.
*
* Typically, the renderer will call CTexture::Bind() when it wants to use the
* texture. This will trigger the loading of the texture data. If it can be loaded
* quickly (i.e. there is already a cached DDS version), then it will be loaded before
* the function returns, and the texture can be rendered as normal.
*
* If loading will take a long time, then Bind() binds a default placeholder texture
* and starts loading the texture in the background. It will use the correct texture
* when the renderer next calls Bind() after the load has finished.
*
* It is also possible to prefetch textures which are not being rendered yet, but
* are expected to be rendered soon (e.g. for off-screen terrain tiles).
* These will be loaded in the background, when there are no higher-priority textures
* to load.
*
* The same texture file can be safely loaded multiple times with different backend parameters
* (but this should be avoided whenever possible, as it wastes VRAM).
*
* For release packages, DDS files can be precached by appending ".dds" to their name,
* which will be used instead of doing runtime conversion. This means most players should
* never experience the slow asynchronous conversion behaviour.
* These cache files will typically be packed into an archive for faster loading;
* if no archive cache is available then the source file will be converted and stored
* as a loose cache file on the user's disk.
*/
class CTextureManager
{
NONCOPYABLE(CTextureManager);
public:
/**
* Construct texture manager. vfs must be the VFS instance used for all textures
* loaded from this object.
* highQuality is slower and intended for batch-conversion modes.
*/
CTextureManager(PIVFS vfs, bool highQuality, Renderer::Backend::IDevice* device);
~CTextureManager();
/**
* Create a texture with the given properties.
* The texture data will not be loaded immediately.
*/
CTexturePtr CreateTexture(const CTextureProperties& props);
/**
* Wraps a backend texture.
*/
CTexturePtr WrapBackendTexture(
std::unique_ptr<Renderer::Backend::ITexture> backendTexture);
/**
* Returns a magenta texture. Use this for highlighting errors
* (e.g. missing terrain textures).
*/
const CTexturePtr& GetErrorTexture();
/**
* Returns a single color RGBA texture with CColor(1.0f, 1.0f, 1.0f, 1.0f).
*/
const CTexturePtr& GetWhiteTexture();
/**
* Returns a single color RGBA texture with CColor(0.0f, 0.0f, 0.0f, 0.0f).
*/
const CTexturePtr& GetTransparentTexture();
/**
* Returns a white RGBA texture with alpha gradient.
*/
const CTexturePtr& GetAlphaGradientTexture();
/**
* Returns a single color RGBA texture cube with CColor(0.0f, 0.0f, 0.0f, 1.0f).
*/
const CTexturePtr& GetBlackTextureCube();
/**
* Work on asynchronous texture loading operations, if any.
* Returns true if it did any work.
* The caller should typically loop this per frame until it returns
* false or exceeds the allocated time for this frame.
*/
bool MakeProgress();
/**
* Work on asynchronous texture uploading operations, if any.
* Returns true if it did any work. Mostly the same as MakeProgress.
*/
bool MakeUploadProgress(Renderer::Backend::IDeviceCommandContext* deviceCommandContext);
/**
* Synchronously converts and compresses and saves the texture,
* and returns the output path (minus a "cache/" prefix). This
* is intended for pre-caching textures in release archives.
* @return true on success
*/
bool GenerateCachedTexture(const VfsPath& path, VfsPath& outputPath);
/**
* Returns true if the given texture exists.
* This tests both for the original and converted filename.
*/
bool TextureExists(const VfsPath& path) const;
/**
* Returns total number of bytes uploaded for all current texture.
*/
size_t GetBytesUploaded() const;
/**
* Should be called on any quality or anisotropic change.
*/
void OnQualityChanged();
private:
CTextureManagerImpl* m;
};
/**
* Represents the filename and GL parameters of a texture,
* for passing to CTextureManager::CreateTexture.
*/
class CTextureProperties
{
friend class CTextureManagerImpl;
friend struct TextureCacheCmp;
friend struct TPequal_to;
friend struct TPhash;
public:
/**
* Use the given texture name, and default GL parameters.
*/
explicit CTextureProperties(const VfsPath& path)
: m_Path(path)
{
}
CTextureProperties(
const VfsPath& path, const Renderer::Backend::Format formatOverride)
: m_Path(path), m_FormatOverride(formatOverride)
{
}
/**
* Set sampler address mode.
*/
void SetAddressMode(const Renderer::Backend::Sampler::AddressMode addressMode)
{
m_AddressModeU = m_AddressModeV = addressMode;
}
/**
* Set sampler address mode separately for different coordinates.
*/
void SetAddressMode(
const Renderer::Backend::Sampler::AddressMode addressModeU,
const Renderer::Backend::Sampler::AddressMode addressModeV)
{
m_AddressModeU = addressModeU;
m_AddressModeV = addressModeV;
}
/**
* The value of max anisotropy is set by options. Though it might make sense
* to add an override.
*/
void SetAnisotropicFilter(const bool enabled) { m_AnisotropicFilterEnabled = enabled; }
// TODO: rather than this static definition of texture properties
// (especially anisotropy), maybe we want something that can be more
// easily tweaked in an Options menu? e.g. the caller just specifies
// "terrain texture mode" and we combine it with the user's options.
// That'd let us dynamically change texture properties easily.
//
// enum EQualityMode
// {
// NONE,
// TERRAIN,
// MODEL,
// GUI
// }
// void SetQuality(EQualityMode mode, float anisotropy, float lodbias, int reducemipmaps, ...);
//
// or something a bit like that.
void SetIgnoreQuality(bool ignore) { m_IgnoreQuality = ignore; }
private:
// Must update TPhash, TPequal_to when changing these fields
VfsPath m_Path;
Renderer::Backend::Sampler::AddressMode m_AddressModeU =
Renderer::Backend::Sampler::AddressMode::REPEAT;
Renderer::Backend::Sampler::AddressMode m_AddressModeV =
Renderer::Backend::Sampler::AddressMode::REPEAT;
bool m_AnisotropicFilterEnabled = false;
Renderer::Backend::Format m_FormatOverride =
Renderer::Backend::Format::UNDEFINED;
bool m_IgnoreQuality = false;
};
/**
* Represents a texture object.
* The texture data may or may not have been loaded yet.
* Before it has been loaded, all operations will act on a default
* 1x1-pixel grey texture instead.
*/
class CTexture
{
NONCOPYABLE(CTexture);
public:
~CTexture();
/**
* Returns the width (in pixels) of the current texture.
*/
size_t GetWidth() const;
/**
* Returns the height (in pixels) of the current texture.
*/
size_t GetHeight() const;
/**
* Returns whether the current texture has an alpha channel.
*/
bool HasAlpha() const;
/**
* Returns the ARGB value of the lowest mipmap level (i.e. the
* average of the whole texture).
* Returns 0 if the texture has no mipmaps.
*/
u32 GetBaseColor() const;
/**
* Returns total number of bytes uploaded for this texture.
*/
size_t GetUploadedSize() const;
/**
* Uploads a texture data to a backend texture if successfully loaded.
* If the texture data hasn't been loaded yet, this may wait a short while to
* load it. If loading takes too long then it will return sooner and the data will
* be loaded in a background thread, so this does not guarantee the texture really
* will be uploaded.
*/
void UploadBackendTextureIfNeeded(
Renderer::Backend::IDeviceCommandContext* deviceCommandContext);
/**
* Returns a backend texture if successfully uploaded, else fallback.
*/
Renderer::Backend::ITexture* GetBackendTexture();
const Renderer::Backend::ITexture* GetBackendTexture() const;
/**
* Attempt to load the texture data quickly, as with
* GetUploadedBackendTextureIfNeeded(). Returns whether the texture data is
* currently loaded (but not uploaded).
*/
bool TryLoad();
/**
* Returns whether the texture data is currently loaded.
*/
bool IsLoaded() const { return m_State == LOADED; }
/**
* Returns whether the texture data is currently uploaded.
*/
bool IsUploaded() const { return m_State == UPLOADED; }
/**
* Activate the prefetching optimisation for this texture.
* Use this if it is likely the texture will be needed in the near future.
* It will be loaded in the background so that it is likely to be ready when
* it is used by Bind().
*/
void Prefetch();
private:
friend class CTextureManagerImpl;
friend class CPredefinedTexture;
friend struct TextureCacheCmp;
friend struct TPequal_to;
friend struct TPhash;
// Only the texture manager can create these
explicit CTexture(
std::unique_ptr<Renderer::Backend::ITexture> texture,
Renderer::Backend::ITexture* fallback,
const CTextureProperties& props, CTextureManagerImpl* textureManager);
void ResetBackendTexture(
std::unique_ptr<Renderer::Backend::ITexture> backendTexture,
Renderer::Backend::ITexture* fallbackBackendTexture);
const CTextureProperties m_Properties;
std::unique_ptr<Renderer::Backend::ITexture> m_BackendTexture;
// It's possible to m_FallbackBackendTexture references m_BackendTexture.
Renderer::Backend::ITexture* m_FallbackBackendTexture = nullptr;
u32 m_BaseColor;
std::unique_ptr<Tex> m_TextureData;
size_t m_UploadedSize = 0;
uint32_t m_BaseLevelOffset = 0;
enum
{
UNLOADED, // loading has not started
PREFETCH_NEEDS_LOADING, // was prefetched; currently waiting to try loading from cache
PREFETCH_NEEDS_CONVERTING, // was prefetched; currently waiting to be sent to the texture converter
PREFETCH_IS_CONVERTING, // was prefetched; currently being processed by the texture converter
HIGH_NEEDS_CONVERTING, // high-priority; currently waiting to be sent to the texture converter
HIGH_IS_CONVERTING, // high-priority; currently being processed by the texture converter
LOADED, // loading texture data has completed (successfully or not)
UPLOADED // uploading to backend has completed (successfully or not)
} m_State;
CTextureManagerImpl* m_TextureManager;
// Self-reference to let us recover the CTexturePtr for this object.
// (weak pointer to avoid cycles)
std::weak_ptr<CTexture> m_Self;
};
#endif // INCLUDED_TEXTUREMANAGER
|