Texture.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. #include "Base.h"
  2. #include "Image.h"
  3. #include "Texture.h"
  4. #include "FileSystem.h"
  5. // PVRTC (GL_IMG_texture_compression_pvrtc) : Imagination based gpus
  6. #ifndef GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG
  7. #define GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01
  8. #endif
  9. #ifndef GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG
  10. #define GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03
  11. #endif
  12. #ifndef GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG
  13. #define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00
  14. #endif
  15. #ifndef GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG
  16. #define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02
  17. #endif
  18. // S3TC/DXT (GL_EXT_texture_compression_s3tc) : Most desktop/console gpus
  19. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT
  20. #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1
  21. #endif
  22. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT
  23. #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2
  24. #endif
  25. #ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT
  26. #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3
  27. #endif
  28. // ATC (GL_AMD_compressed_ATC_texture) : Qualcomm/Adreno based gpus
  29. #ifndef ATC_RGB_AMD
  30. #define ATC_RGB_AMD 0x8C92
  31. #endif
  32. #ifndef ATC_RGBA_EXPLICIT_ALPHA_AMD
  33. #define ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
  34. #endif
  35. #ifndef ATC_RGBA_INTERPOLATED_ALPHA_AMD
  36. #define ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
  37. #endif
  38. namespace gameplay
  39. {
  40. static std::vector<Texture*> __textureCache;
  41. static TextureHandle __currentTextureId;
  42. Texture::Texture() : _handle(0), _format(UNKNOWN), _width(0), _height(0), _mipmapped(false), _cached(false), _compressed(false),
  43. _wrapS(Texture::REPEAT), _wrapT(Texture::REPEAT), _minFilter(Texture::NEAREST_MIPMAP_LINEAR), _magFilter(Texture::LINEAR)
  44. {
  45. }
  46. Texture::~Texture()
  47. {
  48. if (_handle)
  49. {
  50. GL_ASSERT( glDeleteTextures(1, &_handle) );
  51. _handle = 0;
  52. }
  53. // Remove ourself from the texture cache.
  54. if (_cached)
  55. {
  56. std::vector<Texture*>::iterator itr = std::find(__textureCache.begin(), __textureCache.end(), this);
  57. if (itr != __textureCache.end())
  58. {
  59. __textureCache.erase(itr);
  60. }
  61. }
  62. }
  63. Texture* Texture::create(const char* path, bool generateMipmaps)
  64. {
  65. GP_ASSERT(path);
  66. // Search texture cache first.
  67. for (size_t i = 0, count = __textureCache.size(); i < count; ++i)
  68. {
  69. Texture* t = __textureCache[i];
  70. GP_ASSERT(t);
  71. if (t->_path == path)
  72. {
  73. // If 'generateMipmaps' is true, call Texture::generateMipamps() to force the
  74. // texture to generate its mipmap chain if it hasn't already done so.
  75. if (generateMipmaps)
  76. {
  77. t->generateMipmaps();
  78. }
  79. // Found a match.
  80. t->addRef();
  81. return t;
  82. }
  83. }
  84. Texture* texture = NULL;
  85. // Filter loading based on file extension.
  86. const char* ext = strrchr(FileSystem::resolvePath(path), '.');
  87. if (ext)
  88. {
  89. switch (strlen(ext))
  90. {
  91. case 4:
  92. if (tolower(ext[1]) == 'p' && tolower(ext[2]) == 'n' && tolower(ext[3]) == 'g')
  93. {
  94. Image* image = Image::create(path);
  95. if (image)
  96. texture = create(image, generateMipmaps);
  97. SAFE_RELEASE(image);
  98. }
  99. else if (tolower(ext[1]) == 'p' && tolower(ext[2]) == 'v' && tolower(ext[3]) == 'r')
  100. {
  101. // PowerVR Compressed Texture RGBA.
  102. texture = createCompressedPVRTC(path);
  103. }
  104. else if (tolower(ext[1]) == 'd' && tolower(ext[2]) == 'd' && tolower(ext[3]) == 's')
  105. {
  106. // DDS file format (DXT/S3TC) compressed textures
  107. texture = createCompressedDDS(path);
  108. }
  109. break;
  110. }
  111. }
  112. if (texture)
  113. {
  114. texture->_path = path;
  115. texture->_cached = true;
  116. // Add to texture cache.
  117. __textureCache.push_back(texture);
  118. return texture;
  119. }
  120. GP_ERROR("Failed to load texture from file '%s'.", path);
  121. return NULL;
  122. }
  123. Texture* Texture::create(Image* image, bool generateMipmaps)
  124. {
  125. GP_ASSERT(image);
  126. switch (image->getFormat())
  127. {
  128. case Image::RGB:
  129. return create(Texture::RGB, image->getWidth(), image->getHeight(), image->getData(), generateMipmaps);
  130. case Image::RGBA:
  131. return create(Texture::RGBA, image->getWidth(), image->getHeight(), image->getData(), generateMipmaps);
  132. default:
  133. GP_ERROR("Unsupported image format (%d).", image->getFormat());
  134. return NULL;
  135. }
  136. }
  137. Texture* Texture::create(Format format, unsigned int width, unsigned int height, const unsigned char* data, bool generateMipmaps)
  138. {
  139. // Create and load the texture.
  140. GLuint textureId;
  141. GL_ASSERT( glGenTextures(1, &textureId) );
  142. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, textureId) );
  143. GL_ASSERT( glPixelStorei(GL_UNPACK_ALIGNMENT, 1) );
  144. #ifndef OPENGL_ES
  145. // glGenerateMipmap is new in OpenGL 3.0. For OpenGL 2.0 we must fallback to use glTexParameteri
  146. // with GL_GENERATE_MIPMAP prior to actual texture creation (glTexImage2D)
  147. if ( generateMipmaps && glGenerateMipmap == NULL )
  148. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE) );
  149. #endif
  150. GL_ASSERT( glTexImage2D(GL_TEXTURE_2D, 0, (GLenum)format, width, height, 0, (GLenum)format, GL_UNSIGNED_BYTE, data) );
  151. // Set initial minification filter based on whether or not mipmaping was enabled.
  152. Filter minFilter = generateMipmaps ? NEAREST_MIPMAP_LINEAR : LINEAR;
  153. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter) );
  154. Texture* texture = new Texture();
  155. texture->_handle = textureId;
  156. texture->_format = format;
  157. texture->_width = width;
  158. texture->_height = height;
  159. texture->_minFilter = minFilter;
  160. if (generateMipmaps)
  161. {
  162. texture->generateMipmaps();
  163. }
  164. // Restore the texture id
  165. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, __currentTextureId) );
  166. return texture;
  167. }
  168. Texture* Texture::create(TextureHandle handle, int width, int height, Format format)
  169. {
  170. GP_ASSERT(handle);
  171. Texture* texture = new Texture();
  172. texture->_handle = handle;
  173. texture->_format = format;
  174. texture->_width = width;
  175. texture->_height = height;
  176. return texture;
  177. }
  178. // Computes the size of a PVRTC data chunk for a mipmap level of the given size.
  179. static unsigned int computePVRTCDataSize(int width, int height, int bpp)
  180. {
  181. int blockSize;
  182. int widthBlocks;
  183. int heightBlocks;
  184. if (bpp == 4)
  185. {
  186. blockSize = 4 * 4; // Pixel by pixel block size for 4bpp
  187. widthBlocks = std::max(width >> 2, 2);
  188. heightBlocks = std::max(height >> 2, 2);
  189. }
  190. else
  191. {
  192. blockSize = 8 * 4; // Pixel by pixel block size for 2bpp
  193. widthBlocks = std::max(width >> 3, 2);
  194. heightBlocks = std::max(height >> 2, 2);
  195. }
  196. return widthBlocks * heightBlocks * ((blockSize * bpp) >> 3);
  197. }
  198. Texture* Texture::createCompressedPVRTC(const char* path)
  199. {
  200. std::auto_ptr<Stream> stream(FileSystem::open(path));
  201. if (stream.get() == NULL || !stream->canRead())
  202. {
  203. GP_ERROR("Failed to load file '%s'.", path);
  204. return NULL;
  205. }
  206. // Read first 4 bytes to determine PVRTC format.
  207. size_t read;
  208. unsigned int version;
  209. read = stream->read(&version, sizeof(unsigned int), 1);
  210. if (read != 1)
  211. {
  212. GP_ERROR("Failed to read PVR version.");
  213. return NULL;
  214. }
  215. // Rewind to start of header.
  216. if (stream->seek(0, SEEK_SET) == false)
  217. {
  218. GP_ERROR("Failed to seek backwards to beginning of file after reading PVR version.");
  219. return NULL;
  220. }
  221. // Read texture data.
  222. GLsizei width, height;
  223. GLenum format;
  224. GLubyte* data = NULL;
  225. unsigned int mipMapCount;
  226. if (version == 0x03525650)
  227. {
  228. // Modern PVR file format.
  229. data = readCompressedPVRTC(path, stream.get(), &width, &height, &format, &mipMapCount);
  230. }
  231. else
  232. {
  233. // Legacy PVR file format.
  234. data = readCompressedPVRTCLegacy(path, stream.get(), &width, &height, &format, &mipMapCount);
  235. }
  236. if (data == NULL)
  237. {
  238. GP_ERROR("Failed to read texture data from PVR file '%s'.", path);
  239. return NULL;
  240. }
  241. stream->close();
  242. int bpp = (format == GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG || format == GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG) ? 2 : 4;
  243. // Generate our texture.
  244. GLuint textureId;
  245. GL_ASSERT( glGenTextures(1, &textureId) );
  246. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, textureId) );
  247. Filter minFilter = mipMapCount > 1 ? NEAREST_MIPMAP_LINEAR : LINEAR;
  248. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter) );
  249. Texture* texture = new Texture();
  250. texture->_handle = textureId;
  251. texture->_width = width;
  252. texture->_height = height;
  253. texture->_mipmapped = mipMapCount > 1;
  254. texture->_compressed = true;
  255. texture->_minFilter = minFilter;
  256. // Load the data for each level.
  257. GLubyte* ptr = data;
  258. for (unsigned int level = 0; level < mipMapCount; ++level)
  259. {
  260. unsigned int dataSize = computePVRTCDataSize(width, height, bpp);
  261. // Upload data to GL.
  262. GL_ASSERT( glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height, 0, dataSize, ptr) );
  263. width = std::max(width >> 1, 1);
  264. height = std::max(height >> 1, 1);
  265. ptr += dataSize;
  266. }
  267. // Free data.
  268. SAFE_DELETE_ARRAY(data);
  269. return texture;
  270. }
  271. GLubyte* Texture::readCompressedPVRTC(const char* path, Stream* stream, GLsizei* width, GLsizei* height, GLenum* format, unsigned int* mipMapCount)
  272. {
  273. GP_ASSERT(stream);
  274. GP_ASSERT(path);
  275. GP_ASSERT(width);
  276. GP_ASSERT(height);
  277. GP_ASSERT(format);
  278. GP_ASSERT(mipMapCount);
  279. struct pvrtc_file_header
  280. {
  281. unsigned int version;
  282. unsigned int flags;
  283. unsigned int pixelFormat[2];
  284. unsigned int colorSpace;
  285. unsigned int channelType;
  286. unsigned int height;
  287. unsigned int width;
  288. unsigned int depth;
  289. unsigned int surfaceCount;
  290. unsigned int faceCount;
  291. unsigned int mipMapCount;
  292. unsigned int metaDataSize;
  293. };
  294. size_t read;
  295. // Read header data.
  296. pvrtc_file_header header;
  297. read = stream->read(&header, sizeof(pvrtc_file_header), 1);
  298. if (read != 1)
  299. {
  300. GP_ERROR("Failed to read PVR header data for file '%s'.", path);
  301. return NULL;
  302. }
  303. if (header.pixelFormat[1] != 0)
  304. {
  305. // Unsupported pixel format.
  306. GP_ERROR("Unsupported pixel format in PVR file '%s'. (MSB == %d != 0)", path, header.pixelFormat[1]);
  307. return NULL;
  308. }
  309. int bpp;
  310. switch (header.pixelFormat[0])
  311. {
  312. case 0:
  313. *format = GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  314. bpp = 2;
  315. break;
  316. case 1:
  317. *format = GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  318. bpp = 2;
  319. break;
  320. case 2:
  321. *format = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  322. bpp = 4;
  323. break;
  324. case 3:
  325. *format = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  326. bpp = 4;
  327. break;
  328. default:
  329. // Unsupported format.
  330. GP_ERROR("Unsupported pixel format value (%d) in PVR file '%s'.", header.pixelFormat[0], path);
  331. return NULL;
  332. }
  333. *width = (GLsizei)header.width;
  334. *height = (GLsizei)header.height;
  335. *mipMapCount = header.mipMapCount;
  336. // Skip meta-data.
  337. if (stream->seek(header.metaDataSize, SEEK_CUR) == false)
  338. {
  339. GP_ERROR("Failed to seek past header meta data in PVR file '%s'.", path);
  340. return NULL;
  341. }
  342. // Compute total size of data to be read.
  343. int w = *width;
  344. int h = *height;
  345. size_t dataSize = 0;
  346. for (unsigned int level = 0; level < header.mipMapCount; ++level)
  347. {
  348. dataSize += computePVRTCDataSize(w, h, bpp);
  349. w = std::max(w>>1, 1);
  350. h = std::max(h>>1, 1);
  351. }
  352. // Read data.
  353. GLubyte* data = new GLubyte[dataSize];
  354. read = stream->read(data, 1, dataSize);
  355. if (read != dataSize)
  356. {
  357. SAFE_DELETE_ARRAY(data);
  358. GP_ERROR("Failed to read texture data from PVR file '%s'.", path);
  359. return NULL;
  360. }
  361. return data;
  362. }
  363. GLubyte* Texture::readCompressedPVRTCLegacy(const char* path, Stream* stream, GLsizei* width, GLsizei* height, GLenum* format, unsigned int* mipMapCount)
  364. {
  365. char PVRTCIdentifier[] = "PVR!";
  366. struct pvrtc_file_header_legacy
  367. {
  368. unsigned int size; // size of the structure
  369. unsigned int height; // height of surface to be created
  370. unsigned int width; // width of input surface
  371. unsigned int mipmapCount; // number of mip-map levels requested
  372. unsigned int formatflags; // pixel format flags
  373. unsigned int dataSize; // total size in bytes
  374. unsigned int bpp; // number of bits per pixel
  375. unsigned int redBitMask; // mask for red bit
  376. unsigned int greenBitMask; // mask for green bits
  377. unsigned int blueBitMask; // mask for blue bits
  378. unsigned int alphaBitMask; // mask for alpha channel
  379. unsigned int pvrtcTag; // magic number identifying pvrtc file
  380. unsigned int surfaceCount; // number of surfaces present in the pvrtc
  381. };
  382. // Read the file header.
  383. unsigned int size = sizeof(pvrtc_file_header_legacy);
  384. pvrtc_file_header_legacy header;
  385. unsigned int read = (int)stream->read(&header, 1, size);
  386. if (read != size)
  387. {
  388. GP_ERROR("Failed to read file header for pvrtc file '%s'.", path);
  389. return NULL;
  390. }
  391. // Proper file header identifier.
  392. if (PVRTCIdentifier[0] != (char)((header.pvrtcTag >> 0) & 0xff) ||
  393. PVRTCIdentifier[1] != (char)((header.pvrtcTag >> 8) & 0xff) ||
  394. PVRTCIdentifier[2] != (char)((header.pvrtcTag >> 16) & 0xff) ||
  395. PVRTCIdentifier[3] != (char)((header.pvrtcTag >> 24) & 0xff))
  396. {
  397. GP_ERROR("Failed to load pvrtc file '%s': invalid header.", path);
  398. return NULL;
  399. }
  400. // Format flags for GLenum format.
  401. if (header.bpp == 4)
  402. {
  403. *format = header.alphaBitMask ? GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG : GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  404. }
  405. else if (header.bpp == 2)
  406. {
  407. *format = header.alphaBitMask ? GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG : GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  408. }
  409. else
  410. {
  411. GP_ERROR("Failed to load pvrtc file '%s': invalid pvrtc compressed texture format flags.", path);
  412. return NULL;
  413. }
  414. *width = (GLsizei)header.width;
  415. *height = (GLsizei)header.height;
  416. *mipMapCount = header.mipmapCount + 1; // +1 because mipmapCount does not include the base level
  417. GLubyte* data = new GLubyte[header.dataSize];
  418. read = (int)stream->read(data, 1, header.dataSize);
  419. if (read != header.dataSize)
  420. {
  421. GP_ERROR("Failed to load texture data for pvrtc file '%s'.", path);
  422. SAFE_DELETE_ARRAY(data);
  423. return NULL;
  424. }
  425. return data;
  426. }
  427. int Texture::getMaskByteIndex(unsigned int mask)
  428. {
  429. switch (mask)
  430. {
  431. case 0xff000000:
  432. return 3;
  433. case 0x00ff0000:
  434. return 2;
  435. case 0x0000ff00:
  436. return 1;
  437. case 0x000000ff:
  438. return 0;
  439. default:
  440. return -1; // no or invalid mask
  441. }
  442. }
  443. Texture* Texture::createCompressedDDS(const char* path)
  444. {
  445. GP_ASSERT(path);
  446. // DDS file structures.
  447. struct dds_pixel_format
  448. {
  449. unsigned int dwSize;
  450. unsigned int dwFlags;
  451. unsigned int dwFourCC;
  452. unsigned int dwRGBBitCount;
  453. unsigned int dwRBitMask;
  454. unsigned int dwGBitMask;
  455. unsigned int dwBBitMask;
  456. unsigned int dwABitMask;
  457. };
  458. struct dds_header
  459. {
  460. unsigned int dwSize;
  461. unsigned int dwFlags;
  462. unsigned int dwHeight;
  463. unsigned int dwWidth;
  464. unsigned int dwPitchOrLinearSize;
  465. unsigned int dwDepth;
  466. unsigned int dwMipMapCount;
  467. unsigned int dwReserved1[11];
  468. dds_pixel_format ddspf;
  469. unsigned int dwCaps;
  470. unsigned int dwCaps2;
  471. unsigned int dwCaps3;
  472. unsigned int dwCaps4;
  473. unsigned int dwReserved2;
  474. };
  475. struct dds_mip_level
  476. {
  477. GLubyte* data;
  478. GLsizei width;
  479. GLsizei height;
  480. GLsizei size;
  481. };
  482. Texture* texture = NULL;
  483. // Read DDS file.
  484. std::auto_ptr<Stream> stream(FileSystem::open(path));
  485. if (stream.get() == NULL || !stream->canRead())
  486. {
  487. GP_ERROR("Failed to open file '%s'.", path);
  488. return NULL;
  489. }
  490. // Validate DDS magic number.
  491. char code[4];
  492. if (stream->read(code, 1, 4) != 4 || strncmp(code, "DDS ", 4) != 0)
  493. {
  494. GP_ERROR("Failed to read DDS file '%s': invalid DDS magic number.", path);
  495. return NULL;
  496. }
  497. // Read DDS header.
  498. dds_header header;
  499. if (stream->read(&header, sizeof(dds_header), 1) != 1)
  500. {
  501. GP_ERROR("Failed to read header for DDS file '%s'.", path);
  502. return NULL;
  503. }
  504. if ((header.dwFlags & 0x20000/*DDSD_MIPMAPCOUNT*/) == 0)
  505. {
  506. // Mipmap count not specified (non-mipmapped texture).
  507. header.dwMipMapCount = 1;
  508. }
  509. // Allocate mip level structures.
  510. dds_mip_level* mipLevels = new dds_mip_level[header.dwMipMapCount];
  511. memset(mipLevels, 0, sizeof(dds_mip_level) * header.dwMipMapCount);
  512. GLenum format = 0;
  513. GLenum internalFormat = 0;
  514. bool compressed = false;
  515. GLsizei width = header.dwWidth;
  516. GLsizei height = header.dwHeight;
  517. Texture::Format textureFormat = Texture::UNKNOWN;
  518. if (header.ddspf.dwFlags & 0x4/*DDPF_FOURCC*/)
  519. {
  520. compressed = true;
  521. int bytesPerBlock;
  522. // Compressed.
  523. switch (header.ddspf.dwFourCC)
  524. {
  525. case ('D'|('X'<<8)|('T'<<16)|('1'<<24)):
  526. format = internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
  527. bytesPerBlock = 8;
  528. break;
  529. case ('D'|('X'<<8)|('T'<<16)|('3'<<24)):
  530. format = internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
  531. bytesPerBlock = 16;
  532. break;
  533. case ('D'|('X'<<8)|('T'<<16)|('5'<<24)):
  534. format = internalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
  535. bytesPerBlock = 16;
  536. break;
  537. case ('A'|('T'<<8)|('C'<<16)|(' '<<24)):
  538. format = internalFormat = ATC_RGB_AMD;
  539. bytesPerBlock = 8;
  540. break;
  541. case ('A'|('T'<<8)|('C'<<16)|('A'<<24)):
  542. format = internalFormat = ATC_RGBA_EXPLICIT_ALPHA_AMD;
  543. bytesPerBlock = 16;
  544. break;
  545. case ('A'|('T'<<8)|('C'<<16)|('I'<<24)):
  546. format = internalFormat = ATC_RGBA_INTERPOLATED_ALPHA_AMD;
  547. bytesPerBlock = 16;
  548. break;
  549. default:
  550. GP_ERROR("Unsupported compressed texture format (%d) for DDS file '%s'.", header.ddspf.dwFourCC, path);
  551. SAFE_DELETE_ARRAY(mipLevels);
  552. return NULL;
  553. }
  554. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  555. {
  556. dds_mip_level& level = mipLevels[i];
  557. level.width = width;
  558. level.height = height;
  559. level.size = std::max(1, (width+3) >> 2) * std::max(1, (height+3) >> 2) * bytesPerBlock;
  560. level.data = new GLubyte[level.size];
  561. if (stream->read(level.data, 1, level.size) != (unsigned int)level.size)
  562. {
  563. GP_ERROR("Failed to load dds compressed texture bytes for texture: %s", path);
  564. // Cleanup mip data.
  565. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  566. SAFE_DELETE_ARRAY(level.data);
  567. SAFE_DELETE_ARRAY(mipLevels);
  568. return texture;
  569. }
  570. width = std::max(1, width >> 1);
  571. height = std::max(1, height >> 1);
  572. }
  573. }
  574. else if (header.ddspf.dwFlags & 0x40/*DDPF_RGB*/)
  575. {
  576. // RGB/RGBA (uncompressed)
  577. bool colorConvert = false;
  578. unsigned int rmask = header.ddspf.dwRBitMask;
  579. unsigned int gmask = header.ddspf.dwGBitMask;
  580. unsigned int bmask = header.ddspf.dwBBitMask;
  581. unsigned int amask = header.ddspf.dwABitMask;
  582. int ridx = getMaskByteIndex(rmask);
  583. int gidx = getMaskByteIndex(gmask);
  584. int bidx = getMaskByteIndex(bmask);
  585. int aidx = getMaskByteIndex(amask);
  586. if (header.ddspf.dwRGBBitCount == 24)
  587. {
  588. format = internalFormat = GL_RGB;
  589. textureFormat = Texture::RGB;
  590. colorConvert = (ridx != 0) || (gidx != 1) || (bidx != 2);
  591. }
  592. else if (header.ddspf.dwRGBBitCount == 32)
  593. {
  594. format = internalFormat = GL_RGBA;
  595. textureFormat = Texture::RGBA;
  596. if (ridx == 0 && gidx == 1 && bidx == 2)
  597. {
  598. aidx = 3; // XBGR or ABGR
  599. colorConvert = false;
  600. }
  601. else if (ridx == 2 && gidx == 1 && bidx == 0)
  602. {
  603. aidx = 3; // XRGB or ARGB
  604. colorConvert = true;
  605. }
  606. else
  607. {
  608. format = 0; // invalid format
  609. }
  610. }
  611. if (format == 0)
  612. {
  613. GP_ERROR("Failed to create texture from uncompressed DDS file '%s': Unsupported color format (must be one of R8G8B8, A8R8G8B8, A8B8G8R8, X8R8G8B8, X8B8G8R8.", path);
  614. SAFE_DELETE_ARRAY(mipLevels);
  615. return NULL;
  616. }
  617. // Read data.
  618. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  619. {
  620. dds_mip_level& level = mipLevels[i];
  621. level.width = width;
  622. level.height = height;
  623. level.size = width * height * (header.ddspf.dwRGBBitCount >> 3);
  624. level.data = new GLubyte[level.size];
  625. if (stream->read(level.data, 1, level.size) != (unsigned int)level.size)
  626. {
  627. GP_ERROR("Failed to load bytes for RGB dds texture: %s", path);
  628. // Cleanup mip data.
  629. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  630. SAFE_DELETE_ARRAY(level.data);
  631. SAFE_DELETE_ARRAY(mipLevels);
  632. return texture;
  633. }
  634. width = std::max(1, width >> 1);
  635. height = std::max(1, height >> 1);
  636. }
  637. // Perform color conversion.
  638. if (colorConvert)
  639. {
  640. // Note: While it's possible to use BGRA_EXT texture formats here and avoid CPU color conversion below,
  641. // there seems to be different flavors of the BGRA extension, with some vendors requiring an internal
  642. // format of RGBA and others requiring an internal format of BGRA.
  643. // We could be smarter here later and skip color conversion in favor of GL_BGRA_EXT (for format
  644. // and/or internal format) based on which GL extensions are available.
  645. // Tip: Using A8B8G8R8 and X8B8G8R8 DDS format maps directly to GL RGBA and requires on no color conversion.
  646. GLubyte *pixel, r, g, b, a;
  647. if (format == GL_RGB)
  648. {
  649. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  650. {
  651. dds_mip_level& level = mipLevels[i];
  652. for (int j = 0; j < level.size; j += 3)
  653. {
  654. pixel = &level.data[j];
  655. r = pixel[ridx]; g = pixel[gidx]; b = pixel[bidx];
  656. pixel[0] = r; pixel[1] = g; pixel[2] = b;
  657. }
  658. }
  659. }
  660. else if (format == GL_RGBA)
  661. {
  662. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  663. {
  664. dds_mip_level& level = mipLevels[i];
  665. for (int j = 0; j < level.size; j += 4)
  666. {
  667. pixel = &level.data[j];
  668. r = pixel[ridx]; g = pixel[gidx]; b = pixel[bidx]; a = pixel[aidx];
  669. pixel[0] = r; pixel[1] = g; pixel[2] = b; pixel[3] = a;
  670. }
  671. }
  672. }
  673. }
  674. }
  675. else
  676. {
  677. // Unsupported.
  678. GP_ERROR("Failed to create texture from DDS file '%s': unsupported flags (%d).", path, header.ddspf.dwFlags);
  679. SAFE_DELETE_ARRAY(mipLevels);
  680. return NULL;
  681. }
  682. // Close file.
  683. stream->close();
  684. // Generate GL texture.
  685. GLuint textureId;
  686. GL_ASSERT( glGenTextures(1, &textureId) );
  687. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, textureId) );
  688. Filter minFilter = header.dwMipMapCount > 1 ? NEAREST_MIPMAP_LINEAR : LINEAR;
  689. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter ) );
  690. // Create gameplay texture.
  691. texture = new Texture();
  692. texture->_handle = textureId;
  693. texture->_width = header.dwWidth;
  694. texture->_height = header.dwHeight;
  695. texture->_compressed = compressed;
  696. texture->_mipmapped = header.dwMipMapCount > 1;
  697. texture->_minFilter = minFilter;
  698. // Load texture data.
  699. for (unsigned int i = 0; i < header.dwMipMapCount; ++i)
  700. {
  701. dds_mip_level& level = mipLevels[i];
  702. if (compressed)
  703. {
  704. GL_ASSERT( glCompressedTexImage2D(GL_TEXTURE_2D, i, format, level.width, level.height, 0, level.size, level.data) );
  705. }
  706. else
  707. {
  708. GL_ASSERT( glTexImage2D(GL_TEXTURE_2D, i, internalFormat, level.width, level.height, 0, format, GL_UNSIGNED_BYTE, level.data) );
  709. }
  710. // Clean up the texture data.
  711. SAFE_DELETE_ARRAY(level.data);
  712. }
  713. // Clean up mip levels structure.
  714. SAFE_DELETE_ARRAY(mipLevels);
  715. return texture;
  716. }
  717. Texture::Format Texture::getFormat() const
  718. {
  719. return _format;
  720. }
  721. const char* Texture::getPath() const
  722. {
  723. return _path.c_str();
  724. }
  725. unsigned int Texture::getWidth() const
  726. {
  727. return _width;
  728. }
  729. unsigned int Texture::getHeight() const
  730. {
  731. return _height;
  732. }
  733. TextureHandle Texture::getHandle() const
  734. {
  735. return _handle;
  736. }
  737. void Texture::generateMipmaps()
  738. {
  739. if (!_mipmapped)
  740. {
  741. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, _handle) );
  742. GL_ASSERT( glHint(GL_GENERATE_MIPMAP_HINT, GL_NICEST) );
  743. if( glGenerateMipmap != NULL )
  744. GL_ASSERT( glGenerateMipmap(GL_TEXTURE_2D) );
  745. _mipmapped = true;
  746. }
  747. }
  748. bool Texture::isMipmapped() const
  749. {
  750. return _mipmapped;
  751. }
  752. bool Texture::isCompressed() const
  753. {
  754. return _compressed;
  755. }
  756. Texture::Sampler::Sampler(Texture* texture)
  757. : _texture(texture), _wrapS(Texture::REPEAT), _wrapT(Texture::REPEAT)
  758. {
  759. GP_ASSERT(texture);
  760. _minFilter = texture->_minFilter;
  761. _magFilter = texture->_magFilter;
  762. }
  763. Texture::Sampler::~Sampler()
  764. {
  765. SAFE_RELEASE(_texture);
  766. }
  767. Texture::Sampler* Texture::Sampler::create(Texture* texture)
  768. {
  769. GP_ASSERT(texture);
  770. texture->addRef();
  771. return new Sampler(texture);
  772. }
  773. Texture::Sampler* Texture::Sampler::create(const char* path, bool generateMipmaps)
  774. {
  775. Texture* texture = Texture::create(path, generateMipmaps);
  776. return texture ? new Sampler(texture) : NULL;
  777. }
  778. void Texture::Sampler::setWrapMode(Wrap wrapS, Wrap wrapT)
  779. {
  780. _wrapS = wrapS;
  781. _wrapT = wrapT;
  782. }
  783. void Texture::Sampler::setFilterMode(Filter minificationFilter, Filter magnificationFilter)
  784. {
  785. _minFilter = minificationFilter;
  786. _magFilter = magnificationFilter;
  787. }
  788. Texture* Texture::Sampler::getTexture() const
  789. {
  790. return _texture;
  791. }
  792. void Texture::Sampler::bind()
  793. {
  794. GP_ASSERT(_texture);
  795. GL_ASSERT( glBindTexture(GL_TEXTURE_2D, _texture->_handle) );
  796. if (_texture->_minFilter != _minFilter)
  797. {
  798. _texture->_minFilter = _minFilter;
  799. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (GLenum)_minFilter) );
  800. }
  801. if (_texture->_magFilter != _magFilter)
  802. {
  803. _texture->_magFilter = _magFilter;
  804. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (GLenum)_magFilter) );
  805. }
  806. if (_texture->_wrapS != _wrapS)
  807. {
  808. _texture->_wrapS = _wrapS;
  809. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (GLenum)_wrapS) );
  810. }
  811. if (_texture->_wrapT != _wrapT)
  812. {
  813. _texture->_wrapT = _wrapT;
  814. GL_ASSERT( glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (GLenum)_wrapT) );
  815. }
  816. }
  817. }