Texture.cpp 28 KB

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