SDLImage.cpp 12 KB

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