Image.cpp 70 KB

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