Image.cpp 74 KB

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