SDLImage.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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() && from->getAsyncUpscale())
  211. ENGINE->async().run(scalingTask);
  212. else
  213. scalingTask();
  214. return self;
  215. }
  216. bool SDLImageShared::isLoading() const
  217. {
  218. return upscalingInProgress;
  219. }
  220. void SDLImageShared::setAsyncUpscale(bool on)
  221. {
  222. asyncUpscale = on;
  223. }
  224. bool SDLImageShared::getAsyncUpscale() const
  225. {
  226. return asyncUpscale;
  227. }
  228. std::shared_ptr<const ISharedImage> SDLImageShared::scaleTo(const Point & size, SDL_Palette * palette) const
  229. {
  230. if(upscalingInProgress)
  231. throw std::runtime_error("Attempt to access images that is still being loaded!");
  232. if (palette && surf->format->palette)
  233. SDL_SetSurfacePalette(surf, palette);
  234. SDLImageScaler scaler(surf, Rect(margins, fullSize), true);
  235. scaler.scaleSurface(size, EScalingAlgorithm::XBRZ_ALPHA);
  236. auto scaled = scaler.acquireResultSurface();
  237. if (scaled->format && scaled->format->palette) // fix color keying, because SDL loses it at this point
  238. CSDL_Ext::setColorKey(scaled, scaled->format->palette->colors[0]);
  239. else if(scaled->format && scaled->format->Amask)
  240. SDL_SetSurfaceBlendMode(scaled, SDL_BLENDMODE_BLEND);//just in case
  241. else
  242. CSDL_Ext::setDefaultColorKey(scaled);//just in case
  243. auto ret = std::make_shared<SDLImageShared>(scaled);
  244. ret->fullSize = scaler.getResultDimensions().dimensions();
  245. ret->margins = scaler.getResultDimensions().topLeft();
  246. // erase our own reference
  247. SDL_FreeSurface(scaled);
  248. if (surf->format->palette)
  249. SDL_SetSurfacePalette(surf, originalPalette);
  250. return ret;
  251. }
  252. void SDLImageShared::exportBitmap(const boost::filesystem::path& path, SDL_Palette * palette) const
  253. {
  254. auto directory = path;
  255. directory.remove_filename();
  256. boost::filesystem::create_directories(directory);
  257. if(upscalingInProgress)
  258. throw std::runtime_error("Attempt to access images that is still being loaded!");
  259. if (!surf)
  260. return;
  261. if (palette && surf->format->palette)
  262. SDL_SetSurfacePalette(surf, palette);
  263. IMG_SavePNG(surf, path.string().c_str());
  264. if (palette && surf->format->palette)
  265. SDL_SetSurfacePalette(surf, originalPalette);
  266. }
  267. bool SDLImageShared::isTransparent(const Point & coords) const
  268. {
  269. if(upscalingInProgress)
  270. throw std::runtime_error("Attempt to access images that is still being loaded!");
  271. if (!surf)
  272. return true;
  273. Point test = coords - margins;
  274. if (test.x < 0 || test.y < 0 || test.x >= surf->w || test.y >= surf->h)
  275. return true;
  276. SDL_Color color;
  277. SDL_GetRGBA(CSDL_Ext::getPixel(surf, test.x, test.y), surf->format, &color.r, &color.g, &color.b, &color.a);
  278. bool pixelTransparent = color.a < 128;
  279. bool pixelCyan = (color.r == 0 && color.g == 255 && color.b == 255);
  280. return pixelTransparent || pixelCyan;
  281. }
  282. Rect SDLImageShared::contentRect() const
  283. {
  284. if(upscalingInProgress)
  285. throw std::runtime_error("Attempt to access images that is still being loaded!");
  286. if (!surf)
  287. return Rect();
  288. return Rect(margins, Point(surf->w, surf->h));
  289. }
  290. const SDL_Palette * SDLImageShared::getPalette() const
  291. {
  292. if(upscalingInProgress)
  293. throw std::runtime_error("Attempt to access images that is still being loaded!");
  294. if (!surf)
  295. return nullptr;
  296. return surf->format->palette;
  297. }
  298. Point SDLImageShared::dimensions() const
  299. {
  300. if(upscalingInProgress)
  301. throw std::runtime_error("Attempt to access images that is still being loaded!");
  302. return fullSize;
  303. }
  304. std::shared_ptr<const ISharedImage> SDLImageShared::horizontalFlip() 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::horizontalFlip(surf);
  311. auto ret = std::make_shared<SDLImageShared>(flipped);
  312. ret->fullSize = fullSize;
  313. ret->margins.x = margins.x;
  314. ret->margins.y = fullSize.y - surf->h - margins.y;
  315. ret->fullSize = fullSize;
  316. // erase our own reference
  317. SDL_FreeSurface(flipped);
  318. return ret;
  319. }
  320. std::shared_ptr<const ISharedImage> SDLImageShared::verticalFlip() const
  321. {
  322. if(upscalingInProgress)
  323. throw std::runtime_error("Attempt to access images that is still being loaded!");
  324. if (!surf)
  325. return shared_from_this();
  326. SDL_Surface * flipped = CSDL_Ext::verticalFlip(surf);
  327. auto ret = std::make_shared<SDLImageShared>(flipped);
  328. ret->fullSize = fullSize;
  329. ret->margins.x = fullSize.x - surf->w - margins.x;
  330. ret->margins.y = margins.y;
  331. ret->fullSize = fullSize;
  332. // erase our own reference
  333. SDL_FreeSurface(flipped);
  334. return ret;
  335. }
  336. std::shared_ptr<SDLImageShared> SDLImageShared::drawShadow(bool doSheer) const
  337. {
  338. if(upscalingInProgress)
  339. throw std::runtime_error("Attempt to access images that is still being loaded!");
  340. if (!surf)
  341. return nullptr;
  342. SDL_Surface * shadow = CSDL_Ext::drawShadow(surf, doSheer);
  343. auto ret = std::make_shared<SDLImageShared>(shadow);
  344. ret->fullSize = fullSize;
  345. ret->margins.x = margins.x;
  346. ret->margins.y = margins.y;
  347. ret->optimizeSurface();
  348. // erase our own reference
  349. SDL_FreeSurface(shadow);
  350. return ret;
  351. }
  352. std::shared_ptr<SDLImageShared> SDLImageShared::drawOutline(const ColorRGBA & color, int thickness) const
  353. {
  354. if(upscalingInProgress)
  355. throw std::runtime_error("Attempt to access images that is still being loaded!");
  356. if (!surf)
  357. return nullptr;
  358. SDL_Color sdlColor = { color.r, color.g, color.b, color.a };
  359. SDL_Surface * outline = CSDL_Ext::drawOutline(surf, sdlColor, thickness);
  360. auto ret = std::make_shared<SDLImageShared>(outline);
  361. ret->fullSize = fullSize;
  362. ret->margins.x = margins.x;
  363. ret->margins.y = margins.y;
  364. ret->optimizeSurface();
  365. // erase our own reference
  366. SDL_FreeSurface(outline);
  367. return ret;
  368. }
  369. // Keep the original palette, in order to do color switching operation
  370. void SDLImageShared::savePalette()
  371. {
  372. if(upscalingInProgress)
  373. throw std::runtime_error("Attempt to access images that is still being loaded!");
  374. // For some images that don't have palette, skip this
  375. if(surf->format->palette == nullptr)
  376. return;
  377. if(originalPalette == nullptr)
  378. originalPalette = SDL_AllocPalette(surf->format->palette->ncolors);
  379. SDL_SetPaletteColors(originalPalette, surf->format->palette->colors, 0, surf->format->palette->ncolors);
  380. }
  381. SDLImageShared::~SDLImageShared()
  382. {
  383. SDL_FreeSurface(surf);
  384. if (originalPalette)
  385. SDL_FreePalette(originalPalette);
  386. }