Image.cpp 55 KB

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