Image.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. /*
  2. ===========================================================================
  3. Doom 3 GPL Source Code
  4. Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
  5. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
  6. Doom 3 Source Code is free software: you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation, either version 3 of the License, or
  9. (at your option) any later version.
  10. Doom 3 Source Code is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
  16. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below.
  17. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
  18. ===========================================================================
  19. */
  20. /*
  21. ====================================================================
  22. IMAGE
  23. idImage have a one to one correspondance with OpenGL textures.
  24. No texture is ever used that does not have a corresponding idImage.
  25. no code outside this unit should call any of these OpenGL functions:
  26. qglGenTextures
  27. qglDeleteTextures
  28. qglBindTexture
  29. qglTexParameter
  30. qglTexImage
  31. qglTexSubImage
  32. qglCopyTexImage
  33. qglCopyTexSubImage
  34. qglEnable( GL_TEXTURE_* )
  35. qglDisable( GL_TEXTURE_* )
  36. ====================================================================
  37. */
  38. typedef enum {
  39. IS_UNLOADED, // no gl texture number
  40. IS_PARTIAL, // has a texture number and the low mip levels loaded
  41. IS_LOADED // has a texture number and the full mip hierarchy
  42. } imageState_t;
  43. static const int MAX_TEXTURE_LEVELS = 14;
  44. // surface description flags
  45. const unsigned long DDSF_CAPS = 0x00000001l;
  46. const unsigned long DDSF_HEIGHT = 0x00000002l;
  47. const unsigned long DDSF_WIDTH = 0x00000004l;
  48. const unsigned long DDSF_PITCH = 0x00000008l;
  49. const unsigned long DDSF_PIXELFORMAT = 0x00001000l;
  50. const unsigned long DDSF_MIPMAPCOUNT = 0x00020000l;
  51. const unsigned long DDSF_LINEARSIZE = 0x00080000l;
  52. const unsigned long DDSF_DEPTH = 0x00800000l;
  53. // pixel format flags
  54. const unsigned long DDSF_ALPHAPIXELS = 0x00000001l;
  55. const unsigned long DDSF_FOURCC = 0x00000004l;
  56. const unsigned long DDSF_RGB = 0x00000040l;
  57. const unsigned long DDSF_RGBA = 0x00000041l;
  58. // our extended flags
  59. const unsigned long DDSF_ID_INDEXCOLOR = 0x10000000l;
  60. const unsigned long DDSF_ID_MONOCHROME = 0x20000000l;
  61. // dwCaps1 flags
  62. const unsigned long DDSF_COMPLEX = 0x00000008l;
  63. const unsigned long DDSF_TEXTURE = 0x00001000l;
  64. const unsigned long DDSF_MIPMAP = 0x00400000l;
  65. #define DDS_MAKEFOURCC(a, b, c, d) ((a) | ((b) << 8) | ((c) << 16) | ((d) << 24))
  66. typedef struct {
  67. unsigned long dwSize;
  68. unsigned long dwFlags;
  69. unsigned long dwFourCC;
  70. unsigned long dwRGBBitCount;
  71. unsigned long dwRBitMask;
  72. unsigned long dwGBitMask;
  73. unsigned long dwBBitMask;
  74. unsigned long dwABitMask;
  75. } ddsFilePixelFormat_t;
  76. typedef struct
  77. {
  78. unsigned long dwSize;
  79. unsigned long dwFlags;
  80. unsigned long dwHeight;
  81. unsigned long dwWidth;
  82. unsigned long dwPitchOrLinearSize;
  83. unsigned long dwDepth;
  84. unsigned long dwMipMapCount;
  85. unsigned long dwReserved1[11];
  86. ddsFilePixelFormat_t ddspf;
  87. unsigned long dwCaps1;
  88. unsigned long dwCaps2;
  89. unsigned long dwReserved2[3];
  90. } ddsFileHeader_t;
  91. // increasing numeric values imply more information is stored
  92. typedef enum {
  93. TD_SPECULAR, // may be compressed, and always zeros the alpha channel
  94. TD_DIFFUSE, // may be compressed
  95. TD_DEFAULT, // will use compressed formats when possible
  96. TD_BUMP, // may be compressed with 8 bit lookup
  97. TD_HIGH_QUALITY // either 32 bit or a component format, no loss at all
  98. } textureDepth_t;
  99. typedef enum {
  100. TT_DISABLED,
  101. TT_2D,
  102. TT_3D,
  103. TT_CUBIC,
  104. TT_RECT
  105. } textureType_t;
  106. typedef enum {
  107. CF_2D, // not a cube map
  108. CF_NATIVE, // _px, _nx, _py, etc, directly sent to GL
  109. CF_CAMERA // _forward, _back, etc, rotated and flipped as needed before sending to GL
  110. } cubeFiles_t;
  111. #define MAX_IMAGE_NAME 256
  112. class idImage {
  113. public:
  114. idImage();
  115. // Makes this image active on the current GL texture unit.
  116. // automatically enables or disables cube mapping or texture3D
  117. // May perform file loading if the image was not preloaded.
  118. // May start a background image read.
  119. void Bind();
  120. // for use with fragment programs, doesn't change any enable2D/3D/cube states
  121. void BindFragment();
  122. // deletes the texture object, but leaves the structure so it can be reloaded
  123. void PurgeImage();
  124. // used by callback functions to specify the actual data
  125. // data goes from the bottom to the top line of the image, as OpenGL expects it
  126. // These perform an implicit Bind() on the current texture unit
  127. // FIXME: should we implement cinematics this way, instead of with explicit calls?
  128. void GenerateImage( const byte *pic, int width, int height,
  129. textureFilter_t filter, bool allowDownSize,
  130. textureRepeat_t repeat, textureDepth_t depth );
  131. void Generate3DImage( const byte *pic, int width, int height, int depth,
  132. textureFilter_t filter, bool allowDownSize,
  133. textureRepeat_t repeat, textureDepth_t minDepth );
  134. void GenerateCubeImage( const byte *pic[6], int size,
  135. textureFilter_t filter, bool allowDownSize,
  136. textureDepth_t depth );
  137. void CopyFramebuffer( int x, int y, int width, int height, bool useOversizedBuffer );
  138. void CopyDepthbuffer( int x, int y, int width, int height );
  139. void UploadScratch( const byte *pic, int width, int height );
  140. // just for resource tracking
  141. void SetClassification( int tag );
  142. // estimates size of the GL image based on dimensions and storage type
  143. int StorageSize() const;
  144. // print a one line summary of the image
  145. void Print() const;
  146. // check for changed timestamp on disk and reload if necessary
  147. void Reload( bool checkPrecompressed, bool force );
  148. void AddReference() { refCount++; };
  149. //==========================================================
  150. void GetDownsize( int &scaled_width, int &scaled_height ) const;
  151. void MakeDefault(); // fill with a grid pattern
  152. void SetImageFilterAndRepeat() const;
  153. bool ShouldImageBePartialCached();
  154. void WritePrecompressedImage();
  155. bool CheckPrecompressedImage( bool fullLoad );
  156. void UploadPrecompressedImage( byte *data, int len );
  157. void ActuallyLoadImage( bool checkForPrecompressed, bool fromBackEnd );
  158. void StartBackgroundImageLoad();
  159. int BitsForInternalFormat( int internalFormat ) const;
  160. void UploadCompressedNormalMap( int width, int height, const byte *rgba, int mipLevel );
  161. GLenum SelectInternalFormat( const byte **dataPtrs, int numDataPtrs, int width, int height,
  162. textureDepth_t minimumDepth, bool *monochromeResult ) const;
  163. void ImageProgramStringToCompressedFileName( const char *imageProg, char *fileName ) const;
  164. int NumLevelsForImageSize( int width, int height ) const;
  165. // data commonly accessed is grouped here
  166. static const int TEXTURE_NOT_LOADED = -1;
  167. GLuint texnum; // gl texture binding, will be TEXTURE_NOT_LOADED if not loaded
  168. textureType_t type;
  169. int frameUsed; // for texture usage in frame statistics
  170. int bindCount; // incremented each bind
  171. // background loading information
  172. idImage *partialImage; // shrunken, space-saving version
  173. bool isPartialImage; // true if this is pointed to by another image
  174. bool backgroundLoadInProgress; // true if another thread is reading the complete d3t file
  175. backgroundDownload_t bgl;
  176. idImage * bglNext; // linked from tr.backgroundImageLoads
  177. // parameters that define this image
  178. idStr imgName; // game path, including extension (except for cube maps), may be an image program
  179. void (*generatorFunction)( idImage *image ); // NULL for files
  180. bool allowDownSize; // this also doubles as a don't-partially-load flag
  181. textureFilter_t filter;
  182. textureRepeat_t repeat;
  183. textureDepth_t depth;
  184. cubeFiles_t cubeFiles; // determines the naming and flipping conventions for the six images
  185. bool referencedOutsideLevelLoad;
  186. bool levelLoadReferenced; // for determining if it needs to be purged
  187. bool precompressedFile; // true when it was loaded from a .d3t file
  188. bool defaulted; // true if the default image was generated because a file couldn't be loaded
  189. bool isMonochrome; // so the NV20 path can use a reduced pass count
  190. ID_TIME_T timestamp; // the most recent of all images used in creation, for reloadImages command
  191. int imageHash; // for identical-image checking
  192. int classification; // just for resource profiling
  193. // data for listImages
  194. int uploadWidth, uploadHeight, uploadDepth; // after power of two, downsample, and MAX_TEXTURE_SIZE
  195. int internalFormat;
  196. idImage *cacheUsagePrev, *cacheUsageNext; // for dynamic cache purging of old images
  197. idImage * hashNext; // for hash chains to speed lookup
  198. int refCount; // overall ref count
  199. };
  200. ID_INLINE idImage::idImage() {
  201. texnum = TEXTURE_NOT_LOADED;
  202. partialImage = NULL;
  203. type = TT_DISABLED;
  204. isPartialImage = false;
  205. frameUsed = 0;
  206. classification = 0;
  207. backgroundLoadInProgress = false;
  208. bgl.opcode = DLTYPE_FILE;
  209. bgl.f = NULL;
  210. bglNext = NULL;
  211. imgName[0] = '\0';
  212. generatorFunction = NULL;
  213. allowDownSize = false;
  214. filter = TF_DEFAULT;
  215. repeat = TR_REPEAT;
  216. depth = TD_DEFAULT;
  217. cubeFiles = CF_2D;
  218. referencedOutsideLevelLoad = false;
  219. levelLoadReferenced = false;
  220. precompressedFile = false;
  221. defaulted = false;
  222. timestamp = 0;
  223. bindCount = 0;
  224. uploadWidth = uploadHeight = uploadDepth = 0;
  225. internalFormat = 0;
  226. cacheUsagePrev = cacheUsageNext = NULL;
  227. hashNext = NULL;
  228. isMonochrome = false;
  229. refCount = 0;
  230. }
  231. // data is RGBA
  232. void R_WriteTGA( const char *filename, const byte *data, int width, int height, bool flipVertical = false );
  233. // data is an 8 bit index into palette, which is RGB (no A)
  234. void R_WritePalTGA( const char *filename, const byte *data, const byte *palette, int width, int height, bool flipVertical = false );
  235. // data is in top-to-bottom raster order unless flipVertical is set
  236. class idImageManager {
  237. public:
  238. void Init();
  239. void Shutdown();
  240. // If the exact combination of parameters has been asked for already, an existing
  241. // image will be returned, otherwise a new image will be created.
  242. // Be careful not to use the same image file with different filter / repeat / etc parameters
  243. // if possible, because it will cause a second copy to be loaded.
  244. // If the load fails for any reason, the image will be filled in with the default
  245. // grid pattern.
  246. // Will automatically resample non-power-of-two images and execute image programs if needed.
  247. idImage * ImageFromFile( const char *name,
  248. textureFilter_t filter, bool allowDownSize,
  249. textureRepeat_t repeat, textureDepth_t depth, cubeFiles_t cubeMap = CF_2D );
  250. // look for a loaded image, whatever the parameters
  251. idImage * GetImage( const char *name ) const;
  252. // The callback will be issued immediately, and later if images are reloaded or vid_restart
  253. // The callback function should call one of the idImage::Generate* functions to fill in the data
  254. idImage * ImageFromFunction( const char *name, void (*generatorFunction)( idImage *image ));
  255. // called once a frame to allow any background loads that have been completed
  256. // to turn into textures.
  257. void CompleteBackgroundImageLoads();
  258. // returns the number of bytes of image data bound in the previous frame
  259. int SumOfUsedImages();
  260. // called each frame to allow some cvars to automatically force changes
  261. void CheckCvars();
  262. // purges all the images before a vid_restart
  263. void PurgeAllImages();
  264. // reloads all apropriate images after a vid_restart
  265. void ReloadAllImages();
  266. // disable the active texture unit
  267. void BindNull();
  268. // Mark all file based images as currently unused,
  269. // but don't free anything. Calls to ImageFromFile() will
  270. // either mark the image as used, or create a new image without
  271. // loading the actual data.
  272. // Called only by renderSystem::BeginLevelLoad
  273. void BeginLevelLoad();
  274. // Free all images marked as unused, and load all images that are necessary.
  275. // This architecture prevents us from having the union of two level's
  276. // worth of data present at one time.
  277. // Called only by renderSystem::EndLevelLoad
  278. void EndLevelLoad();
  279. // used to clear and then write the dds conversion batch file
  280. void StartBuild();
  281. void FinishBuild( bool removeDups = false );
  282. void AddDDSCommand( const char *cmd );
  283. void PrintMemInfo( MemInfo_t *mi );
  284. // cvars
  285. static idCVar image_roundDown; // round bad sizes down to nearest power of two
  286. static idCVar image_colorMipLevels; // development aid to see texture mip usage
  287. static idCVar image_downSize; // controls texture downsampling
  288. static idCVar image_useCompression; // 0 = force everything to high quality
  289. static idCVar image_filter; // changes texture filtering on mipmapped images
  290. static idCVar image_anisotropy; // set the maximum texture anisotropy if available
  291. static idCVar image_lodbias; // change lod bias on mipmapped images
  292. static idCVar image_useAllFormats; // allow alpha/intensity/luminance/luminance+alpha
  293. static idCVar image_usePrecompressedTextures; // use .dds files if present
  294. static idCVar image_writePrecompressedTextures; // write .dds files if necessary
  295. static idCVar image_writeNormalTGA; // debug tool to write out .tgas of the final normal maps
  296. static idCVar image_writeNormalTGAPalletized; // debug tool to write out palletized versions of the final normal maps
  297. static idCVar image_writeTGA; // debug tool to write out .tgas of the non normal maps
  298. static idCVar image_useNormalCompression; // 1 = use 256 color compression for normal maps if available, 2 = use rxgb compression
  299. static idCVar image_useOffLineCompression; // will write a batch file with commands for the offline compression
  300. static idCVar image_preload; // if 0, dynamically load all images
  301. static idCVar image_cacheMinK; // maximum K of precompressed files to read at specification time,
  302. // the remainder will be dynamically cached
  303. static idCVar image_cacheMegs; // maximum bytes set aside for temporary loading of full-sized precompressed images
  304. static idCVar image_useCache; // 1 = do background load image caching
  305. static idCVar image_showBackgroundLoads; // 1 = print number of outstanding background loads
  306. static idCVar image_forceDownSize; // allows the ability to force a downsize
  307. static idCVar image_downSizeSpecular; // downsize specular
  308. static idCVar image_downSizeSpecularLimit;// downsize specular limit
  309. static idCVar image_downSizeBump; // downsize bump maps
  310. static idCVar image_downSizeBumpLimit; // downsize bump limit
  311. static idCVar image_ignoreHighQuality; // ignore high quality on materials
  312. static idCVar image_downSizeLimit; // downsize diffuse limit
  313. // built-in images
  314. idImage * defaultImage;
  315. idImage * flatNormalMap; // 128 128 255 in all pixels
  316. idImage * ambientNormalMap; // tr.ambientLightVector encoded in all pixels
  317. idImage * rampImage; // 0-255 in RGBA in S
  318. idImage * alphaRampImage; // 0-255 in alpha, 255 in RGB
  319. idImage * alphaNotchImage; // 2x1 texture with just 1110 and 1111 with point sampling
  320. idImage * whiteImage; // full of 0xff
  321. idImage * blackImage; // full of 0x00
  322. idImage * normalCubeMapImage; // cube map to normalize STR into RGB
  323. idImage * noFalloffImage; // all 255, but zero clamped
  324. idImage * fogImage; // increasing alpha is denser fog
  325. idImage * fogEnterImage; // adjust fogImage alpha based on terminator plane
  326. idImage * cinematicImage;
  327. idImage * scratchImage;
  328. idImage * scratchImage2;
  329. idImage * accumImage;
  330. idImage * currentRenderImage; // for SS_POST_PROCESS shaders
  331. idImage * scratchCubeMapImage;
  332. idImage * specularTableImage; // 1D intensity texture with our specular function
  333. idImage * specular2DTableImage; // 2D intensity texture with our specular function with variable specularity
  334. idImage * borderClampImage; // white inside, black outside
  335. //--------------------------------------------------------
  336. idImage * AllocImage( const char *name );
  337. void SetNormalPalette();
  338. void ChangeTextureFilter();
  339. idList<idImage*> images;
  340. idStrList ddsList;
  341. idHashIndex ddsHash;
  342. bool insideLevelLoad; // don't actually load images now
  343. byte originalToCompressed[256]; // maps normal maps to 8 bit textures
  344. byte compressedPalette[768]; // the palette that normal maps use
  345. // default filter modes for images
  346. GLenum textureMinFilter;
  347. GLenum textureMaxFilter;
  348. float textureAnisotropy;
  349. float textureLODBias;
  350. idImage * imageHashTable[FILE_HASH_SIZE];
  351. idImage * backgroundImageLoads; // chain of images that have background file loads active
  352. idImage cacheLRU; // head/tail of doubly linked list
  353. int totalCachedImageSize; // for determining when something should be purged
  354. int numActiveBackgroundImageLoads;
  355. const static int MAX_BACKGROUND_IMAGE_LOADS = 8;
  356. };
  357. extern idImageManager *globalImages; // pointer to global list for the rest of the system
  358. int MakePowerOfTwo( int num );
  359. /*
  360. ====================================================================
  361. IMAGEPROCESS
  362. FIXME: make an "imageBlock" type to hold byte*,width,height?
  363. ====================================================================
  364. */
  365. byte *R_Dropsample( const byte *in, int inwidth, int inheight,
  366. int outwidth, int outheight );
  367. byte *R_ResampleTexture( const byte *in, int inwidth, int inheight,
  368. int outwidth, int outheight );
  369. byte *R_MipMapWithAlphaSpecularity( const byte *in, int width, int height );
  370. byte *R_MipMap( const byte *in, int width, int height, bool preserveBorder );
  371. byte *R_MipMap3D( const byte *in, int width, int height, int depth, bool preserveBorder );
  372. // these operate in-place on the provided pixels
  373. void R_SetBorderTexels( byte *inBase, int width, int height, const byte border[4] );
  374. void R_SetBorderTexels3D( byte *inBase, int width, int height, int depth, const byte border[4] );
  375. void R_BlendOverTexture( byte *data, int pixelCount, const byte blend[4] );
  376. void R_HorizontalFlip( byte *data, int width, int height );
  377. void R_VerticalFlip( byte *data, int width, int height );
  378. void R_RotatePic( byte *data, int width );
  379. /*
  380. ====================================================================
  381. IMAGEFILES
  382. ====================================================================
  383. */
  384. void R_LoadImage( const char *name, byte **pic, int *width, int *height, ID_TIME_T *timestamp, bool makePowerOf2 );
  385. // pic is in top to bottom raster format
  386. bool R_LoadCubeImages( const char *cname, cubeFiles_t extensions, byte *pic[6], int *size, ID_TIME_T *timestamp );
  387. /*
  388. ====================================================================
  389. IMAGEPROGRAM
  390. ====================================================================
  391. */
  392. void R_LoadImageProgram( const char *name, byte **pic, int *width, int *height, ID_TIME_T *timestamp, textureDepth_t *depth = NULL );
  393. const char *R_ParsePastImageProgram( idLexer &src );