Image.cpp 72 KB

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