Image.cpp 75 KB

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