Image.cpp 76 KB

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