SDLImage.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 <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, bool optimizeImage)
  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. if(optimizeImage)
  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 = SDLImageShared::createScaled(this, factor, algorithm);
  193. if (surf->format->palette)
  194. SDL_SetSurfacePalette(surf, originalPalette);
  195. return result;
  196. }
  197. std::shared_ptr<SDLImageShared> SDLImageShared::createScaled(const SDLImageShared * from, int integerScaleFactor, EScalingAlgorithm algorithm)
  198. {
  199. auto self = std::make_shared<SDLImageShared>(nullptr);
  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(ENGINE->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. ENGINE->async().run(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 true;
  265. Point test = coords - margins;
  266. if (test.x < 0 || test.y < 0 || test.x >= surf->w || test.y >= surf->h)
  267. return true;
  268. SDL_Color color;
  269. SDL_GetRGBA(CSDL_Ext::getPixel(surf, test.x, test.y), surf->format, &color.r, &color.g, &color.b, &color.a);
  270. bool pixelTransparent = color.a < 128;
  271. bool pixelCyan = (color.r == 0 && color.g == 255 && color.b == 255);
  272. return pixelTransparent || pixelCyan;
  273. }
  274. Rect SDLImageShared::contentRect() const
  275. {
  276. if(upscalingInProgress)
  277. throw std::runtime_error("Attempt to access images that is still being loaded!");
  278. if (!surf)
  279. return Rect();
  280. return Rect(margins, Point(surf->w, surf->h));
  281. }
  282. const SDL_Palette * SDLImageShared::getPalette() const
  283. {
  284. if(upscalingInProgress)
  285. throw std::runtime_error("Attempt to access images that is still being loaded!");
  286. if (!surf)
  287. return nullptr;
  288. return surf->format->palette;
  289. }
  290. Point SDLImageShared::dimensions() const
  291. {
  292. if(upscalingInProgress)
  293. throw std::runtime_error("Attempt to access images that is still being loaded!");
  294. return fullSize;
  295. }
  296. std::shared_ptr<const ISharedImage> SDLImageShared::horizontalFlip() const
  297. {
  298. if(upscalingInProgress)
  299. throw std::runtime_error("Attempt to access images that is still being loaded!");
  300. if (!surf)
  301. return shared_from_this();
  302. SDL_Surface * flipped = CSDL_Ext::horizontalFlip(surf);
  303. auto ret = std::make_shared<SDLImageShared>(flipped);
  304. ret->fullSize = fullSize;
  305. ret->margins.x = margins.x;
  306. ret->margins.y = fullSize.y - surf->h - margins.y;
  307. ret->fullSize = fullSize;
  308. // erase our own reference
  309. SDL_FreeSurface(flipped);
  310. return ret;
  311. }
  312. std::shared_ptr<const ISharedImage> SDLImageShared::verticalFlip() const
  313. {
  314. if(upscalingInProgress)
  315. throw std::runtime_error("Attempt to access images that is still being loaded!");
  316. if (!surf)
  317. return shared_from_this();
  318. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  319. auto ret = std::make_shared<SDLImageShared>(flipped);
  320. ret->fullSize = fullSize;
  321. ret->margins.x = fullSize.x - surf->w - margins.x;
  322. ret->margins.y = margins.y;
  323. ret->fullSize = fullSize;
  324. // erase our own reference
  325. SDL_FreeSurface(flipped);
  326. return ret;
  327. }
  328. std::shared_ptr<SDLImageShared> SDLImageShared::drawShadow(bool doSheer) const
  329. {
  330. if(upscalingInProgress)
  331. throw std::runtime_error("Attempt to access images that is still being loaded!");
  332. if (!surf)
  333. return nullptr;
  334. SDL_Surface * shadow = CSDL_Ext::drawShadow(surf, doSheer);
  335. auto ret = std::make_shared<SDLImageShared>(shadow);
  336. ret->fullSize = fullSize;
  337. ret->margins.x = margins.x;
  338. ret->margins.y = margins.y;
  339. ret->optimizeSurface();
  340. // erase our own reference
  341. SDL_FreeSurface(shadow);
  342. return ret;
  343. }
  344. std::shared_ptr<SDLImageShared> SDLImageShared::drawOutline(const ColorRGBA & color, int thickness) const
  345. {
  346. if(upscalingInProgress)
  347. throw std::runtime_error("Attempt to access images that is still being loaded!");
  348. if (!surf)
  349. return nullptr;
  350. SDL_Color sdlColor = { color.r, color.g, color.b, color.a };
  351. SDL_Surface * outline = CSDL_Ext::drawOutline(surf, sdlColor, thickness);
  352. auto ret = std::make_shared<SDLImageShared>(outline);
  353. ret->fullSize = fullSize;
  354. ret->margins.x = margins.x;
  355. ret->margins.y = margins.y;
  356. ret->optimizeSurface();
  357. // erase our own reference
  358. SDL_FreeSurface(outline);
  359. return ret;
  360. }
  361. // Keep the original palette, in order to do color switching operation
  362. void SDLImageShared::savePalette()
  363. {
  364. if(upscalingInProgress)
  365. throw std::runtime_error("Attempt to access images that is still being loaded!");
  366. // For some images that don't have palette, skip this
  367. if(surf->format->palette == nullptr)
  368. return;
  369. if(originalPalette == nullptr)
  370. originalPalette = SDL_AllocPalette(surf->format->palette->ncolors);
  371. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, surf->format->palette->ncolors);
  372. }
  373. SDLImageShared::~SDLImageShared()
  374. {
  375. SDL_FreeSurface(surf);
  376. if (originalPalette)
  377. SDL_FreePalette(originalPalette);
  378. }