Image.cpp 67 KB

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