Image.cpp 67 KB

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