Image.cpp 70 KB

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