Image.cpp 73 KB

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