SDLImage.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. /*
  2. * SDLImage.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "SDLImage.h"
  12. #include "SDLImageLoader.h"
  13. #include "SDLImageScaler.h"
  14. #include "SDL_Extensions.h"
  15. #include "../render/ColorFilter.h"
  16. #include "../render/CBitmapHandler.h"
  17. #include "../render/CDefFile.h"
  18. #include "../GameEngine.h"
  19. #include "../render/IScreenHandler.h"
  20. #include "../../lib/AsyncRunner.h"
  21. #include "../../lib/CConfigHandler.h"
  22. #include <tbb/parallel_for.h>
  23. #include <tbb/task_arena.h>
  24. #include <SDL_image.h>
  25. #include <SDL_surface.h>
  26. #include <SDL_version.h>
  27. class SDLImageLoader;
  28. int IImage::width() const
  29. {
  30. return dimensions().x;
  31. }
  32. int IImage::height() const
  33. {
  34. return dimensions().y;
  35. }
  36. SDLImageShared::SDLImageShared(const CDefFile * data, size_t frame, size_t group)
  37. : surf(nullptr),
  38. margins(0, 0),
  39. fullSize(0, 0),
  40. originalPalette(nullptr)
  41. {
  42. SDLImageLoader loader(this);
  43. data->loadFrame(frame, group, loader);
  44. savePalette();
  45. }
  46. SDLImageShared::SDLImageShared(SDL_Surface * from)
  47. : surf(nullptr),
  48. margins(0, 0),
  49. fullSize(0, 0),
  50. originalPalette(nullptr)
  51. {
  52. surf = from;
  53. if (surf == nullptr)
  54. return;
  55. savePalette();
  56. surf->refcount++;
  57. fullSize.x = surf->w;
  58. fullSize.y = surf->h;
  59. }
  60. SDLImageShared::SDLImageShared(const ImagePath & filename)
  61. : surf(nullptr),
  62. margins(0, 0),
  63. fullSize(0, 0),
  64. originalPalette(nullptr)
  65. {
  66. surf = BitmapHandler::loadBitmap(filename);
  67. if(surf == nullptr)
  68. {
  69. logGlobal->error("Error: failed to load image %s", filename.getOriginalName());
  70. return;
  71. }
  72. else
  73. {
  74. savePalette();
  75. fullSize.x = surf->w;
  76. fullSize.y = surf->h;
  77. optimizeSurface();
  78. }
  79. }
  80. void SDLImageShared::scaledDraw(SDL_Surface * where, SDL_Palette * palette, const Point & scaleTo, const Point & dest, const Rect * src, const ColorRGBA & colorMultiplier, uint8_t alpha, EImageBlitMode mode) const
  81. {
  82. if(upscalingInProgress)
  83. throw std::runtime_error("Attempt to access images that is still being loaded!");
  84. if (!surf)
  85. return;
  86. Rect sourceRect(0, 0, surf->w, surf->h);
  87. Point destShift(0, 0);
  88. Point destScale = Point(surf->w, surf->h) * scaleTo / dimensions();
  89. Point marginsScaled = margins * scaleTo / dimensions();
  90. if(src)
  91. {
  92. Rect srcUnscaled(Point(src->topLeft() * dimensions() / scaleTo), Point(src->dimensions() * dimensions() / scaleTo));
  93. if(srcUnscaled.x < margins.x)
  94. destShift.x += marginsScaled.x - src->x;
  95. if(srcUnscaled.y < margins.y)
  96. destShift.y += marginsScaled.y - src->y;
  97. sourceRect = Rect(srcUnscaled).intersect(Rect(margins.x, margins.y, surf->w, surf->h));
  98. destScale.x = std::min(destScale.x, sourceRect.w * scaleTo.x / dimensions().x);
  99. destScale.y = std::min(destScale.y, sourceRect.h * scaleTo.y / dimensions().y);
  100. sourceRect -= margins;
  101. }
  102. else
  103. destShift = marginsScaled;
  104. destShift += dest;
  105. SDL_SetSurfaceColorMod(surf, colorMultiplier.r, colorMultiplier.g, colorMultiplier.b);
  106. SDL_SetSurfaceAlphaMod(surf, alpha);
  107. if (alpha != SDL_ALPHA_OPAQUE || (mode != EImageBlitMode::OPAQUE && surf->format->Amask != 0))
  108. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_BLEND);
  109. else
  110. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_NONE);
  111. if (palette && surf->format->palette)
  112. SDL_SetSurfacePalette(surf, palette);
  113. SDL_Rect srcRect = CSDL_Ext::toSDL(sourceRect);
  114. SDL_Rect dstRect = CSDL_Ext::toSDL(Rect(destShift, destScale));
  115. if (sourceRect.dimensions() * scaleTo / dimensions() != destScale)
  116. logGlobal->info("???");
  117. SDL_Surface * tempSurface = SDL_ConvertSurface(surf, where->format, 0);
  118. int result = SDL_BlitScaled(tempSurface, &srcRect, where, &dstRect);
  119. SDL_FreeSurface(tempSurface);
  120. if (result != 0)
  121. logGlobal->error("SDL_BlitScaled failed! %s", SDL_GetError());
  122. if (surf->format->palette)
  123. SDL_SetSurfacePalette(surf, originalPalette);
  124. }
  125. void SDLImageShared::draw(SDL_Surface * where, SDL_Palette * palette, const Point & dest, const Rect * src, const ColorRGBA & colorMultiplier, uint8_t alpha, EImageBlitMode mode) const
  126. {
  127. if(upscalingInProgress)
  128. throw std::runtime_error("Attempt to access images that is still being loaded!");
  129. if (!surf)
  130. return;
  131. Rect sourceRect(0, 0, surf->w, surf->h);
  132. Point destShift(0, 0);
  133. if(src)
  134. {
  135. if(src->x < margins.x)
  136. destShift.x += margins.x - src->x;
  137. if(src->y < margins.y)
  138. destShift.y += margins.y - src->y;
  139. sourceRect = Rect(*src).intersect(Rect(margins.x, margins.y, surf->w, surf->h));
  140. sourceRect -= margins;
  141. }
  142. else
  143. destShift = margins;
  144. destShift += dest;
  145. SDL_SetSurfaceColorMod(surf, colorMultiplier.r, colorMultiplier.g, colorMultiplier.b);
  146. SDL_SetSurfaceAlphaMod(surf, alpha);
  147. if (alpha != SDL_ALPHA_OPAQUE || (mode != EImageBlitMode::OPAQUE && surf->format->Amask != 0))
  148. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_BLEND);
  149. else
  150. SDL_SetSurfaceBlendMode(surf, SDL_BLENDMODE_NONE);
  151. if (palette && surf->format->palette)
  152. SDL_SetSurfacePalette(surf, palette);
  153. if(surf->format->palette && mode != EImageBlitMode::OPAQUE && mode != EImageBlitMode::COLORKEY)
  154. {
  155. CSDL_Ext::blit8bppAlphaTo24bpp(surf, sourceRect, where, destShift, alpha);
  156. }
  157. else
  158. {
  159. CSDL_Ext::blitSurface(surf, sourceRect, where, destShift);
  160. }
  161. if (surf->format->palette)
  162. SDL_SetSurfacePalette(surf, originalPalette);
  163. }
  164. void SDLImageShared::optimizeSurface()
  165. {
  166. assert(upscalingInProgress == false);
  167. if (!surf)
  168. return;
  169. SDLImageOptimizer optimizer(surf, Rect(margins, fullSize));
  170. optimizer.optimizeSurface(surf);
  171. SDL_FreeSurface(surf);
  172. surf = optimizer.acquireResultSurface();
  173. margins = optimizer.getResultDimensions().topLeft();
  174. fullSize = optimizer.getResultDimensions().dimensions();
  175. }
  176. std::shared_ptr<const ISharedImage> SDLImageShared::scaleInteger(int factor, SDL_Palette * palette, EImageBlitMode mode) const
  177. {
  178. if(upscalingInProgress)
  179. throw std::runtime_error("Attempt to access images that is still being loaded!");
  180. if (factor <= 0)
  181. throw std::runtime_error("Unable to scale by integer value of " + std::to_string(factor));
  182. if (!surf)
  183. return shared_from_this();
  184. if (palette && surf->format->palette)
  185. SDL_SetSurfacePalette(surf, palette);
  186. // simple heuristics to differentiate tileable UI elements from map object / combat assets
  187. EScalingAlgorithm algorithm;
  188. if (mode == EImageBlitMode::OPAQUE || mode == EImageBlitMode::COLORKEY || mode == EImageBlitMode::SIMPLE)
  189. algorithm = EScalingAlgorithm::XBRZ_OPAQUE;
  190. else
  191. algorithm = EScalingAlgorithm::XBRZ_ALPHA;
  192. auto result = std::make_shared<SDLImageShared>(this, factor, algorithm);
  193. if (surf->format->palette)
  194. SDL_SetSurfacePalette(surf, originalPalette);
  195. return result;
  196. }
  197. SDLImageShared::SDLImageShared(const SDLImageShared * from, int integerScaleFactor, EScalingAlgorithm algorithm)
  198. {
  199. upscalingInProgress = true;
  200. auto scaler = std::make_shared<SDLImageScaler>(from->surf, Rect(from->margins, from->fullSize), true);
  201. const auto & scalingTask = [this, algorithm, scaler]()
  202. {
  203. scaler->scaleSurfaceIntegerFactor(ENGINE->screenHandler().getScalingFactor(), algorithm);
  204. surf = scaler->acquireResultSurface();
  205. fullSize = scaler->getResultDimensions().dimensions();
  206. margins = scaler->getResultDimensions().topLeft();
  207. upscalingInProgress = false;
  208. };
  209. if(settings["video"]["asyncUpscaling"].Bool())
  210. ENGINE->async().run(scalingTask);
  211. else
  212. scalingTask();
  213. }
  214. bool SDLImageShared::isLoading() const
  215. {
  216. return upscalingInProgress;
  217. }
  218. std::shared_ptr<const ISharedImage> SDLImageShared::scaleTo(const Point & size, SDL_Palette * palette) const
  219. {
  220. if(upscalingInProgress)
  221. throw std::runtime_error("Attempt to access images that is still being loaded!");
  222. if (palette && surf->format->palette)
  223. SDL_SetSurfacePalette(surf, palette);
  224. SDLImageScaler scaler(surf, Rect(margins, fullSize), true);
  225. scaler.scaleSurface(size, EScalingAlgorithm::XBRZ_ALPHA);
  226. auto scaled = scaler.acquireResultSurface();
  227. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  228. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  229. else if(scaled->format && scaled->format->Amask)
  230. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  231. else
  232. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  233. auto ret = std::make_shared<SDLImageShared>(scaled);
  234. ret->fullSize = scaler.getResultDimensions().dimensions();
  235. ret->margins = scaler.getResultDimensions().topLeft();
  236. // erase our own reference
  237. SDL_FreeSurface(scaled);
  238. if (surf->format->palette)
  239. SDL_SetSurfacePalette(surf, originalPalette);
  240. return ret;
  241. }
  242. void SDLImageShared::exportBitmap(const boost::filesystem::path& path, SDL_Palette * palette) const
  243. {
  244. auto directory = path;
  245. directory.remove_filename();
  246. boost::filesystem::create_directories(directory);
  247. if(upscalingInProgress)
  248. throw std::runtime_error("Attempt to access images that is still being loaded!");
  249. if (!surf)
  250. return;
  251. if (palette && surf->format->palette)
  252. SDL_SetSurfacePalette(surf, palette);
  253. IMG_SavePNG(surf, path.string().c_str());
  254. if (palette && surf->format->palette)
  255. SDL_SetSurfacePalette(surf, originalPalette);
  256. }
  257. bool SDLImageShared::isTransparent(const Point & coords) const
  258. {
  259. if(upscalingInProgress)
  260. throw std::runtime_error("Attempt to access images that is still being loaded!");
  261. if (!surf)
  262. return true;
  263. Point test = coords - margins;
  264. if (test.x < 0 || test.y < 0 || test.x >= surf->w || test.y >= surf->h)
  265. return true;
  266. SDL_Color color;
  267. SDL_GetRGBA(CSDL_Ext::getPixel(surf, test.x, test.y), surf->format, &color.r, &color.g, &color.b, &color.a);
  268. bool pixelTransparent = color.a < 128;
  269. bool pixelCyan = (color.r == 0 && color.g == 255 && color.b == 255);
  270. return pixelTransparent || pixelCyan;
  271. }
  272. Rect SDLImageShared::contentRect() const
  273. {
  274. if(upscalingInProgress)
  275. throw std::runtime_error("Attempt to access images that is still being loaded!");
  276. auto tmpMargins = margins;
  277. auto tmpSize = Point(surf->w, surf->h);
  278. return Rect(tmpMargins, tmpSize);
  279. }
  280. const SDL_Palette * SDLImageShared::getPalette() const
  281. {
  282. if(upscalingInProgress)
  283. throw std::runtime_error("Attempt to access images that is still being loaded!");
  284. if (!surf)
  285. return nullptr;
  286. return surf->format->palette;
  287. }
  288. Point SDLImageShared::dimensions() const
  289. {
  290. if(upscalingInProgress)
  291. throw std::runtime_error("Attempt to access images that is still being loaded!");
  292. return fullSize;
  293. }
  294. std::shared_ptr<const ISharedImage> SDLImageShared::horizontalFlip() const
  295. {
  296. if(upscalingInProgress)
  297. throw std::runtime_error("Attempt to access images that is still being loaded!");
  298. if (!surf)
  299. return shared_from_this();
  300. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  301. auto ret = std::make_shared<SDLImageShared>(flipped);
  302. ret->fullSize = fullSize;
  303. ret->margins.x = margins.x;
  304. ret->margins.y = fullSize.y - surf->h - margins.y;
  305. ret->fullSize = fullSize;
  306. return ret;
  307. }
  308. std::shared_ptr<const ISharedImage> SDLImageShared::verticalFlip() const
  309. {
  310. if(upscalingInProgress)
  311. throw std::runtime_error("Attempt to access images that is still being loaded!");
  312. if (!surf)
  313. return shared_from_this();
  314. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  315. auto ret = std::make_shared<SDLImageShared>(flipped);
  316. ret->fullSize = fullSize;
  317. ret->margins.x = fullSize.x - surf->w - margins.x;
  318. ret->margins.y = margins.y;
  319. ret->fullSize = fullSize;
  320. return ret;
  321. }
  322. // Keep the original palette, in order to do color switching operation
  323. void SDLImageShared::savePalette()
  324. {
  325. if(upscalingInProgress)
  326. throw std::runtime_error("Attempt to access images that is still being loaded!");
  327. // For some images that don't have palette, skip this
  328. if(surf->format->palette == nullptr)
  329. return;
  330. if(originalPalette == nullptr)
  331. originalPalette = SDL_AllocPalette(surf->format->palette->ncolors);
  332. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, surf->format->palette->ncolors);
  333. }
  334. SDLImageShared::~SDLImageShared()
  335. {
  336. SDL_FreeSurface(surf);
  337. SDL_FreePalette(originalPalette);
  338. }