Image.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/Profiler.h"
  25. #include "../IO/File.h"
  26. #include "../IO/FileSystem.h"
  27. #include "../IO/Log.h"
  28. #include "../Resource/Decompress.h"
  29. #include <JO/jo_jpeg.h>
  30. #include <SDL/include/SDL_surface.h>
  31. #include <STB/stb_image.h>
  32. #include <STB/stb_image_write.h>
  33. #include <crunch/inc/crnlib.h>
  34. #include "../DebugNew.h"
  35. extern "C" unsigned char* stbi_write_png_to_mem(unsigned char* pixels, int stride_bytes, int x, int y, int n, int* out_len);
  36. #ifndef MAKEFOURCC
  37. #define MAKEFOURCC(ch0, ch1, ch2, ch3) ((unsigned)(ch0) | ((unsigned)(ch1) << 8) | ((unsigned)(ch2) << 16) | ((unsigned)(ch3) << 24))
  38. #endif
  39. #define FOURCC_DXT1 (MAKEFOURCC('D','X','T','1'))
  40. #define FOURCC_DXT2 (MAKEFOURCC('D','X','T','2'))
  41. #define FOURCC_DXT3 (MAKEFOURCC('D','X','T','3'))
  42. #define FOURCC_DXT4 (MAKEFOURCC('D','X','T','4'))
  43. #define FOURCC_DXT5 (MAKEFOURCC('D','X','T','5'))
  44. #define FOURCC_DX10 (MAKEFOURCC('D','X','1','0'))
  45. static const unsigned DDSCAPS_COMPLEX = 0x00000008U;
  46. static const unsigned DDSCAPS_TEXTURE = 0x00001000U;
  47. static const unsigned DDSCAPS_MIPMAP = 0x00400000U;
  48. static const unsigned DDSCAPS2_VOLUME = 0x00200000U;
  49. static const unsigned DDSCAPS2_CUBEMAP = 0x00000200U;
  50. static const unsigned DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400U;
  51. static const unsigned DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800U;
  52. static const unsigned DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000U;
  53. static const unsigned DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000U;
  54. static const unsigned DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000U;
  55. static const unsigned DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000U;
  56. static const unsigned DDSCAPS2_CUBEMAP_ALL_FACES = 0x0000FC00U;
  57. // DX10 flags
  58. static const unsigned DDS_DIMENSION_TEXTURE1D = 2;
  59. static const unsigned DDS_DIMENSION_TEXTURE2D = 3;
  60. static const unsigned DDS_DIMENSION_TEXTURE3D = 4;
  61. static const unsigned DDS_RESOURCE_MISC_TEXTURECUBE = 0x4;
  62. static const unsigned DDS_DXGI_FORMAT_R8G8B8A8_UNORM = 28;
  63. static const unsigned DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB = 26;
  64. static const unsigned DDS_DXGI_FORMAT_BC1_UNORM = 71;
  65. static const unsigned DDS_DXGI_FORMAT_BC1_UNORM_SRGB = 72;
  66. static const unsigned DDS_DXGI_FORMAT_BC2_UNORM = 74;
  67. static const unsigned DDS_DXGI_FORMAT_BC2_UNORM_SRGB = 75;
  68. static const unsigned DDS_DXGI_FORMAT_BC3_UNORM = 77;
  69. static const unsigned DDS_DXGI_FORMAT_BC3_UNORM_SRGB = 78;
  70. namespace Atomic
  71. {
  72. /// DirectDraw color key definition.
  73. struct DDColorKey
  74. {
  75. unsigned dwColorSpaceLowValue_;
  76. unsigned dwColorSpaceHighValue_;
  77. };
  78. /// DirectDraw pixel format definition.
  79. struct DDPixelFormat
  80. {
  81. unsigned dwSize_;
  82. unsigned dwFlags_;
  83. unsigned dwFourCC_;
  84. union
  85. {
  86. unsigned dwRGBBitCount_;
  87. unsigned dwYUVBitCount_;
  88. unsigned dwZBufferBitDepth_;
  89. unsigned dwAlphaBitDepth_;
  90. unsigned dwLuminanceBitCount_;
  91. unsigned dwBumpBitCount_;
  92. unsigned dwPrivateFormatBitCount_;
  93. };
  94. union
  95. {
  96. unsigned dwRBitMask_;
  97. unsigned dwYBitMask_;
  98. unsigned dwStencilBitDepth_;
  99. unsigned dwLuminanceBitMask_;
  100. unsigned dwBumpDuBitMask_;
  101. unsigned dwOperations_;
  102. };
  103. union
  104. {
  105. unsigned dwGBitMask_;
  106. unsigned dwUBitMask_;
  107. unsigned dwZBitMask_;
  108. unsigned dwBumpDvBitMask_;
  109. struct
  110. {
  111. unsigned short wFlipMSTypes_;
  112. unsigned short wBltMSTypes_;
  113. } multiSampleCaps_;
  114. };
  115. union
  116. {
  117. unsigned dwBBitMask_;
  118. unsigned dwVBitMask_;
  119. unsigned dwStencilBitMask_;
  120. unsigned dwBumpLuminanceBitMask_;
  121. };
  122. union
  123. {
  124. unsigned dwRGBAlphaBitMask_;
  125. unsigned dwYUVAlphaBitMask_;
  126. unsigned dwLuminanceAlphaBitMask_;
  127. unsigned dwRGBZBitMask_;
  128. unsigned dwYUVZBitMask_;
  129. };
  130. };
  131. /// DirectDraw surface capabilities.
  132. struct DDSCaps2
  133. {
  134. unsigned dwCaps_;
  135. unsigned dwCaps2_;
  136. unsigned dwCaps3_;
  137. union
  138. {
  139. unsigned dwCaps4_;
  140. unsigned dwVolumeDepth_;
  141. };
  142. };
  143. struct DDSHeader10
  144. {
  145. unsigned dxgiFormat;
  146. unsigned resourceDimension;
  147. unsigned miscFlag;
  148. unsigned arraySize;
  149. unsigned reserved;
  150. };
  151. /// DirectDraw surface description.
  152. struct DDSurfaceDesc2
  153. {
  154. unsigned dwSize_;
  155. unsigned dwFlags_;
  156. unsigned dwHeight_;
  157. unsigned dwWidth_;
  158. union
  159. {
  160. unsigned lPitch_;
  161. unsigned dwLinearSize_;
  162. };
  163. union
  164. {
  165. unsigned dwBackBufferCount_;
  166. unsigned dwDepth_;
  167. };
  168. union
  169. {
  170. unsigned dwMipMapCount_;
  171. unsigned dwRefreshRate_;
  172. unsigned dwSrcVBHandle_;
  173. };
  174. unsigned dwAlphaBitDepth_;
  175. unsigned dwReserved_;
  176. unsigned lpSurface_; // Do not define as a void pointer, as it is 8 bytes in a 64bit build
  177. union
  178. {
  179. DDColorKey ddckCKDestOverlay_;
  180. unsigned dwEmptyFaceColor_;
  181. };
  182. DDColorKey ddckCKDestBlt_;
  183. DDColorKey ddckCKSrcOverlay_;
  184. DDColorKey ddckCKSrcBlt_;
  185. union
  186. {
  187. DDPixelFormat ddpfPixelFormat_;
  188. unsigned dwFVF_;
  189. };
  190. DDSCaps2 ddsCaps_;
  191. unsigned dwTextureStage_;
  192. };
  193. bool CompressedLevel::Decompress(unsigned char* dest)
  194. {
  195. if (!data_)
  196. return false;
  197. switch (format_)
  198. {
  199. case CF_DXT1:
  200. case CF_DXT3:
  201. case CF_DXT5:
  202. DecompressImageDXT(dest, data_, width_, height_, depth_, format_);
  203. return true;
  204. case CF_ETC1:
  205. DecompressImageETC(dest, data_, width_, height_);
  206. return true;
  207. case CF_PVRTC_RGB_2BPP:
  208. case CF_PVRTC_RGBA_2BPP:
  209. case CF_PVRTC_RGB_4BPP:
  210. case CF_PVRTC_RGBA_4BPP:
  211. DecompressImagePVRTC(dest, data_, width_, height_, format_);
  212. return true;
  213. default:
  214. // Unknown format
  215. return false;
  216. }
  217. }
  218. Image::Image(Context* context) :
  219. Resource(context),
  220. width_(0),
  221. height_(0),
  222. depth_(0),
  223. components_(0),
  224. cubemap_(false),
  225. array_(false),
  226. sRGB_(false)
  227. {
  228. }
  229. Image::~Image()
  230. {
  231. }
  232. void Image::RegisterObject(Context* context)
  233. {
  234. context->RegisterFactory<Image>();
  235. }
  236. bool Image::BeginLoad(Deserializer& source)
  237. {
  238. // Check for DDS, KTX or PVR compressed format
  239. String fileID = source.ReadFileID();
  240. if (fileID == "DDS ")
  241. {
  242. // DDS compressed format
  243. DDSurfaceDesc2 ddsd;
  244. source.Read(&ddsd, sizeof(ddsd));
  245. // DDS DX10+
  246. const bool hasDXGI = ddsd.ddpfPixelFormat_.dwFourCC_ == FOURCC_DX10;
  247. DDSHeader10 dxgiHeader;
  248. if (hasDXGI)
  249. source.Read(&dxgiHeader, sizeof(dxgiHeader));
  250. unsigned fourCC = ddsd.ddpfPixelFormat_.dwFourCC_;
  251. // If the DXGI header is available then remap formats and check sRGB
  252. if (hasDXGI)
  253. {
  254. switch (dxgiHeader.dxgiFormat)
  255. {
  256. case DDS_DXGI_FORMAT_BC1_UNORM:
  257. case DDS_DXGI_FORMAT_BC1_UNORM_SRGB:
  258. fourCC = FOURCC_DXT1;
  259. break;
  260. case DDS_DXGI_FORMAT_BC2_UNORM:
  261. case DDS_DXGI_FORMAT_BC2_UNORM_SRGB:
  262. fourCC = FOURCC_DXT3;
  263. break;
  264. case DDS_DXGI_FORMAT_BC3_UNORM:
  265. case DDS_DXGI_FORMAT_BC3_UNORM_SRGB:
  266. fourCC = FOURCC_DXT5;
  267. break;
  268. case DDS_DXGI_FORMAT_R8G8B8A8_UNORM:
  269. case DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
  270. fourCC = 0;
  271. break;
  272. default:
  273. LOGERROR("Unrecognized DDS DXGI image format");
  274. return false;
  275. }
  276. // Check the internal sRGB formats
  277. if (dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_BC1_UNORM_SRGB ||
  278. dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_BC2_UNORM_SRGB ||
  279. dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_BC3_UNORM_SRGB ||
  280. dxgiHeader.dxgiFormat == DDS_DXGI_FORMAT_R8G8B8A8_UNORM_SRGB)
  281. {
  282. sRGB_ = true;
  283. }
  284. }
  285. switch (fourCC)
  286. {
  287. case FOURCC_DXT1:
  288. compressedFormat_ = CF_DXT1;
  289. components_ = 3;
  290. break;
  291. case FOURCC_DXT3:
  292. compressedFormat_ = CF_DXT3;
  293. components_ = 4;
  294. break;
  295. case FOURCC_DXT5:
  296. compressedFormat_ = CF_DXT5;
  297. components_ = 4;
  298. break;
  299. case 0:
  300. if (ddsd.ddpfPixelFormat_.dwRGBBitCount_ != 32 && ddsd.ddpfPixelFormat_.dwRGBBitCount_ != 24 &&
  301. ddsd.ddpfPixelFormat_.dwRGBBitCount_ != 16)
  302. {
  303. LOGERROR("Unsupported DDS pixel byte size");
  304. return false;
  305. }
  306. compressedFormat_ = CF_RGBA;
  307. components_ = 4;
  308. break;
  309. default:
  310. LOGERROR("Unrecognized DDS image format");
  311. return false;
  312. }
  313. // Is it a cube map or texture array? If so determine the size of the image chain.
  314. cubemap_ = (ddsd.ddsCaps_.dwCaps2_ & DDSCAPS2_CUBEMAP_ALL_FACES) != 0 || (hasDXGI && (dxgiHeader.miscFlag & DDS_RESOURCE_MISC_TEXTURECUBE) != 0);
  315. unsigned imageChainCount = 1;
  316. if (cubemap_)
  317. imageChainCount = 6;
  318. else if (hasDXGI && dxgiHeader.arraySize > 1)
  319. {
  320. imageChainCount = dxgiHeader.arraySize;
  321. array_ = true;
  322. }
  323. // Calculate the size of the data
  324. unsigned dataSize = 0;
  325. if (compressedFormat_ != CF_RGBA)
  326. {
  327. const unsigned blockSize = compressedFormat_ == CF_DXT1 ? 8 : 16; //DXT1/BC1 is 8 bytes, DXT3/BC2 and DXT5/BC3 are 16 bytes
  328. // Add 3 to ensure valid block: ie 2x2 fits uses a whole 4x4 block
  329. unsigned blocksWide = (ddsd.dwWidth_ + 3) / 4;
  330. unsigned blocksHeight = (ddsd.dwHeight_ + 3) / 4;
  331. dataSize = blocksWide * blocksHeight * blockSize;
  332. // Calculate mip data size
  333. unsigned x = ddsd.dwWidth_ / 2;
  334. unsigned y = ddsd.dwHeight_ / 2;
  335. unsigned z = ddsd.dwDepth_ / 2;
  336. for (unsigned level = ddsd.dwMipMapCount_; level > 0; x /= 2, y /= 2, z /= 2, level -= 1)
  337. {
  338. blocksWide = (Max(x, 1) + 3) / 4;
  339. blocksHeight = (Max(y, 1) + 3) / 4;
  340. dataSize += blockSize * blocksWide * blocksHeight * Max(z, 1);
  341. }
  342. }
  343. else
  344. {
  345. dataSize = (ddsd.ddpfPixelFormat_.dwRGBBitCount_ / 8) * ddsd.dwWidth_ * ddsd.dwHeight_ * Max(ddsd.dwDepth_, 1);
  346. // Calculate mip data size
  347. unsigned x = ddsd.dwWidth_ / 2;
  348. unsigned y = ddsd.dwHeight_ / 2;
  349. unsigned z = ddsd.dwDepth_ / 2;
  350. for (unsigned level = ddsd.dwMipMapCount_; level > 0; x /= 2, y /= 2, z /= 2, level -= 1)
  351. dataSize += (ddsd.ddpfPixelFormat_.dwRGBBitCount_ / 8) * Max(x, 1) * Max(y, 1) * Max(z, 1);
  352. }
  353. // Do not use a shared ptr here, in case nothing is refcounting the image outside this function.
  354. // A raw pointer is fine as the image chain (if needed) uses shared ptr's properly
  355. Image* currentImage = this;
  356. for (unsigned faceIndex = 0; faceIndex < imageChainCount; ++faceIndex)
  357. {
  358. currentImage->data_ = new unsigned char[dataSize];
  359. currentImage->cubemap_ = cubemap_;
  360. currentImage->array_ = array_;
  361. currentImage->components_ = components_;
  362. currentImage->compressedFormat_ = compressedFormat_;
  363. currentImage->width_ = ddsd.dwWidth_;
  364. currentImage->height_ = ddsd.dwHeight_;
  365. currentImage->depth_ = ddsd.dwDepth_;
  366. currentImage->numCompressedLevels_ = ddsd.dwMipMapCount_;
  367. if (!currentImage->numCompressedLevels_)
  368. currentImage->numCompressedLevels_ = 1;
  369. // Memory use needs to be exact per image as it's used for verifying the data size in GetCompressedLevel()
  370. // even though it would be more proper for the first image to report the size of all siblings combined
  371. currentImage->SetMemoryUse(dataSize);
  372. source.Read(currentImage->data_.Get(), dataSize);
  373. if (faceIndex < imageChainCount - 1)
  374. {
  375. // Build the image chain
  376. SharedPtr<Image> nextImage(new Image(context_));
  377. currentImage->nextSibling_ = nextImage;
  378. currentImage = nextImage;
  379. }
  380. }
  381. // If uncompressed DDS, convert the data to 8bit RGBA as the texture classes can not currently use eg. RGB565 format
  382. if (compressedFormat_ == CF_RGBA)
  383. {
  384. PROFILE(ConvertDDSToRGBA);
  385. SharedPtr<Image> currentImage(this);
  386. while (currentImage.NotNull())
  387. {
  388. unsigned sourcePixelByteSize = ddsd.ddpfPixelFormat_.dwRGBBitCount_ >> 3;
  389. unsigned numPixels = dataSize / sourcePixelByteSize;
  390. #define ADJUSTSHIFT(mask, l, r) \
  391. if (mask && mask >= 0x100) \
  392. { \
  393. while ((mask >> r) >= 0x100) \
  394. ++r; \
  395. } \
  396. else if (mask && mask < 0x80) \
  397. { \
  398. while ((mask << l) < 0x80) \
  399. ++l; \
  400. }
  401. unsigned rShiftL = 0, gShiftL = 0, bShiftL = 0, aShiftL = 0;
  402. unsigned rShiftR = 0, gShiftR = 0, bShiftR = 0, aShiftR = 0;
  403. unsigned rMask = ddsd.ddpfPixelFormat_.dwRBitMask_;
  404. unsigned gMask = ddsd.ddpfPixelFormat_.dwGBitMask_;
  405. unsigned bMask = ddsd.ddpfPixelFormat_.dwBBitMask_;
  406. unsigned aMask = ddsd.ddpfPixelFormat_.dwRGBAlphaBitMask_;
  407. ADJUSTSHIFT(rMask, rShiftL, rShiftR)
  408. ADJUSTSHIFT(gMask, gShiftL, gShiftR)
  409. ADJUSTSHIFT(bMask, bShiftL, bShiftR)
  410. ADJUSTSHIFT(aMask, aShiftL, aShiftR)
  411. SharedArrayPtr<unsigned char> rgbaData(new unsigned char[numPixels * 4]);
  412. SetMemoryUse(numPixels * 4);
  413. switch (sourcePixelByteSize)
  414. {
  415. case 4:
  416. {
  417. unsigned* src = (unsigned*)currentImage->data_.Get();
  418. unsigned char* dest = rgbaData.Get();
  419. while (numPixels--)
  420. {
  421. unsigned pixels = *src++;
  422. *dest++ = ((pixels & rMask) << rShiftL) >> rShiftR;
  423. *dest++ = ((pixels & gMask) << gShiftL) >> gShiftR;
  424. *dest++ = ((pixels & bMask) << bShiftL) >> bShiftR;
  425. *dest++ = ((pixels & aMask) << aShiftL) >> aShiftR;
  426. }
  427. }
  428. break;
  429. case 3:
  430. {
  431. unsigned char* src = currentImage->data_.Get();
  432. unsigned char* dest = rgbaData.Get();
  433. while (numPixels--)
  434. {
  435. unsigned pixels = src[0] | (src[1] << 8) | (src[2] << 16);
  436. src += 3;
  437. *dest++ = ((pixels & rMask) << rShiftL) >> rShiftR;
  438. *dest++ = ((pixels & gMask) << gShiftL) >> gShiftR;
  439. *dest++ = ((pixels & bMask) << bShiftL) >> bShiftR;
  440. *dest++ = ((pixels & aMask) << aShiftL) >> aShiftR;
  441. }
  442. }
  443. break;
  444. default:
  445. {
  446. unsigned short* src = (unsigned short*)currentImage->data_.Get();
  447. unsigned char* dest = rgbaData.Get();
  448. while (numPixels--)
  449. {
  450. unsigned short pixels = *src++;
  451. *dest++ = ((pixels & rMask) << rShiftL) >> rShiftR;
  452. *dest++ = ((pixels & gMask) << gShiftL) >> gShiftR;
  453. *dest++ = ((pixels & bMask) << bShiftL) >> bShiftR;
  454. *dest++ = ((pixels & aMask) << aShiftL) >> aShiftR;
  455. }
  456. }
  457. break;
  458. }
  459. // Replace with converted data
  460. currentImage->data_ = rgbaData;
  461. currentImage = currentImage->GetNextSibling();
  462. }
  463. }
  464. }
  465. else if (fileID == "\253KTX")
  466. {
  467. source.Seek(12);
  468. unsigned endianness = source.ReadUInt();
  469. unsigned type = source.ReadUInt();
  470. /* unsigned typeSize = */ source.ReadUInt();
  471. unsigned format = source.ReadUInt();
  472. unsigned internalFormat = source.ReadUInt();
  473. /* unsigned baseInternalFormat = */ source.ReadUInt();
  474. unsigned width = source.ReadUInt();
  475. unsigned height = source.ReadUInt();
  476. unsigned depth = source.ReadUInt();
  477. /* unsigned arrayElements = */ source.ReadUInt();
  478. unsigned faces = source.ReadUInt();
  479. unsigned mipmaps = source.ReadUInt();
  480. unsigned keyValueBytes = source.ReadUInt();
  481. if (endianness != 0x04030201)
  482. {
  483. LOGERROR("Big-endian KTX files not supported");
  484. return false;
  485. }
  486. if (type != 0 || format != 0)
  487. {
  488. LOGERROR("Uncompressed KTX files not supported");
  489. return false;
  490. }
  491. if (faces > 1 || depth > 1)
  492. {
  493. LOGERROR("3D or cube KTX files not supported");
  494. return false;
  495. }
  496. if (mipmaps == 0)
  497. {
  498. LOGERROR("KTX files without explicitly specified mipmap count not supported");
  499. return false;
  500. }
  501. switch (internalFormat)
  502. {
  503. case 0x83f1:
  504. compressedFormat_ = CF_DXT1;
  505. components_ = 4;
  506. break;
  507. case 0x83f2:
  508. compressedFormat_ = CF_DXT3;
  509. components_ = 4;
  510. break;
  511. case 0x83f3:
  512. compressedFormat_ = CF_DXT5;
  513. components_ = 4;
  514. break;
  515. case 0x8d64:
  516. compressedFormat_ = CF_ETC1;
  517. components_ = 3;
  518. break;
  519. case 0x8c00:
  520. compressedFormat_ = CF_PVRTC_RGB_4BPP;
  521. components_ = 3;
  522. break;
  523. case 0x8c01:
  524. compressedFormat_ = CF_PVRTC_RGB_2BPP;
  525. components_ = 3;
  526. break;
  527. case 0x8c02:
  528. compressedFormat_ = CF_PVRTC_RGBA_4BPP;
  529. components_ = 4;
  530. break;
  531. case 0x8c03:
  532. compressedFormat_ = CF_PVRTC_RGBA_2BPP;
  533. components_ = 4;
  534. break;
  535. default:
  536. compressedFormat_ = CF_NONE;
  537. break;
  538. }
  539. if (compressedFormat_ == CF_NONE)
  540. {
  541. LOGERROR("Unsupported texture format in KTX file");
  542. return false;
  543. }
  544. source.Seek(source.GetPosition() + keyValueBytes);
  545. unsigned dataSize = (unsigned)(source.GetSize() - source.GetPosition() - mipmaps * sizeof(unsigned));
  546. data_ = new unsigned char[dataSize];
  547. width_ = width;
  548. height_ = height;
  549. numCompressedLevels_ = mipmaps;
  550. unsigned dataOffset = 0;
  551. for (unsigned i = 0; i < mipmaps; ++i)
  552. {
  553. unsigned levelSize = source.ReadUInt();
  554. if (levelSize + dataOffset > dataSize)
  555. {
  556. LOGERROR("KTX mipmap level data size exceeds file size");
  557. return false;
  558. }
  559. source.Read(&data_[dataOffset], levelSize);
  560. dataOffset += levelSize;
  561. if (source.GetPosition() & 3)
  562. source.Seek((source.GetPosition() + 3) & 0xfffffffc);
  563. }
  564. SetMemoryUse(dataSize);
  565. }
  566. else if (fileID == "PVR\3")
  567. {
  568. /* unsigned flags = */ source.ReadUInt();
  569. unsigned pixelFormatLo = source.ReadUInt();
  570. /* unsigned pixelFormatHi = */ source.ReadUInt();
  571. /* unsigned colourSpace = */ source.ReadUInt();
  572. /* unsigned channelType = */ source.ReadUInt();
  573. unsigned height = source.ReadUInt();
  574. unsigned width = source.ReadUInt();
  575. unsigned depth = source.ReadUInt();
  576. /* unsigned numSurfaces = */ source.ReadUInt();
  577. unsigned numFaces = source.ReadUInt();
  578. unsigned mipmapCount = source.ReadUInt();
  579. unsigned metaDataSize = source.ReadUInt();
  580. if (depth > 1 || numFaces > 1)
  581. {
  582. LOGERROR("3D or cube PVR files not supported");
  583. return false;
  584. }
  585. if (mipmapCount == 0)
  586. {
  587. LOGERROR("PVR files without explicitly specified mipmap count not supported");
  588. return false;
  589. }
  590. switch (pixelFormatLo)
  591. {
  592. case 0:
  593. compressedFormat_ = CF_PVRTC_RGB_2BPP;
  594. components_ = 3;
  595. break;
  596. case 1:
  597. compressedFormat_ = CF_PVRTC_RGBA_2BPP;
  598. components_ = 4;
  599. break;
  600. case 2:
  601. compressedFormat_ = CF_PVRTC_RGB_4BPP;
  602. components_ = 3;
  603. break;
  604. case 3:
  605. compressedFormat_ = CF_PVRTC_RGBA_4BPP;
  606. components_ = 4;
  607. break;
  608. case 6:
  609. compressedFormat_ = CF_ETC1;
  610. components_ = 3;
  611. break;
  612. case 7:
  613. compressedFormat_ = CF_DXT1;
  614. components_ = 4;
  615. break;
  616. case 9:
  617. compressedFormat_ = CF_DXT3;
  618. components_ = 4;
  619. break;
  620. case 11:
  621. compressedFormat_ = CF_DXT5;
  622. components_ = 4;
  623. break;
  624. default:
  625. compressedFormat_ = CF_NONE;
  626. break;
  627. }
  628. if (compressedFormat_ == CF_NONE)
  629. {
  630. LOGERROR("Unsupported texture format in PVR file");
  631. return false;
  632. }
  633. source.Seek(source.GetPosition() + metaDataSize);
  634. unsigned dataSize = source.GetSize() - source.GetPosition();
  635. data_ = new unsigned char[dataSize];
  636. width_ = width;
  637. height_ = height;
  638. numCompressedLevels_ = mipmapCount;
  639. source.Read(data_.Get(), dataSize);
  640. SetMemoryUse(dataSize);
  641. }
  642. else
  643. {
  644. // Not DDS, KTX or PVR, use STBImage to load other image formats as uncompressed
  645. source.Seek(0);
  646. int width, height;
  647. unsigned components;
  648. unsigned char* pixelData = GetImageData(source, width, height, components);
  649. if (!pixelData)
  650. {
  651. LOGERROR("Could not load image " + source.GetName() + ": " + String(stbi_failure_reason()));
  652. return false;
  653. }
  654. SetSize(width, height, components);
  655. SetData(pixelData);
  656. FreeImageData(pixelData);
  657. }
  658. return true;
  659. }
  660. bool Image::Save(Serializer& dest) const
  661. {
  662. PROFILE(SaveImage);
  663. if (IsCompressed())
  664. {
  665. LOGERROR("Can not save compressed image " + GetName());
  666. return false;
  667. }
  668. if (!data_)
  669. {
  670. LOGERROR("Can not save zero-sized image " + GetName());
  671. return false;
  672. }
  673. int len;
  674. unsigned char* png = stbi_write_png_to_mem(data_.Get(), 0, width_, height_, components_, &len);
  675. bool success = dest.Write(png, (unsigned)len) == (unsigned)len;
  676. free(png);
  677. return success;
  678. }
  679. bool Image::SetSize(int width, int height, unsigned components)
  680. {
  681. return SetSize(width, height, 1, components);
  682. }
  683. bool Image::SetSize(int width, int height, int depth, unsigned components)
  684. {
  685. if (width == width_ && height == height_ && depth == depth_ && components == components_)
  686. return true;
  687. if (width <= 0 || height <= 0 || depth <= 0)
  688. return false;
  689. if (components > 4)
  690. {
  691. LOGERROR("More than 4 color components are not supported");
  692. return false;
  693. }
  694. data_ = new unsigned char[width * height * depth * components];
  695. width_ = width;
  696. height_ = height;
  697. depth_ = depth;
  698. components_ = components;
  699. compressedFormat_ = CF_NONE;
  700. numCompressedLevels_ = 0;
  701. nextLevel_.Reset();
  702. SetMemoryUse(width * height * depth * components);
  703. return true;
  704. }
  705. void Image::SetPixel(int x, int y, const Color& color)
  706. {
  707. SetPixelInt(x, y, 0, color.ToUInt());
  708. }
  709. void Image::SetPixel(int x, int y, int z, const Color& color)
  710. {
  711. SetPixelInt(x, y, z, color.ToUInt());
  712. }
  713. void Image::SetPixelInt(int x, int y, unsigned uintColor)
  714. {
  715. SetPixelInt(x, y, 0, uintColor);
  716. }
  717. void Image::SetPixelInt(int x, int y, int z, unsigned uintColor)
  718. {
  719. if (!data_ || x < 0 || x >= width_ || y < 0 || y >= height_ || z < 0 || z >= depth_ || IsCompressed())
  720. return;
  721. unsigned char* dest = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  722. unsigned char* src = (unsigned char*)&uintColor;
  723. switch (components_)
  724. {
  725. case 4:
  726. dest[3] = src[3];
  727. // Fall through
  728. case 3:
  729. dest[2] = src[2];
  730. // Fall through
  731. case 2:
  732. dest[1] = src[1];
  733. // Fall through
  734. default:
  735. dest[0] = src[0];
  736. break;
  737. }
  738. }
  739. void Image::SetData(const unsigned char* pixelData)
  740. {
  741. if (!data_)
  742. return;
  743. if (IsCompressed())
  744. {
  745. LOGERROR("Can not set new pixel data for a compressed image");
  746. return;
  747. }
  748. memcpy(data_.Get(), pixelData, width_ * height_ * depth_ * components_);
  749. nextLevel_.Reset();
  750. }
  751. bool Image::LoadColorLUT(Deserializer& source)
  752. {
  753. String fileID = source.ReadFileID();
  754. if (fileID == "DDS " || fileID == "\253KTX" || fileID == "PVR\3")
  755. {
  756. LOGERROR("Invalid image format, can not load image");
  757. return false;
  758. }
  759. source.Seek(0);
  760. int width, height;
  761. unsigned components;
  762. unsigned char* pixelDataIn = GetImageData(source, width, height, components);
  763. if (!pixelDataIn)
  764. {
  765. LOGERROR("Could not load image " + source.GetName() + ": " + String(stbi_failure_reason()));
  766. return false;
  767. }
  768. if (components != 3)
  769. {
  770. LOGERROR("Invalid image format, can not load image");
  771. return false;
  772. }
  773. SetSize(COLOR_LUT_SIZE, COLOR_LUT_SIZE, COLOR_LUT_SIZE, components);
  774. SetMemoryUse(width_ * height_ * depth_ * components);
  775. unsigned char* pixelDataOut = GetData();
  776. for (int z = 0; z < depth_; ++z)
  777. {
  778. for (int y = 0; y < height_; ++y)
  779. {
  780. unsigned char* in = &pixelDataIn[z * width_ * 3 + y * width * 3];
  781. unsigned char* out = &pixelDataOut[z * width_ * height_ * 3 + y * width_ * 3];
  782. for (int x = 0; x < width_ * 3; x += 3)
  783. {
  784. out[x] = in[x];
  785. out[x + 1] = in[x + 1];
  786. out[x + 2] = in[x + 2];
  787. }
  788. }
  789. }
  790. FreeImageData(pixelDataIn);
  791. return true;
  792. }
  793. bool Image::FlipHorizontal()
  794. {
  795. if (!data_)
  796. return false;
  797. if (depth_ > 1)
  798. {
  799. LOGERROR("FlipHorizontal not supported for 3D images");
  800. return false;
  801. }
  802. if (!IsCompressed())
  803. {
  804. SharedArrayPtr<unsigned char> newData(new unsigned char[width_ * height_ * components_]);
  805. unsigned rowSize = width_ * components_;
  806. for (int y = 0; y < height_; ++y)
  807. {
  808. for (int x = 0; x < width_; ++x)
  809. {
  810. for (unsigned c = 0; c < components_; ++c)
  811. newData[y * rowSize + x * components_ + c] = data_[y * rowSize + (width_ - x - 1) * components_ + c];
  812. }
  813. }
  814. data_ = newData;
  815. }
  816. else
  817. {
  818. if (compressedFormat_ > CF_DXT5)
  819. {
  820. LOGERROR("FlipHorizontal not yet implemented for other compressed formats than RGBA & DXT1,3,5");
  821. return false;
  822. }
  823. // Memory use = combined size of the compressed mip levels
  824. SharedArrayPtr<unsigned char> newData(new unsigned char[GetMemoryUse()]);
  825. unsigned dataOffset = 0;
  826. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  827. {
  828. CompressedLevel level = GetCompressedLevel(i);
  829. if (!level.data_)
  830. {
  831. LOGERROR("Got compressed level with no data, aborting horizontal flip");
  832. return false;
  833. }
  834. for (unsigned y = 0; y < level.rows_; ++y)
  835. {
  836. for (unsigned x = 0; x < level.rowSize_; x += level.blockSize_)
  837. {
  838. unsigned char* src = level.data_ + y * level.rowSize_ + (level.rowSize_ - level.blockSize_ - x);
  839. unsigned char* dest = newData.Get() + y * level.rowSize_ + x;
  840. FlipBlockHorizontal(dest, src, compressedFormat_);
  841. }
  842. }
  843. dataOffset += level.dataSize_;
  844. }
  845. data_ = newData;
  846. }
  847. return true;
  848. }
  849. bool Image::FlipVertical()
  850. {
  851. if (!data_)
  852. return false;
  853. if (depth_ > 1)
  854. {
  855. LOGERROR("FlipVertical not supported for 3D images");
  856. return false;
  857. }
  858. if (!IsCompressed())
  859. {
  860. SharedArrayPtr<unsigned char> newData(new unsigned char[width_ * height_ * components_]);
  861. unsigned rowSize = width_ * components_;
  862. for (int y = 0; y < height_; ++y)
  863. memcpy(&newData[(height_ - y - 1) * rowSize], &data_[y * rowSize], rowSize);
  864. data_ = newData;
  865. }
  866. else
  867. {
  868. if (compressedFormat_ > CF_DXT5)
  869. {
  870. LOGERROR("FlipVertical not yet implemented for other compressed formats than DXT1,3,5");
  871. return false;
  872. }
  873. // Memory use = combined size of the compressed mip levels
  874. SharedArrayPtr<unsigned char> newData(new unsigned char[GetMemoryUse()]);
  875. unsigned dataOffset = 0;
  876. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  877. {
  878. CompressedLevel level = GetCompressedLevel(i);
  879. if (!level.data_)
  880. {
  881. LOGERROR("Got compressed level with no data, aborting vertical flip");
  882. return false;
  883. }
  884. for (unsigned y = 0; y < level.rows_; ++y)
  885. {
  886. unsigned char* src = level.data_ + y * level.rowSize_;
  887. unsigned char* dest = newData.Get() + dataOffset + (level.rows_ - y - 1) * level.rowSize_;
  888. for (unsigned x = 0; x < level.rowSize_; x += level.blockSize_)
  889. FlipBlockVertical(dest + x, src + x, compressedFormat_);
  890. }
  891. dataOffset += level.dataSize_;
  892. }
  893. data_ = newData;
  894. }
  895. return true;
  896. }
  897. bool Image::Resize(int width, int height)
  898. {
  899. PROFILE(ResizeImage);
  900. if (IsCompressed())
  901. {
  902. LOGERROR("Resize not supported for compressed images");
  903. return false;
  904. }
  905. if (depth_ > 1)
  906. {
  907. LOGERROR("Resize not supported for 3D images");
  908. return false;
  909. }
  910. if (!data_ || width <= 0 || height <= 0)
  911. return false;
  912. /// \todo Reducing image size does not sample all needed pixels
  913. SharedArrayPtr<unsigned char> newData(new unsigned char[width * height * components_]);
  914. for (int y = 0; y < height; ++y)
  915. {
  916. for (int x = 0; x < width; ++x)
  917. {
  918. // Calculate float coordinates between 0 - 1 for resampling
  919. float xF = (width_ > 1) ? (float)x / (float)(width - 1) : 0.0f;
  920. float yF = (height_ > 1) ? (float)y / (float)(height - 1) : 0.0f;
  921. unsigned uintColor = GetPixelBilinear(xF, yF).ToUInt();
  922. unsigned char* dest = newData + (y * width + x) * components_;
  923. unsigned char* src = (unsigned char*)&uintColor;
  924. switch (components_)
  925. {
  926. case 4:
  927. dest[3] = src[3];
  928. // Fall through
  929. case 3:
  930. dest[2] = src[2];
  931. // Fall through
  932. case 2:
  933. dest[1] = src[1];
  934. // Fall through
  935. default:
  936. dest[0] = src[0];
  937. break;
  938. }
  939. }
  940. }
  941. width_ = width;
  942. height_ = height;
  943. data_ = newData;
  944. SetMemoryUse(width * height * depth_ * components_);
  945. return true;
  946. }
  947. void Image::Clear(const Color& color)
  948. {
  949. ClearInt(color.ToUInt());
  950. }
  951. void Image::ClearInt(unsigned uintColor)
  952. {
  953. PROFILE(ClearImage);
  954. if (!data_)
  955. return;
  956. if (IsCompressed())
  957. {
  958. LOGERROR("Clear not supported for compressed images");
  959. return;
  960. }
  961. unsigned char* src = (unsigned char*)&uintColor;
  962. for (unsigned i = 0; i < width_ * height_ * depth_ * components_; ++i)
  963. data_[i] = src[i % components_];
  964. }
  965. bool Image::SaveBMP(const String& fileName) const
  966. {
  967. PROFILE(SaveImageBMP);
  968. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  969. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  970. {
  971. LOGERROR("Access denied to " + fileName);
  972. return false;
  973. }
  974. if (IsCompressed())
  975. {
  976. LOGERROR("Can not save compressed image to BMP");
  977. return false;
  978. }
  979. if (data_)
  980. return stbi_write_bmp(fileName.CString(), width_, height_, components_, data_.Get()) != 0;
  981. else
  982. return false;
  983. }
  984. bool Image::SavePNG(const String& fileName) const
  985. {
  986. PROFILE(SaveImagePNG);
  987. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  988. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  989. {
  990. LOGERROR("Access denied to " + fileName);
  991. return false;
  992. }
  993. if (IsCompressed())
  994. {
  995. LOGERROR("Can not save compressed image to PNG");
  996. return false;
  997. }
  998. if (data_)
  999. return stbi_write_png(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get(), 0) != 0;
  1000. else
  1001. return false;
  1002. }
  1003. bool Image::SaveTGA(const String& fileName) const
  1004. {
  1005. PROFILE(SaveImageTGA);
  1006. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  1007. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  1008. {
  1009. LOGERROR("Access denied to " + fileName);
  1010. return false;
  1011. }
  1012. if (IsCompressed())
  1013. {
  1014. LOGERROR("Can not save compressed image to TGA");
  1015. return false;
  1016. }
  1017. if (data_)
  1018. return stbi_write_tga(GetNativePath(fileName).CString(), width_, height_, components_, data_.Get()) != 0;
  1019. else
  1020. return false;
  1021. }
  1022. bool Image::SaveJPG(const String& fileName, int quality) const
  1023. {
  1024. PROFILE(SaveImageJPG);
  1025. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  1026. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  1027. {
  1028. LOGERROR("Access denied to " + fileName);
  1029. return false;
  1030. }
  1031. if (IsCompressed())
  1032. {
  1033. LOGERROR("Can not save compressed image to JPG");
  1034. return false;
  1035. }
  1036. if (data_)
  1037. return jo_write_jpg(GetNativePath(fileName).CString(), data_.Get(), width_, height_, components_, quality) != 0;
  1038. else
  1039. return false;
  1040. }
  1041. bool Image::SaveDDS(const String& fileName) const
  1042. {
  1043. #if defined(ATOMIC_PLATFORM_WINDOWS) || defined (ATOMIC_PLATFORM_LINUX) || defined (ATOMIC_PLATFORM_OSX)
  1044. PROFILE(SaveImageDDS);
  1045. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  1046. if (fileSystem && !fileSystem->CheckAccess(GetPath(fileName)))
  1047. {
  1048. LOGERROR("Access denied to " + fileName);
  1049. return false;
  1050. }
  1051. if (IsCompressed())
  1052. {
  1053. LOGERROR("Can not save compressed image to DDS");
  1054. return false;
  1055. }
  1056. if (data_)
  1057. {
  1058. // #623 BEGIN TODO: Should have an abstract ImageReader and ImageWriter classes
  1059. // with subclasses for particular image output types. Also should have image settings in the image meta.
  1060. // ImageReader/Writers should also support a progress callback so UI can be updated.
  1061. // Compression setup
  1062. crn_comp_params compParams;
  1063. compParams.m_width = width_;
  1064. compParams.m_height = height_;
  1065. compParams.set_flag(cCRNCompFlagPerceptual, true); // IsSRGB() incorrectly returning false
  1066. compParams.set_flag(cCRNCompFlagDXT1AForTransparency, false);
  1067. compParams.set_flag(cCRNCompFlagHierarchical, true);
  1068. compParams.m_file_type = cCRNFileTypeDDS;
  1069. compParams.m_format = (HasAlphaChannel() ? cCRNFmtDXT5 : cCRNFmtDXT1);
  1070. compParams.m_pImages[0][0] = (uint32_t*)data_.Get();
  1071. compParams.m_target_bitrate = 0;
  1072. compParams.m_quality_level = 255;
  1073. compParams.m_num_helper_threads = 1;
  1074. compParams.m_pProgress_func = nullptr;
  1075. // Mipmap setup
  1076. crn_mipmap_params mipParams;
  1077. mipParams.m_gamma_filtering = true; // IsSRGB() incorrectly returns false
  1078. mipParams.m_mode = cCRNMipModeNoMips; // or cCRNMipModeGenerateMips
  1079. // Output params
  1080. crn_uint32 actualQualityLevel;
  1081. float actualBitrate;
  1082. crn_uint32 outputFileSize;
  1083. void* compressedData = crn_compress(
  1084. compParams,
  1085. mipParams,
  1086. outputFileSize,
  1087. &actualQualityLevel,
  1088. &actualBitrate);
  1089. if (nullptr == compressedData)
  1090. {
  1091. LOGERROR("Failed to compress image to DXT");
  1092. return false;
  1093. }
  1094. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  1095. SharedPtr<File> dest(new File(context_, fileName, FILE_WRITE));
  1096. if (dest.Null())
  1097. {
  1098. // Open error already logged
  1099. crn_free_block(compressedData);
  1100. return false;
  1101. }
  1102. else
  1103. {
  1104. bool success = dest->Write(compressedData, outputFileSize) == outputFileSize;
  1105. crn_free_block(compressedData);
  1106. return success;
  1107. }
  1108. // #623 END TODO
  1109. }
  1110. #else
  1111. LOGWARNING("Image::SaveDDS - Unsupported on current platform");
  1112. #endif
  1113. return false;
  1114. }
  1115. bool Image::IsPOT() const
  1116. {
  1117. return IsPowerOfTwo(width_) && IsPowerOfTwo(height_);
  1118. }
  1119. bool Image::HasAlphaChannel() const
  1120. {
  1121. return components_ > 3;
  1122. }
  1123. Color Image::GetPixel(int x, int y) const
  1124. {
  1125. return GetPixel(x, y, 0);
  1126. }
  1127. Color Image::GetPixel(int x, int y, int z) const
  1128. {
  1129. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  1130. return Color::BLACK;
  1131. x = Clamp(x, 0, width_ - 1);
  1132. y = Clamp(y, 0, height_ - 1);
  1133. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  1134. Color ret;
  1135. switch (components_)
  1136. {
  1137. case 4:
  1138. ret.a_ = (float)src[3] / 255.0f;
  1139. // Fall through
  1140. case 3:
  1141. ret.b_ = (float)src[2] / 255.0f;
  1142. // Fall through
  1143. case 2:
  1144. ret.g_ = (float)src[1] / 255.0f;
  1145. ret.r_ = (float)src[0] / 255.0f;
  1146. break;
  1147. default:
  1148. ret.r_ = ret.g_ = ret.b_ = (float)src[0] / 255.0f;
  1149. break;
  1150. }
  1151. return ret;
  1152. }
  1153. unsigned Image::GetPixelInt(int x, int y) const
  1154. {
  1155. return GetPixelInt(x, y, 0);
  1156. }
  1157. unsigned Image::GetPixelInt(int x, int y, int z) const
  1158. {
  1159. if (!data_ || z < 0 || z >= depth_ || IsCompressed())
  1160. return 0xff000000;
  1161. x = Clamp(x, 0, width_ - 1);
  1162. y = Clamp(y, 0, height_ - 1);
  1163. unsigned char* src = data_ + (z * width_ * height_ + y * width_ + x) * components_;
  1164. unsigned ret = 0;
  1165. if (components_ < 4)
  1166. ret |= 0xff000000;
  1167. switch (components_)
  1168. {
  1169. case 4:
  1170. ret |= (unsigned)src[3] << 24;
  1171. // Fall through
  1172. case 3:
  1173. ret |= (unsigned)src[2] << 16;
  1174. // Fall through
  1175. case 2:
  1176. ret |= (unsigned)src[1] << 8;
  1177. ret |= (unsigned)src[0];
  1178. break;
  1179. default:
  1180. ret |= (unsigned)src[0] << 16;
  1181. ret |= (unsigned)src[0] << 8;
  1182. ret |= (unsigned)src[0];
  1183. break;
  1184. }
  1185. return ret;
  1186. }
  1187. Color Image::GetPixelBilinear(float x, float y) const
  1188. {
  1189. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  1190. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  1191. int xI = (int)x;
  1192. int yI = (int)y;
  1193. float xF = x - floorf(x);
  1194. float yF = y - floorf(y);
  1195. Color topColor = GetPixel(xI, yI).Lerp(GetPixel(xI + 1, yI), xF);
  1196. Color bottomColor = GetPixel(xI, yI + 1).Lerp(GetPixel(xI + 1, yI + 1), xF);
  1197. return topColor.Lerp(bottomColor, yF);
  1198. }
  1199. Color Image::GetPixelTrilinear(float x, float y, float z) const
  1200. {
  1201. if (depth_ < 2)
  1202. return GetPixelBilinear(x, y);
  1203. x = Clamp(x * width_ - 0.5f, 0.0f, (float)(width_ - 1));
  1204. y = Clamp(y * height_ - 0.5f, 0.0f, (float)(height_ - 1));
  1205. z = Clamp(z * depth_ - 0.5f, 0.0f, (float)(depth_ - 1));
  1206. int xI = (int)x;
  1207. int yI = (int)y;
  1208. int zI = (int)z;
  1209. if (zI == depth_ - 1)
  1210. return GetPixelBilinear(x, y);
  1211. float xF = x - floorf(x);
  1212. float yF = y - floorf(y);
  1213. float zF = z - floorf(z);
  1214. Color topColorNear = GetPixel(xI, yI, zI).Lerp(GetPixel(xI + 1, yI, zI), xF);
  1215. Color bottomColorNear = GetPixel(xI, yI + 1, zI).Lerp(GetPixel(xI + 1, yI + 1, zI), xF);
  1216. Color colorNear = topColorNear.Lerp(bottomColorNear, yF);
  1217. Color topColorFar = GetPixel(xI, yI, zI + 1).Lerp(GetPixel(xI + 1, yI, zI + 1), xF);
  1218. Color bottomColorFar = GetPixel(xI, yI + 1, zI + 1).Lerp(GetPixel(xI + 1, yI + 1, zI + 1), xF);
  1219. Color colorFar = topColorFar.Lerp(bottomColorFar, yF);
  1220. return colorNear.Lerp(colorFar, zF);
  1221. }
  1222. SharedPtr<Image> Image::GetNextLevel() const
  1223. {
  1224. if (IsCompressed())
  1225. {
  1226. LOGERROR("Can not generate mip level from compressed data");
  1227. return SharedPtr<Image>();
  1228. }
  1229. if (components_ < 1 || components_ > 4)
  1230. {
  1231. LOGERROR("Illegal number of image components for mip level generation");
  1232. return SharedPtr<Image>();
  1233. }
  1234. if (nextLevel_)
  1235. return nextLevel_;
  1236. PROFILE(CalculateImageMipLevel);
  1237. int widthOut = width_ / 2;
  1238. int heightOut = height_ / 2;
  1239. int depthOut = depth_ / 2;
  1240. if (widthOut < 1)
  1241. widthOut = 1;
  1242. if (heightOut < 1)
  1243. heightOut = 1;
  1244. if (depthOut < 1)
  1245. depthOut = 1;
  1246. SharedPtr<Image> mipImage(new Image(context_));
  1247. if (depth_ > 1)
  1248. mipImage->SetSize(widthOut, heightOut, depthOut, components_);
  1249. else
  1250. mipImage->SetSize(widthOut, heightOut, components_);
  1251. const unsigned char* pixelDataIn = data_.Get();
  1252. unsigned char* pixelDataOut = mipImage->data_.Get();
  1253. // 1D case
  1254. if (depth_ == 1 && (height_ == 1 || width_ == 1))
  1255. {
  1256. // Loop using the larger dimension
  1257. if (widthOut < heightOut)
  1258. widthOut = heightOut;
  1259. switch (components_)
  1260. {
  1261. case 1:
  1262. for (int x = 0; x < widthOut; ++x)
  1263. pixelDataOut[x] = (unsigned char)(((unsigned)pixelDataIn[x * 2] + pixelDataIn[x * 2 + 1]) >> 1);
  1264. break;
  1265. case 2:
  1266. for (int x = 0; x < widthOut * 2; x += 2)
  1267. {
  1268. pixelDataOut[x] = (unsigned char)(((unsigned)pixelDataIn[x * 2] + pixelDataIn[x * 2 + 2]) >> 1);
  1269. pixelDataOut[x + 1] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 1] + pixelDataIn[x * 2 + 3]) >> 1);
  1270. }
  1271. break;
  1272. case 3:
  1273. for (int x = 0; x < widthOut * 3; x += 3)
  1274. {
  1275. pixelDataOut[x] = (unsigned char)(((unsigned)pixelDataIn[x * 2] + pixelDataIn[x * 2 + 3]) >> 1);
  1276. pixelDataOut[x + 1] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 1] + pixelDataIn[x * 2 + 4]) >> 1);
  1277. pixelDataOut[x + 2] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 2] + pixelDataIn[x * 2 + 5]) >> 1);
  1278. }
  1279. break;
  1280. case 4:
  1281. for (int x = 0; x < widthOut * 4; x += 4)
  1282. {
  1283. pixelDataOut[x] = (unsigned char)(((unsigned)pixelDataIn[x * 2] + pixelDataIn[x * 2 + 4]) >> 1);
  1284. pixelDataOut[x + 1] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 1] + pixelDataIn[x * 2 + 5]) >> 1);
  1285. pixelDataOut[x + 2] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 2] + pixelDataIn[x * 2 + 6]) >> 1);
  1286. pixelDataOut[x + 3] = (unsigned char)(((unsigned)pixelDataIn[x * 2 + 3] + pixelDataIn[x * 2 + 7]) >> 1);
  1287. }
  1288. break;
  1289. default:
  1290. assert(false); // Should never reach here
  1291. break;
  1292. }
  1293. }
  1294. // 2D case
  1295. else if (depth_ == 1)
  1296. {
  1297. switch (components_)
  1298. {
  1299. case 1:
  1300. for (int y = 0; y < heightOut; ++y)
  1301. {
  1302. const unsigned char* inUpper = &pixelDataIn[(y * 2) * width_];
  1303. const unsigned char* inLower = &pixelDataIn[(y * 2 + 1) * width_];
  1304. unsigned char* out = &pixelDataOut[y * widthOut];
  1305. for (int x = 0; x < widthOut; ++x)
  1306. {
  1307. out[x] = (unsigned char)(((unsigned)inUpper[x * 2] + inUpper[x * 2 + 1] +
  1308. inLower[x * 2] + inLower[x * 2 + 1]) >> 2);
  1309. }
  1310. }
  1311. break;
  1312. case 2:
  1313. for (int y = 0; y < heightOut; ++y)
  1314. {
  1315. const unsigned char* inUpper = &pixelDataIn[(y * 2) * width_ * 2];
  1316. const unsigned char* inLower = &pixelDataIn[(y * 2 + 1) * width_ * 2];
  1317. unsigned char* out = &pixelDataOut[y * widthOut * 2];
  1318. for (int x = 0; x < widthOut * 2; x += 2)
  1319. {
  1320. out[x] = (unsigned char)(((unsigned)inUpper[x * 2] + inUpper[x * 2 + 2] +
  1321. inLower[x * 2] + inLower[x * 2 + 2]) >> 2);
  1322. out[x + 1] = (unsigned char)(((unsigned)inUpper[x * 2 + 1] + inUpper[x * 2 + 3] +
  1323. inLower[x * 2 + 1] + inLower[x * 2 + 3]) >> 2);
  1324. }
  1325. }
  1326. break;
  1327. case 3:
  1328. for (int y = 0; y < heightOut; ++y)
  1329. {
  1330. const unsigned char* inUpper = &pixelDataIn[(y * 2) * width_ * 3];
  1331. const unsigned char* inLower = &pixelDataIn[(y * 2 + 1) * width_ * 3];
  1332. unsigned char* out = &pixelDataOut[y * widthOut * 3];
  1333. for (int x = 0; x < widthOut * 3; x += 3)
  1334. {
  1335. out[x] = (unsigned char)(((unsigned)inUpper[x * 2] + inUpper[x * 2 + 3] +
  1336. inLower[x * 2] + inLower[x * 2 + 3]) >> 2);
  1337. out[x + 1] = (unsigned char)(((unsigned)inUpper[x * 2 + 1] + inUpper[x * 2 + 4] +
  1338. inLower[x * 2 + 1] + inLower[x * 2 + 4]) >> 2);
  1339. out[x + 2] = (unsigned char)(((unsigned)inUpper[x * 2 + 2] + inUpper[x * 2 + 5] +
  1340. inLower[x * 2 + 2] + inLower[x * 2 + 5]) >> 2);
  1341. }
  1342. }
  1343. break;
  1344. case 4:
  1345. for (int y = 0; y < heightOut; ++y)
  1346. {
  1347. const unsigned char* inUpper = &pixelDataIn[(y * 2) * width_ * 4];
  1348. const unsigned char* inLower = &pixelDataIn[(y * 2 + 1) * width_ * 4];
  1349. unsigned char* out = &pixelDataOut[y * widthOut * 4];
  1350. for (int x = 0; x < widthOut * 4; x += 4)
  1351. {
  1352. out[x] = (unsigned char)(((unsigned)inUpper[x * 2] + inUpper[x * 2 + 4] +
  1353. inLower[x * 2] + inLower[x * 2 + 4]) >> 2);
  1354. out[x + 1] = (unsigned char)(((unsigned)inUpper[x * 2 + 1] + inUpper[x * 2 + 5] +
  1355. inLower[x * 2 + 1] + inLower[x * 2 + 5]) >> 2);
  1356. out[x + 2] = (unsigned char)(((unsigned)inUpper[x * 2 + 2] + inUpper[x * 2 + 6] +
  1357. inLower[x * 2 + 2] + inLower[x * 2 + 6]) >> 2);
  1358. out[x + 3] = (unsigned char)(((unsigned)inUpper[x * 2 + 3] + inUpper[x * 2 + 7] +
  1359. inLower[x * 2 + 3] + inLower[x * 2 + 7]) >> 2);
  1360. }
  1361. }
  1362. break;
  1363. default:
  1364. assert(false); // Should never reach here
  1365. break;
  1366. }
  1367. }
  1368. // 3D case
  1369. else
  1370. {
  1371. switch (components_)
  1372. {
  1373. case 1:
  1374. for (int z = 0; z < depthOut; ++z)
  1375. {
  1376. const unsigned char* inOuter = &pixelDataIn[(z * 2) * width_ * height_];
  1377. const unsigned char* inInner = &pixelDataIn[(z * 2 + 1) * width_ * height_];
  1378. for (int y = 0; y < heightOut; ++y)
  1379. {
  1380. const unsigned char* inOuterUpper = &inOuter[(y * 2) * width_];
  1381. const unsigned char* inOuterLower = &inOuter[(y * 2 + 1) * width_];
  1382. const unsigned char* inInnerUpper = &inInner[(y * 2) * width_];
  1383. const unsigned char* inInnerLower = &inInner[(y * 2 + 1) * width_];
  1384. unsigned char* out = &pixelDataOut[z * widthOut * heightOut + y * widthOut];
  1385. for (int x = 0; x < widthOut; ++x)
  1386. {
  1387. out[x] = (unsigned char)(((unsigned)inOuterUpper[x * 2] + inOuterUpper[x * 2 + 1] +
  1388. inOuterLower[x * 2] + inOuterLower[x * 2 + 1] +
  1389. inInnerUpper[x * 2] + inInnerUpper[x * 2 + 1] +
  1390. inInnerLower[x * 2] + inInnerLower[x * 2 + 1]) >> 3);
  1391. }
  1392. }
  1393. }
  1394. break;
  1395. case 2:
  1396. for (int z = 0; z < depthOut; ++z)
  1397. {
  1398. const unsigned char* inOuter = &pixelDataIn[(z * 2) * width_ * height_ * 2];
  1399. const unsigned char* inInner = &pixelDataIn[(z * 2 + 1) * width_ * height_ * 2];
  1400. for (int y = 0; y < heightOut; ++y)
  1401. {
  1402. const unsigned char* inOuterUpper = &inOuter[(y * 2) * width_ * 2];
  1403. const unsigned char* inOuterLower = &inOuter[(y * 2 + 1) * width_ * 2];
  1404. const unsigned char* inInnerUpper = &inInner[(y * 2) * width_ * 2];
  1405. const unsigned char* inInnerLower = &inInner[(y * 2 + 1) * width_ * 2];
  1406. unsigned char* out = &pixelDataOut[z * widthOut * heightOut * 2 + y * widthOut * 2];
  1407. for (int x = 0; x < widthOut * 2; x += 2)
  1408. {
  1409. out[x] = (unsigned char)(((unsigned)inOuterUpper[x * 2] + inOuterUpper[x * 2 + 2] +
  1410. inOuterLower[x * 2] + inOuterLower[x * 2 + 2] +
  1411. inInnerUpper[x * 2] + inInnerUpper[x * 2 + 2] +
  1412. inInnerLower[x * 2] + inInnerLower[x * 2 + 2]) >> 3);
  1413. out[x + 1] = (unsigned char)(((unsigned)inOuterUpper[x * 2 + 1] + inOuterUpper[x * 2 + 3] +
  1414. inOuterLower[x * 2 + 1] + inOuterLower[x * 2 + 3] +
  1415. inInnerUpper[x * 2 + 1] + inInnerUpper[x * 2 + 3] +
  1416. inInnerLower[x * 2 + 1] + inInnerLower[x * 2 + 3]) >> 3);
  1417. }
  1418. }
  1419. }
  1420. break;
  1421. case 3:
  1422. for (int z = 0; z < depthOut; ++z)
  1423. {
  1424. const unsigned char* inOuter = &pixelDataIn[(z * 2) * width_ * height_ * 3];
  1425. const unsigned char* inInner = &pixelDataIn[(z * 2 + 1) * width_ * height_ * 3];
  1426. for (int y = 0; y < heightOut; ++y)
  1427. {
  1428. const unsigned char* inOuterUpper = &inOuter[(y * 2) * width_ * 3];
  1429. const unsigned char* inOuterLower = &inOuter[(y * 2 + 1) * width_ * 3];
  1430. const unsigned char* inInnerUpper = &inInner[(y * 2) * width_ * 3];
  1431. const unsigned char* inInnerLower = &inInner[(y * 2 + 1) * width_ * 3];
  1432. unsigned char* out = &pixelDataOut[z * widthOut * heightOut * 3 + y * widthOut * 3];
  1433. for (int x = 0; x < widthOut * 3; x += 3)
  1434. {
  1435. out[x] = (unsigned char)(((unsigned)inOuterUpper[x * 2] + inOuterUpper[x * 2 + 3] +
  1436. inOuterLower[x * 2] + inOuterLower[x * 2 + 3] +
  1437. inInnerUpper[x * 2] + inInnerUpper[x * 2 + 3] +
  1438. inInnerLower[x * 2] + inInnerLower[x * 2 + 3]) >> 3);
  1439. out[x + 1] = (unsigned char)(((unsigned)inOuterUpper[x * 2 + 1] + inOuterUpper[x * 2 + 4] +
  1440. inOuterLower[x * 2 + 1] + inOuterLower[x * 2 + 4] +
  1441. inInnerUpper[x * 2 + 1] + inInnerUpper[x * 2 + 4] +
  1442. inInnerLower[x * 2 + 1] + inInnerLower[x * 2 + 4]) >> 3);
  1443. out[x + 2] = (unsigned char)(((unsigned)inOuterUpper[x * 2 + 2] + inOuterUpper[x * 2 + 5] +
  1444. inOuterLower[x * 2 + 2] + inOuterLower[x * 2 + 5] +
  1445. inInnerUpper[x * 2 + 2] + inInnerUpper[x * 2 + 5] +
  1446. inInnerLower[x * 2 + 2] + inInnerLower[x * 2 + 5]) >> 3);
  1447. }
  1448. }
  1449. }
  1450. break;
  1451. case 4:
  1452. for (int z = 0; z < depthOut; ++z)
  1453. {
  1454. const unsigned char* inOuter = &pixelDataIn[(z * 2) * width_ * height_ * 4];
  1455. const unsigned char* inInner = &pixelDataIn[(z * 2 + 1) * width_ * height_ * 4];
  1456. for (int y = 0; y < heightOut; ++y)
  1457. {
  1458. const unsigned char* inOuterUpper = &inOuter[(y * 2) * width_ * 4];
  1459. const unsigned char* inOuterLower = &inOuter[(y * 2 + 1) * width_ * 4];
  1460. const unsigned char* inInnerUpper = &inInner[(y * 2) * width_ * 4];
  1461. const unsigned char* inInnerLower = &inInner[(y * 2 + 1) * width_ * 4];
  1462. unsigned char* out = &pixelDataOut[z * widthOut * heightOut * 4 + y * widthOut * 4];
  1463. for (int x = 0; x < widthOut * 4; x += 4)
  1464. {
  1465. out[x] = (unsigned char)(((unsigned)inOuterUpper[x * 2] + inOuterUpper[x * 2 + 4] +
  1466. inOuterLower[x * 2] + inOuterLower[x * 2 + 4] +
  1467. inInnerUpper[x * 2] + inInnerUpper[x * 2 + 4] +
  1468. inInnerLower[x * 2] + inInnerLower[x * 2 + 4]) >> 3);
  1469. out[x + 1] = (unsigned char)(((unsigned)inOuterUpper[x * 2 + 1] + inOuterUpper[x * 2 + 5] +
  1470. inOuterLower[x * 2 + 1] + inOuterLower[x * 2 + 5] +
  1471. inInnerUpper[x * 2 + 1] + inInnerUpper[x * 2 + 5] +
  1472. inInnerLower[x * 2 + 1] + inInnerLower[x * 2 + 5]) >> 3);
  1473. out[x + 2] = (unsigned char)(((unsigned)inOuterUpper[x * 2 + 2] + inOuterUpper[x * 2 + 6] +
  1474. inOuterLower[x * 2 + 2] + inOuterLower[x * 2 + 6] +
  1475. inInnerUpper[x * 2 + 2] + inInnerUpper[x * 2 + 6] +
  1476. inInnerLower[x * 2 + 2] + inInnerLower[x * 2 + 6]) >> 3);
  1477. }
  1478. }
  1479. }
  1480. break;
  1481. default:
  1482. assert(false); // Should never reach here
  1483. break;
  1484. }
  1485. }
  1486. return mipImage;
  1487. }
  1488. SharedPtr<Image> Image::ConvertToRGBA() const
  1489. {
  1490. if (IsCompressed())
  1491. {
  1492. LOGERROR("Can not convert compressed image to RGBA");
  1493. return SharedPtr<Image>();
  1494. }
  1495. if (components_ < 1 || components_ > 4)
  1496. {
  1497. LOGERROR("Illegal number of image components for conversion to RGBA");
  1498. return SharedPtr<Image>();
  1499. }
  1500. if (!data_)
  1501. {
  1502. LOGERROR("Can not convert image without data to RGBA");
  1503. return SharedPtr<Image>();
  1504. }
  1505. // Already RGBA?
  1506. if (components_ == 4)
  1507. return SharedPtr<Image>(const_cast<Image*>(this));
  1508. SharedPtr<Image> ret(new Image(context_));
  1509. ret->SetSize(width_, height_, depth_, 4);
  1510. const unsigned char* src = data_;
  1511. unsigned char* dest = ret->GetData();
  1512. switch (components_)
  1513. {
  1514. case 1:
  1515. for (unsigned i = 0; i < static_cast<unsigned>(width_ * height_ * depth_); ++i)
  1516. {
  1517. unsigned char pixel = *src++;
  1518. *dest++ = pixel;
  1519. *dest++ = pixel;
  1520. *dest++ = pixel;
  1521. *dest++ = 255;
  1522. }
  1523. break;
  1524. case 2:
  1525. for (unsigned i = 0; i < static_cast<unsigned>(width_ * height_ * depth_); ++i)
  1526. {
  1527. unsigned char pixel = *src++;
  1528. *dest++ = pixel;
  1529. *dest++ = pixel;
  1530. *dest++ = pixel;
  1531. *dest++ = *src++;
  1532. }
  1533. break;
  1534. case 3:
  1535. for (unsigned i = 0; i < static_cast<unsigned>(width_ * height_ * depth_); ++i)
  1536. {
  1537. *dest++ = *src++;
  1538. *dest++ = *src++;
  1539. *dest++ = *src++;
  1540. *dest++ = 255;
  1541. }
  1542. break;
  1543. default:
  1544. assert(false); // Should never reach nere
  1545. break;
  1546. }
  1547. return ret;
  1548. }
  1549. CompressedLevel Image::GetCompressedLevel(unsigned index) const
  1550. {
  1551. CompressedLevel level;
  1552. if (compressedFormat_ == CF_NONE)
  1553. {
  1554. LOGERROR("Image is not compressed");
  1555. return level;
  1556. }
  1557. if (index >= numCompressedLevels_)
  1558. {
  1559. LOGERROR("Compressed image mip level out of bounds");
  1560. return level;
  1561. }
  1562. level.format_ = compressedFormat_;
  1563. level.width_ = width_;
  1564. level.height_ = height_;
  1565. level.depth_ = depth_;
  1566. if (compressedFormat_ == CF_RGBA)
  1567. {
  1568. level.blockSize_ = 4;
  1569. unsigned i = 0;
  1570. unsigned offset = 0;
  1571. for (;;)
  1572. {
  1573. if (!level.width_)
  1574. level.width_ = 1;
  1575. if (!level.height_)
  1576. level.height_ = 1;
  1577. if (!level.depth_)
  1578. level.depth_ = 1;
  1579. level.rowSize_ = level.width_ * level.blockSize_;
  1580. level.rows_ = (unsigned)level.height_;
  1581. level.data_ = data_.Get() + offset;
  1582. level.dataSize_ = level.depth_ * level.rows_ * level.rowSize_;
  1583. if (offset + level.dataSize_ > GetMemoryUse())
  1584. {
  1585. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1586. " Datasize: " + String(GetMemoryUse()));
  1587. level.data_ = 0;
  1588. return level;
  1589. }
  1590. if (i == index)
  1591. return level;
  1592. offset += level.dataSize_;
  1593. level.width_ /= 2;
  1594. level.height_ /= 2;
  1595. level.depth_ /= 2;
  1596. ++i;
  1597. }
  1598. }
  1599. else if (compressedFormat_ < CF_PVRTC_RGB_2BPP)
  1600. {
  1601. level.blockSize_ = (compressedFormat_ == CF_DXT1 || compressedFormat_ == CF_ETC1) ? 8 : 16;
  1602. unsigned i = 0;
  1603. unsigned offset = 0;
  1604. for (;;)
  1605. {
  1606. if (!level.width_)
  1607. level.width_ = 1;
  1608. if (!level.height_)
  1609. level.height_ = 1;
  1610. if (!level.depth_)
  1611. level.depth_ = 1;
  1612. level.rowSize_ = ((level.width_ + 3) / 4) * level.blockSize_;
  1613. level.rows_ = (unsigned)((level.height_ + 3) / 4);
  1614. level.data_ = data_.Get() + offset;
  1615. level.dataSize_ = level.depth_ * level.rows_ * level.rowSize_;
  1616. if (offset + level.dataSize_ > GetMemoryUse())
  1617. {
  1618. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1619. " Datasize: " + String(GetMemoryUse()));
  1620. level.data_ = 0;
  1621. return level;
  1622. }
  1623. if (i == index)
  1624. return level;
  1625. offset += level.dataSize_;
  1626. level.width_ /= 2;
  1627. level.height_ /= 2;
  1628. level.depth_ /= 2;
  1629. ++i;
  1630. }
  1631. }
  1632. else
  1633. {
  1634. level.blockSize_ = compressedFormat_ < CF_PVRTC_RGB_4BPP ? 2 : 4;
  1635. unsigned i = 0;
  1636. unsigned offset = 0;
  1637. for (;;)
  1638. {
  1639. if (!level.width_)
  1640. level.width_ = 1;
  1641. if (!level.height_)
  1642. level.height_ = 1;
  1643. int dataWidth = Max(level.width_, level.blockSize_ == 2 ? 16 : 8);
  1644. int dataHeight = Max(level.height_, 8);
  1645. level.data_ = data_.Get() + offset;
  1646. level.dataSize_ = (dataWidth * dataHeight * level.blockSize_ + 7) >> 3;
  1647. level.rows_ = (unsigned)dataHeight;
  1648. level.rowSize_ = level.dataSize_ / level.rows_;
  1649. if (offset + level.dataSize_ > GetMemoryUse())
  1650. {
  1651. LOGERROR("Compressed level is outside image data. Offset: " + String(offset) + " Size: " + String(level.dataSize_) +
  1652. " Datasize: " + String(GetMemoryUse()));
  1653. level.data_ = 0;
  1654. return level;
  1655. }
  1656. if (i == index)
  1657. return level;
  1658. offset += level.dataSize_;
  1659. level.width_ /= 2;
  1660. level.height_ /= 2;
  1661. ++i;
  1662. }
  1663. }
  1664. }
  1665. Image* Image::GetSubimage(const IntRect& rect) const
  1666. {
  1667. if (!data_)
  1668. return 0;
  1669. if (depth_ > 1)
  1670. {
  1671. LOGERROR("Subimage not supported for 3D images");
  1672. return 0;
  1673. }
  1674. if (rect.left_ < 0 || rect.top_ < 0 || rect.right_ > width_ || rect.bottom_ > height_ || !rect.Width() || !rect.Height())
  1675. {
  1676. LOGERROR("Can not get subimage from image " + GetName() + " with invalid region");
  1677. return 0;
  1678. }
  1679. if (!IsCompressed())
  1680. {
  1681. int x = rect.left_;
  1682. int y = rect.top_;
  1683. int width = rect.Width();
  1684. int height = rect.Height();
  1685. Image* image = new Image(context_);
  1686. image->SetSize(width, height, components_);
  1687. unsigned char* dest = image->GetData();
  1688. unsigned char* src = data_.Get() + (y * width_ + x) * components_;
  1689. for (int i = 0; i < height; ++i)
  1690. {
  1691. memcpy(dest, src, width * components_);
  1692. dest += width * components_;
  1693. src += width_ * components_;
  1694. }
  1695. return image;
  1696. }
  1697. else
  1698. {
  1699. // Pad the region to be a multiple of block size
  1700. IntRect paddedRect = rect;
  1701. paddedRect.left_ = (rect.left_ / 4) * 4;
  1702. paddedRect.top_ = (rect.top_ / 4) * 4;
  1703. paddedRect.right_ = (rect.right_ / 4) * 4;
  1704. paddedRect.bottom_ = (rect.bottom_ / 4) * 4;
  1705. IntRect currentRect = paddedRect;
  1706. PODVector<unsigned char> subimageData;
  1707. unsigned subimageLevels = 0;
  1708. // Save as many mips as possible until the next mip would cross a block boundary
  1709. for (unsigned i = 0; i < numCompressedLevels_; ++i)
  1710. {
  1711. CompressedLevel level = GetCompressedLevel(i);
  1712. if (!level.data_)
  1713. break;
  1714. // Mips are stored continuously
  1715. unsigned destStartOffset = subimageData.Size();
  1716. unsigned destRowSize = currentRect.Width() / 4 * level.blockSize_;
  1717. unsigned destSize = currentRect.Height() / 4 * destRowSize;
  1718. if (!destSize)
  1719. break;
  1720. subimageData.Resize(destStartOffset + destSize);
  1721. unsigned char* dest = &subimageData[destStartOffset];
  1722. for (int y = currentRect.top_; y < currentRect.bottom_; y += 4)
  1723. {
  1724. unsigned char* src = level.data_ + level.rowSize_ * (y / 4) + currentRect.left_ / 4 * level.blockSize_;
  1725. memcpy(dest, src, destRowSize);
  1726. dest += destRowSize;
  1727. }
  1728. ++subimageLevels;
  1729. if ((currentRect.left_ & 4) || (currentRect.right_ & 4) || (currentRect.top_ & 4) || (currentRect.bottom_ & 4))
  1730. break;
  1731. else
  1732. {
  1733. currentRect.left_ /= 2;
  1734. currentRect.right_ /= 2;
  1735. currentRect.top_ /= 2;
  1736. currentRect.bottom_ /= 2;
  1737. }
  1738. }
  1739. if (!subimageLevels)
  1740. {
  1741. LOGERROR("Subimage region from compressed image " + GetName() + " did not produce any data");
  1742. return 0;
  1743. }
  1744. Image* image = new Image(context_);
  1745. image->width_ = paddedRect.Width();
  1746. image->height_ = paddedRect.Height();
  1747. image->depth_ = 1;
  1748. image->compressedFormat_ = compressedFormat_;
  1749. image->numCompressedLevels_ = subimageLevels;
  1750. image->components_ = components_;
  1751. image->data_ = new unsigned char[subimageData.Size()];
  1752. memcpy(image->data_.Get(), &subimageData[0], subimageData.Size());
  1753. image->SetMemoryUse(subimageData.Size());
  1754. return image;
  1755. }
  1756. }
  1757. SDL_Surface* Image::GetSDLSurface(const IntRect& rect) const
  1758. {
  1759. if (!data_)
  1760. return 0;
  1761. if (depth_ > 1)
  1762. {
  1763. LOGERROR("Can not get SDL surface from 3D image");
  1764. return 0;
  1765. }
  1766. if (IsCompressed())
  1767. {
  1768. LOGERROR("Can not get SDL surface from compressed image " + GetName());
  1769. return 0;
  1770. }
  1771. if (components_ < 3)
  1772. {
  1773. LOGERROR("Can not get SDL surface from image " + GetName() + " with less than 3 components");
  1774. return 0;
  1775. }
  1776. IntRect imageRect = rect;
  1777. // Use full image if illegal rect
  1778. if (imageRect.left_ < 0 || imageRect.top_ < 0 || imageRect.right_ > width_ || imageRect.bottom_ > height_ ||
  1779. imageRect.left_ >= imageRect.right_ || imageRect.top_ >= imageRect.bottom_)
  1780. {
  1781. imageRect.left_ = 0;
  1782. imageRect.top_ = 0;
  1783. imageRect.right_ = width_;
  1784. imageRect.bottom_ = height_;
  1785. }
  1786. int imageWidth = width_;
  1787. int width = imageRect.Width();
  1788. int height = imageRect.Height();
  1789. // Assume little-endian for all the supported platforms
  1790. unsigned rMask = 0x000000ff;
  1791. unsigned gMask = 0x0000ff00;
  1792. unsigned bMask = 0x00ff0000;
  1793. unsigned aMask = 0xff000000;
  1794. SDL_Surface* surface = SDL_CreateRGBSurface(0, width, height, components_ * 8, rMask, gMask, bMask, aMask);
  1795. if (surface)
  1796. {
  1797. SDL_LockSurface(surface);
  1798. unsigned char* destination = reinterpret_cast<unsigned char*>(surface->pixels);
  1799. unsigned char* source = data_ + components_ * (imageWidth * imageRect.top_ + imageRect.left_);
  1800. for (int i = 0; i < height; ++i)
  1801. {
  1802. memcpy(destination, source, components_ * width);
  1803. destination += surface->pitch;
  1804. source += components_ * imageWidth;
  1805. }
  1806. SDL_UnlockSurface(surface);
  1807. }
  1808. else
  1809. LOGERROR("Failed to create SDL surface from image " + GetName());
  1810. return surface;
  1811. }
  1812. void Image::PrecalculateLevels()
  1813. {
  1814. if (!data_ || IsCompressed())
  1815. return;
  1816. PROFILE(PrecalculateImageMipLevels);
  1817. nextLevel_.Reset();
  1818. if (width_ > 1 || height_ > 1)
  1819. {
  1820. SharedPtr<Image> current = GetNextLevel();
  1821. nextLevel_ = current;
  1822. while (current && (current->width_ > 1 || current->height_ > 1))
  1823. {
  1824. current->nextLevel_ = current->GetNextLevel();
  1825. current = current->nextLevel_;
  1826. }
  1827. }
  1828. }
  1829. unsigned char* Image::GetImageData(Deserializer& source, int& width, int& height, unsigned& components)
  1830. {
  1831. unsigned dataSize = source.GetSize();
  1832. SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
  1833. source.Read(buffer.Get(), dataSize);
  1834. // #623 BEGIN TODO: Crunch expects all 4 components. This isn't ideal, but since
  1835. // precompressed versions should always be loaded anyway it doesn't matter.
  1836. // Might need to handle differently per platform.
  1837. components = 4;
  1838. return stbi_load_from_memory(buffer.Get(), dataSize, &width, &height, nullptr, components);
  1839. // #623 END TODO: Crunch expects all 4 components. This isn't ideal, but since
  1840. }
  1841. void Image::FreeImageData(unsigned char* pixelData)
  1842. {
  1843. if (!pixelData)
  1844. return;
  1845. stbi_image_free(pixelData);
  1846. }
  1847. }