SDL_Extensions.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. /*
  2. * SDL_Extensions.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 "SDL_Extensions.h"
  12. #include "SDL_PixelAccess.h"
  13. #include "../GameEngine.h"
  14. #include "../render/Graphics.h"
  15. #include "../render/IImage.h"
  16. #include "../render/IScreenHandler.h"
  17. #include "../render/Colors.h"
  18. #include "../CMT.h"
  19. #include "../xBRZ/xbrz.h"
  20. #include "../../lib/GameConstants.h"
  21. #include <tbb/parallel_for.h>
  22. #include <tbb/parallel_reduce.h>
  23. #include <SDL_render.h>
  24. #include <SDL_surface.h>
  25. #include <SDL_version.h>
  26. Rect CSDL_Ext::fromSDL(const SDL_Rect & rect)
  27. {
  28. return Rect(Point(rect.x, rect.y), Point(rect.w, rect.h));
  29. }
  30. SDL_Rect CSDL_Ext::toSDL(const Rect & rect)
  31. {
  32. SDL_Rect result;
  33. result.x = rect.x;
  34. result.y = rect.y;
  35. result.w = rect.w;
  36. result.h = rect.h;
  37. return result;
  38. }
  39. ColorRGBA CSDL_Ext::fromSDL(const SDL_Color & color)
  40. {
  41. return { color.r, color.g, color.b, color.a };
  42. }
  43. SDL_Color CSDL_Ext::toSDL(const ColorRGBA & color)
  44. {
  45. SDL_Color result;
  46. result.r = color.r;
  47. result.g = color.g;
  48. result.b = color.b;
  49. result.a = color.a;
  50. return result;
  51. }
  52. SDL_Surface * CSDL_Ext::newSurface(const Point & dimensions)
  53. {
  54. return newSurface(dimensions, nullptr);
  55. }
  56. SDL_Surface * CSDL_Ext::newSurface(const Point & dimensions, SDL_Surface * mod) //creates new surface, with flags/format same as in surface given
  57. {
  58. SDL_Surface * ret = nullptr;
  59. if (mod != nullptr)
  60. ret = SDL_CreateRGBSurface(0,dimensions.x,dimensions.y,mod->format->BitsPerPixel,mod->format->Rmask,mod->format->Gmask,mod->format->Bmask,mod->format->Amask);
  61. else
  62. ret = SDL_CreateRGBSurfaceWithFormat(0,dimensions.x,dimensions.y,32,SDL_PixelFormatEnum::SDL_PIXELFORMAT_ARGB8888);
  63. if(ret == nullptr)
  64. {
  65. const char * error = SDL_GetError();
  66. std::string messagePattern = "Failed to create SDL Surface of size %d x %d. Reason: %s";
  67. std::string message = boost::str(boost::format(messagePattern) % dimensions.x % dimensions.y % error);
  68. throw std::runtime_error(message);
  69. }
  70. if (mod && mod->format->palette)
  71. {
  72. assert(ret->format->palette);
  73. assert(ret->format->palette->ncolors >= mod->format->palette->ncolors);
  74. memcpy(ret->format->palette->colors, mod->format->palette->colors, mod->format->palette->ncolors * sizeof(SDL_Color));
  75. }
  76. return ret;
  77. }
  78. void CSDL_Ext::blitAt(SDL_Surface * src, int x, int y, SDL_Surface * dst)
  79. {
  80. CSDL_Ext::blitSurface(src, dst, Point(x, y));
  81. }
  82. void CSDL_Ext::blitAt(SDL_Surface * src, const Rect & pos, SDL_Surface * dst)
  83. {
  84. if (src)
  85. blitAt(src,pos.x,pos.y,dst);
  86. }
  87. // Vertical flip
  88. SDL_Surface * CSDL_Ext::verticalFlip(SDL_Surface * toRot)
  89. {
  90. SDL_Surface * ret = SDL_ConvertSurface(toRot, toRot->format, toRot->flags);
  91. SDL_LockSurface(ret);
  92. SDL_LockSurface(toRot);
  93. const int bpp = ret->format->BytesPerPixel;
  94. char * src = reinterpret_cast<char *>(toRot->pixels);
  95. char * dst = reinterpret_cast<char *>(ret->pixels);
  96. for(int i=0; i<ret->h; i++)
  97. {
  98. //FIXME: optimization bugged
  99. // if (bpp == 1)
  100. // {
  101. // // much faster for 8-bit surfaces (majority of our data)
  102. // std::reverse_copy(src, src + toRot->pitch, dst);
  103. // }
  104. // else
  105. // {
  106. char * srcPxl = src;
  107. char * dstPxl = dst + ret->w * bpp;
  108. for(int j=0; j<ret->w; j++)
  109. {
  110. dstPxl -= bpp;
  111. std::copy(srcPxl, srcPxl + bpp, dstPxl);
  112. srcPxl += bpp;
  113. }
  114. // }
  115. src += toRot->pitch;
  116. dst += ret->pitch;
  117. }
  118. SDL_UnlockSurface(ret);
  119. SDL_UnlockSurface(toRot);
  120. return ret;
  121. }
  122. // Horizontal flip
  123. SDL_Surface * CSDL_Ext::horizontalFlip(SDL_Surface * toRot)
  124. {
  125. SDL_Surface * ret = SDL_ConvertSurface(toRot, toRot->format, toRot->flags);
  126. SDL_LockSurface(ret);
  127. SDL_LockSurface(toRot);
  128. char * src = reinterpret_cast<char *>(toRot->pixels);
  129. char * dst = reinterpret_cast<char *>(ret->pixels) + ret->h * ret->pitch;
  130. for(int i=0; i<ret->h; i++)
  131. {
  132. dst -= ret->pitch;
  133. std::copy(src, src + toRot->pitch, dst);
  134. src += toRot->pitch;
  135. }
  136. SDL_UnlockSurface(ret);
  137. SDL_UnlockSurface(toRot);
  138. return ret;
  139. }
  140. uint32_t CSDL_Ext::getPixel(SDL_Surface *surface, const int & x, const int & y, bool colorByte)
  141. {
  142. int bpp = surface->format->BytesPerPixel;
  143. /* Here p is the address to the pixel we want to retrieve */
  144. uint8_t *p = (uint8_t *)surface->pixels + y * surface->pitch + x * bpp;
  145. switch(bpp)
  146. {
  147. case 1:
  148. if(colorByte)
  149. return colorTouint32_t(surface->format->palette->colors+(*p));
  150. else
  151. return *p;
  152. case 2:
  153. return *(uint16_t *)p;
  154. case 3:
  155. return p[0] | p[1] << 8 | p[2] << 16;
  156. case 4:
  157. return *(uint32_t *)p;
  158. default:
  159. return 0; // shouldn't happen, but avoids warnings
  160. }
  161. }
  162. template<int bpp, bool useAlpha>
  163. int CSDL_Ext::blit8bppAlphaTo24bppT(const SDL_Surface * src, const Rect & srcRectInput, SDL_Surface * dst, const Point & dstPointInput, [[maybe_unused]] uint8_t alpha)
  164. {
  165. SDL_Rect srcRectInstance = CSDL_Ext::toSDL(srcRectInput);
  166. SDL_Rect dstRectInstance = CSDL_Ext::toSDL(Rect(dstPointInput, srcRectInput.dimensions()));
  167. SDL_Rect * srcRect =&srcRectInstance;
  168. SDL_Rect * dstRect =&dstRectInstance;
  169. /* Make sure the surfaces aren't locked */
  170. if ( ! src || ! dst )
  171. {
  172. SDL_SetError("SDL_UpperBlit: passed a nullptr surface");
  173. return -1;
  174. }
  175. if ( src->locked || dst->locked )
  176. {
  177. SDL_SetError("Surfaces must not be locked during blit");
  178. return -1;
  179. }
  180. if (src->format->BytesPerPixel==1 && (bpp==3 || bpp==4 || bpp==2)) //everything's ok
  181. {
  182. SDL_Rect fulldst;
  183. int srcx;
  184. int srcy;
  185. int w;
  186. int h;
  187. /* If the destination rectangle is nullptr, use the entire dest surface */
  188. if ( dstRect == nullptr )
  189. {
  190. fulldst.x = fulldst.y = 0;
  191. dstRect = &fulldst;
  192. }
  193. /* clip the source rectangle to the source surface */
  194. if(srcRect)
  195. {
  196. int maxw;
  197. int maxh;
  198. srcx = srcRect->x;
  199. w = srcRect->w;
  200. if(srcx < 0)
  201. {
  202. w += srcx;
  203. dstRect->x -= srcx;
  204. srcx = 0;
  205. }
  206. maxw = src->w - srcx;
  207. if(maxw < w)
  208. w = maxw;
  209. srcy = srcRect->y;
  210. h = srcRect->h;
  211. if(srcy < 0)
  212. {
  213. h += srcy;
  214. dstRect->y -= srcy;
  215. srcy = 0;
  216. }
  217. maxh = src->h - srcy;
  218. if(maxh < h)
  219. h = maxh;
  220. }
  221. else
  222. {
  223. srcx = srcy = 0;
  224. w = src->w;
  225. h = src->h;
  226. }
  227. /* clip the destination rectangle against the clip rectangle */
  228. {
  229. SDL_Rect *clip = &dst->clip_rect;
  230. int dx;
  231. int dy;
  232. dx = clip->x - dstRect->x;
  233. if(dx > 0)
  234. {
  235. w -= dx;
  236. dstRect->x += dx;
  237. srcx += dx;
  238. }
  239. dx = dstRect->x + w - clip->x - clip->w;
  240. if(dx > 0)
  241. w -= dx;
  242. dy = clip->y - dstRect->y;
  243. if(dy > 0)
  244. {
  245. h -= dy;
  246. dstRect->y += dy;
  247. srcy += dy;
  248. }
  249. dy = dstRect->y + h - clip->y - clip->h;
  250. if(dy > 0)
  251. h -= dy;
  252. }
  253. if(w > 0 && h > 0)
  254. {
  255. dstRect->w = w;
  256. dstRect->h = h;
  257. if(SDL_LockSurface(dst))
  258. return -1; //if we cannot lock the surface
  259. const SDL_Color *colors = src->format->palette->colors;
  260. uint8_t *colory = (uint8_t*)src->pixels + srcy*src->pitch + srcx;
  261. uint8_t *py = (uint8_t*)dst->pixels + dstRect->y*dst->pitch + dstRect->x*bpp;
  262. for(int y=0; y<h; ++y, colory+=src->pitch, py+=dst->pitch)
  263. {
  264. uint8_t *color = colory;
  265. uint8_t *p = py;
  266. for(int x = 0; x < w; ++x)
  267. {
  268. const SDL_Color &tbc = colors[*color++]; //color to blit
  269. if constexpr (useAlpha)
  270. ColorPutter<bpp>::PutColorAlphaSwitch(p, tbc.r, tbc.g, tbc.b, int(alpha) * tbc.a / 255 );
  271. else
  272. ColorPutter<bpp>::PutColorAlphaSwitch(p, tbc.r, tbc.g, tbc.b, tbc.a);
  273. p += bpp;
  274. }
  275. }
  276. SDL_UnlockSurface(dst);
  277. }
  278. }
  279. return 0;
  280. }
  281. int CSDL_Ext::blit8bppAlphaTo24bpp(const SDL_Surface * src, const Rect & srcRect, SDL_Surface * dst, const Point & dstPoint, uint8_t alpha)
  282. {
  283. if (alpha == SDL_ALPHA_OPAQUE)
  284. {
  285. switch(dst->format->BytesPerPixel)
  286. {
  287. case 3: return blit8bppAlphaTo24bppT<3, false>(src, srcRect, dst, dstPoint, alpha);
  288. case 4: return blit8bppAlphaTo24bppT<4, false>(src, srcRect, dst, dstPoint, alpha);
  289. }
  290. }
  291. else
  292. {
  293. switch(dst->format->BytesPerPixel)
  294. {
  295. case 3: return blit8bppAlphaTo24bppT<3, true>(src, srcRect, dst, dstPoint, alpha);
  296. case 4: return blit8bppAlphaTo24bppT<4, true>(src, srcRect, dst, dstPoint, alpha);
  297. }
  298. }
  299. logGlobal->error("%d bpp is not supported!", (int)dst->format->BitsPerPixel);
  300. return -1;
  301. }
  302. uint32_t CSDL_Ext::colorTouint32_t(const SDL_Color * color)
  303. {
  304. uint32_t ret = 0;
  305. ret+=color->a;
  306. ret<<=8; //*=256
  307. ret+=color->b;
  308. ret<<=8; //*=256
  309. ret+=color->g;
  310. ret<<=8; //*=256
  311. ret+=color->r;
  312. return ret;
  313. }
  314. static void drawLineXDashed(SDL_Surface * sur, int x1, int y1, int x2, int y2, const SDL_Color & color)
  315. {
  316. double length(x2 - x1);
  317. for(int x = x1; x <= x2; x++)
  318. {
  319. double f = (x - x1) / length;
  320. int y = vstd::lerp(y1, y2, f);
  321. if (std::abs(x - x1) % 5 != 4)
  322. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur, x, y, color.r, color.g, color.b);
  323. }
  324. }
  325. static void drawLineYDashed(SDL_Surface * sur, int x1, int y1, int x2, int y2, const SDL_Color & color)
  326. {
  327. double length(y2 - y1);
  328. for(int y = y1; y <= y2; y++)
  329. {
  330. double f = (y - y1) / length;
  331. int x = vstd::lerp(x1, x2, f);
  332. if (std::abs(y - y1) % 5 != 4)
  333. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur, x, y, color.r, color.g, color.b);
  334. }
  335. }
  336. static void drawLineX(SDL_Surface * sur, int x1, int y1, int x2, int y2, const SDL_Color & color1, const SDL_Color & color2)
  337. {
  338. double length(x2 - x1);
  339. for(int x = x1; x <= x2; x++)
  340. {
  341. double f = (x - x1) / length;
  342. int y = vstd::lerp(y1, y2, f);
  343. uint8_t r = vstd::lerp(color1.r, color2.r, f);
  344. uint8_t g = vstd::lerp(color1.g, color2.g, f);
  345. uint8_t b = vstd::lerp(color1.b, color2.b, f);
  346. uint8_t a = vstd::lerp(color1.a, color2.a, f);
  347. uint8_t *p = CSDL_Ext::getPxPtr(sur, x, y);
  348. ColorPutter<4>::PutColor(p, r,g,b,a);
  349. }
  350. }
  351. static void drawLineY(SDL_Surface * sur, int x1, int y1, int x2, int y2, const SDL_Color & color1, const SDL_Color & color2)
  352. {
  353. double length(y2 - y1);
  354. for(int y = y1; y <= y2; y++)
  355. {
  356. double f = (y - y1) / length;
  357. int x = vstd::lerp(x1, x2, f);
  358. uint8_t r = vstd::lerp(color1.r, color2.r, f);
  359. uint8_t g = vstd::lerp(color1.g, color2.g, f);
  360. uint8_t b = vstd::lerp(color1.b, color2.b, f);
  361. uint8_t a = vstd::lerp(color1.a, color2.a, f);
  362. uint8_t *p = CSDL_Ext::getPxPtr(sur, x, y);
  363. ColorPutter<4>::PutColor(p, r,g,b,a);
  364. }
  365. }
  366. void CSDL_Ext::drawLine(SDL_Surface * sur, const Point & from, const Point & dest, const SDL_Color & color1, const SDL_Color & color2, int thickness)
  367. {
  368. //FIXME: duplicated code with drawLineDashed
  369. int width = std::abs(from.x - dest.x);
  370. int height = std::abs(from.y - dest.y);
  371. if(width == 0 && height == 0)
  372. {
  373. uint8_t * p = CSDL_Ext::getPxPtr(sur, from.x, from.y);
  374. ColorPutter<4>::PutColorAlpha(p, color1);
  375. return;
  376. }
  377. for(int i = 0; i < thickness; ++i)
  378. {
  379. if(width > height)
  380. {
  381. if(from.x < dest.x)
  382. drawLineX(sur, from.x, from.y + i, dest.x, dest.y + i, color1, color2);
  383. else
  384. drawLineX(sur, dest.x, dest.y + i, from.x, from.y + i, color2, color1);
  385. }
  386. else
  387. {
  388. if(from.y < dest.y)
  389. drawLineY(sur, from.x + i, from.y, dest.x + i, dest.y, color1, color2);
  390. else
  391. drawLineY(sur, dest.x + i, dest.y, from.x + i, from.y, color2, color1);
  392. }
  393. }
  394. }
  395. void CSDL_Ext::drawLineDashed(SDL_Surface * sur, const Point & from, const Point & dest, const SDL_Color & color)
  396. {
  397. //FIXME: duplicated code with drawLine
  398. int width = std::abs(from.x - dest.x);
  399. int height = std::abs(from.y - dest.y);
  400. if ( width == 0 && height == 0)
  401. {
  402. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur, from.x, from.y, color.r, color.g, color.b);
  403. return;
  404. }
  405. if (width > height)
  406. {
  407. if ( from.x < dest.x)
  408. drawLineXDashed(sur, from.x, from.y, dest.x, dest.y, color);
  409. else
  410. drawLineXDashed(sur, dest.x, dest.y, from.x, from.y, color);
  411. }
  412. else
  413. {
  414. if ( from.y < dest.y)
  415. drawLineYDashed(sur, from.x, from.y, dest.x, dest.y, color);
  416. else
  417. drawLineYDashed(sur, dest.x, dest.y, from.x, from.y, color);
  418. }
  419. }
  420. void CSDL_Ext::drawBorder(SDL_Surface * sur, int x, int y, int w, int h, const SDL_Color &color, int depth)
  421. {
  422. depth = std::max(1, depth);
  423. for(int depthIterator = 0; depthIterator < depth; depthIterator++)
  424. {
  425. for(int i = 0; i < w; i++)
  426. {
  427. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur,x+i,y+depthIterator,color.r,color.g,color.b);
  428. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur,x+i,y+h-1-depthIterator,color.r,color.g,color.b);
  429. }
  430. for(int i = 0; i < h; i++)
  431. {
  432. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur,x+depthIterator,y+i,color.r,color.g,color.b);
  433. CSDL_Ext::putPixelWithoutRefreshIfInSurf(sur,x+w-1-depthIterator,y+i,color.r,color.g,color.b);
  434. }
  435. }
  436. }
  437. void CSDL_Ext::drawBorder( SDL_Surface * sur, const Rect &r, const SDL_Color &color, int depth)
  438. {
  439. drawBorder(sur, r.x, r.y, r.w, r.h, color, depth);
  440. }
  441. uint8_t * CSDL_Ext::getPxPtr(const SDL_Surface * const &srf, const int x, const int y)
  442. {
  443. return (uint8_t *)srf->pixels + y * srf->pitch + x * srf->format->BytesPerPixel;
  444. }
  445. void CSDL_Ext::putPixelWithoutRefresh(SDL_Surface *ekran, const int & x, const int & y, const uint8_t & R, const uint8_t & G, const uint8_t & B, uint8_t A)
  446. {
  447. uint8_t *p = getPxPtr(ekran, x, y);
  448. switch(ekran->format->BytesPerPixel)
  449. {
  450. case 3:
  451. ColorPutter<3>::PutColor(p, R, G, B);
  452. Channels::px<3>::a.set(p, A); break;
  453. case 4:
  454. ColorPutter<4>::PutColor(p, R, G, B);
  455. Channels::px<4>::a.set(p, A); break;
  456. }
  457. }
  458. void CSDL_Ext::putPixelWithoutRefreshIfInSurf(SDL_Surface *ekran, const int & x, const int & y, const uint8_t & R, const uint8_t & G, const uint8_t & B, uint8_t A)
  459. {
  460. const SDL_Rect & rect = ekran->clip_rect;
  461. if(x >= rect.x && x < rect.w + rect.x
  462. && y >= rect.y && y < rect.h + rect.y)
  463. CSDL_Ext::putPixelWithoutRefresh(ekran, x, y, R, G, B, A);
  464. }
  465. template<typename Functor>
  466. void loopOverPixel(SDL_Surface * surf, const Rect & rect, Functor functor)
  467. {
  468. uint8_t * pixels = static_cast<uint8_t*>(surf->pixels);
  469. tbb::parallel_for(tbb::blocked_range<size_t>(rect.top(), rect.bottom()), [&](const tbb::blocked_range<size_t>& r)
  470. {
  471. for(int yp = r.begin(); yp != r.end(); ++yp)
  472. {
  473. uint8_t * pixel_from = pixels + yp * surf->pitch + rect.left() * surf->format->BytesPerPixel;
  474. uint8_t * pixel_dest = pixels + yp * surf->pitch + rect.right() * surf->format->BytesPerPixel;
  475. for (uint8_t * pixel = pixel_from; pixel < pixel_dest; pixel += surf->format->BytesPerPixel)
  476. {
  477. int r = Channels::px<4>::r.get(pixel);
  478. int g = Channels::px<4>::g.get(pixel);
  479. int b = Channels::px<4>::b.get(pixel);
  480. functor(r, g, b);
  481. Channels::px<4>::r.set(pixel, r);
  482. Channels::px<4>::g.set(pixel, g);
  483. Channels::px<4>::b.set(pixel, b);
  484. }
  485. }
  486. });
  487. }
  488. void CSDL_Ext::convertToGrayscale(SDL_Surface * surf, const Rect & rect )
  489. {
  490. loopOverPixel(surf, rect, [](int &r, int &g, int &b){
  491. int gray = static_cast<int>(0.299 * r + 0.587 * g + 0.114 * b);
  492. r = gray;
  493. g = gray;
  494. b = gray;
  495. });
  496. }
  497. void CSDL_Ext::convertToH2Scheme(SDL_Surface * surf, const Rect & rect )
  498. {
  499. loopOverPixel(surf, rect, [](int &r, int &g, int &b){
  500. double gray = 0.3 * r + 0.59 * g + 0.11 * b;
  501. double factor = 2.0;
  502. //fast approximation instead of colorspace conversion
  503. r = static_cast<int>(gray + (r - gray) * factor);
  504. g = static_cast<int>(gray + (g - gray) * factor);
  505. b = static_cast<int>(gray + (b - gray) * factor);
  506. r = std::clamp(r, 0, 255);
  507. g = std::clamp(g, 0, 255);
  508. b = std::clamp(b, 0, 255);
  509. });
  510. }
  511. void CSDL_Ext::blitSurface(SDL_Surface * src, const Rect & srcRectInput, SDL_Surface * dst, const Point & dstPoint)
  512. {
  513. SDL_Rect srcRect = CSDL_Ext::toSDL(srcRectInput);
  514. SDL_Rect dstRect = CSDL_Ext::toSDL(Rect(dstPoint, srcRectInput.dimensions()));
  515. int result = SDL_UpperBlit(src, &srcRect, dst, &dstRect);
  516. if (result != 0)
  517. logGlobal->error("SDL_UpperBlit failed! %s", SDL_GetError());
  518. }
  519. void CSDL_Ext::blitSurface(SDL_Surface * src, SDL_Surface * dst, const Point & dest)
  520. {
  521. Rect allSurface( Point(0,0), Point(src->w, src->h));
  522. blitSurface(src, allSurface, dst, dest);
  523. }
  524. void CSDL_Ext::fillSurface( SDL_Surface *dst, const SDL_Color & color )
  525. {
  526. Rect allSurface( Point(0,0), Point(dst->w, dst->h));
  527. fillRect(dst, allSurface, color);
  528. }
  529. void CSDL_Ext::fillRect( SDL_Surface *dst, const Rect & dstrect, const SDL_Color & color)
  530. {
  531. SDL_Rect newRect = CSDL_Ext::toSDL(dstrect);
  532. uint32_t sdlColor = SDL_MapRGBA(dst->format, color.r, color.g, color.b, color.a);
  533. SDL_FillRect(dst, &newRect, sdlColor);
  534. }
  535. void CSDL_Ext::fillRectBlended( SDL_Surface *dst, const Rect & dstrect, const SDL_Color & color)
  536. {
  537. SDL_Rect newRect = CSDL_Ext::toSDL(dstrect);
  538. uint32_t sdlColor = SDL_MapRGBA(dst->format, color.r, color.g, color.b, color.a);
  539. SDL_Surface * tmp = SDL_CreateRGBSurface(0, newRect.w, newRect.h, dst->format->BitsPerPixel, dst->format->Rmask, dst->format->Gmask, dst->format->Bmask, dst->format->Amask);
  540. SDL_FillRect(tmp, nullptr, sdlColor);
  541. SDL_BlitSurface(tmp, nullptr, dst, &newRect);
  542. SDL_FreeSurface(tmp);
  543. }
  544. STRONG_INLINE static uint32_t mapColor(SDL_Surface * surface, SDL_Color color)
  545. {
  546. return SDL_MapRGBA(surface->format, color.r, color.g, color.b, color.a);
  547. }
  548. void CSDL_Ext::setColorKey(SDL_Surface * surface, SDL_Color color)
  549. {
  550. uint32_t key = mapColor(surface,color);
  551. SDL_SetColorKey(surface, SDL_TRUE, key);
  552. }
  553. void CSDL_Ext::setDefaultColorKey(SDL_Surface * surface)
  554. {
  555. setColorKey(surface, toSDL(Colors::DEFAULT_KEY_COLOR));
  556. }
  557. void CSDL_Ext::setDefaultColorKeyPresize(SDL_Surface * surface)
  558. {
  559. uint32_t key = mapColor(surface, toSDL(Colors::DEFAULT_KEY_COLOR));
  560. auto & color = surface->format->palette->colors[key];
  561. // set color key only if exactly such color was found
  562. if (color.r == Colors::DEFAULT_KEY_COLOR.r && color.g == Colors::DEFAULT_KEY_COLOR.g && color.b == Colors::DEFAULT_KEY_COLOR.b)
  563. {
  564. SDL_SetColorKey(surface, SDL_TRUE, key);
  565. color.a = SDL_ALPHA_TRANSPARENT;
  566. }
  567. }
  568. void CSDL_Ext::setClipRect(SDL_Surface * src, const Rect & other)
  569. {
  570. SDL_Rect rect = CSDL_Ext::toSDL(other);
  571. SDL_SetClipRect(src, &rect);
  572. }
  573. void CSDL_Ext::getClipRect(SDL_Surface * src, Rect & other)
  574. {
  575. SDL_Rect rect;
  576. SDL_GetClipRect(src, &rect);
  577. other = CSDL_Ext::fromSDL(rect);
  578. }
  579. SDL_Surface* CSDL_Ext::drawOutline(SDL_Surface* sourceSurface, const SDL_Color& color, int thickness)
  580. {
  581. if(thickness < 1)
  582. return nullptr;
  583. SDL_Surface* destSurface = newSurface(Point(sourceSurface->w, sourceSurface->h));
  584. if(SDL_MUSTLOCK(sourceSurface)) SDL_LockSurface(sourceSurface);
  585. if(SDL_MUSTLOCK(destSurface)) SDL_LockSurface(destSurface);
  586. int width = sourceSurface->w;
  587. int height = sourceSurface->h;
  588. // Helper lambda to get alpha
  589. auto getAlpha = [&](int x, int y) -> Uint8 {
  590. if (x < 0 || x >= width || y < 0 || y >= height)
  591. return 0;
  592. Uint32 pixel = *((Uint32*)sourceSurface->pixels + y * width + x);
  593. Uint8 r;
  594. Uint8 g;
  595. Uint8 b;
  596. Uint8 a;
  597. SDL_GetRGBA(pixel, sourceSurface->format, &r, &g, &b, &a);
  598. return a;
  599. };
  600. tbb::parallel_for(tbb::blocked_range<size_t>(0, height), [&](const tbb::blocked_range<size_t>& r)
  601. {
  602. for (int y = r.begin(); y != r.end(); ++y)
  603. {
  604. for (int x = 0; x < width; x++)
  605. {
  606. Uint8 alpha = getAlpha(x, y);
  607. if (alpha != 0)
  608. continue; // Skip opaque or semi-transparent pixels
  609. Uint8 maxNearbyAlpha = 0;
  610. for (int dy = -thickness; dy <= thickness; ++dy)
  611. {
  612. for (int dx = -thickness; dx <= thickness; ++dx)
  613. {
  614. if (dx * dx + dy * dy > thickness * thickness)
  615. continue; // circular area
  616. int nx = x + dx;
  617. int ny = y + dy;
  618. if (nx < 0 || ny < 0 || nx >= width || ny >= height)
  619. continue;
  620. Uint8 neighborAlpha = getAlpha(nx, ny);
  621. if (neighborAlpha > maxNearbyAlpha)
  622. maxNearbyAlpha = neighborAlpha;
  623. }
  624. }
  625. if (maxNearbyAlpha > 0)
  626. {
  627. Uint8 finalAlpha = maxNearbyAlpha - alpha; // alpha is 0 here, so effectively maxNearbyAlpha
  628. Uint32 newPixel = SDL_MapRGBA(destSurface->format, color.r, color.g, color.b, finalAlpha);
  629. *((Uint32*)destSurface->pixels + y * width + x) = newPixel;
  630. }
  631. }
  632. }
  633. });
  634. if(SDL_MUSTLOCK(sourceSurface)) SDL_UnlockSurface(sourceSurface);
  635. if(SDL_MUSTLOCK(destSurface)) SDL_UnlockSurface(destSurface);
  636. return destSurface;
  637. }
  638. void applyAffineTransform(SDL_Surface* src, SDL_Surface* dst, double a, double b, double c, double d, double tx, double ty)
  639. {
  640. // Lock surfaces for direct pixel access
  641. if (SDL_MUSTLOCK(src)) SDL_LockSurface(src);
  642. if (SDL_MUSTLOCK(dst)) SDL_LockSurface(dst);
  643. // Calculate inverse matrix M_inv for mapping dst -> src
  644. double det = a * d - b * c;
  645. if (std::abs(det) < 1e-10)
  646. throw std::runtime_error("Singular transform matrix!");
  647. double invDet = 1.0 / det;
  648. double ia = d * invDet;
  649. double ib = -b * invDet;
  650. double ic = -c * invDet;
  651. double id = a * invDet;
  652. auto srcPixels = (Uint32*)src->pixels;
  653. auto dstPixels = (Uint32*)dst->pixels;
  654. tbb::parallel_for(tbb::blocked_range<size_t>(0, dst->h), [&](const tbb::blocked_range<size_t>& r)
  655. {
  656. // For each pixel in the destination image
  657. for(int y = r.begin(); y != r.end(); ++y)
  658. {
  659. for(int x = 0; x < dst->w; x++)
  660. {
  661. // Map destination pixel (x,y) back to source coordinates (srcX, srcY)
  662. double srcX = ia * (x - tx) + ib * (y - ty);
  663. double srcY = ic * (x - tx) + id * (y - ty);
  664. // Nearest neighbor sampling (can be improved to bilinear)
  665. auto srcXi = static_cast<int>(round(srcX));
  666. auto srcYi = static_cast<int>(round(srcY));
  667. // Check bounds
  668. if (srcXi >= 0 && srcXi < src->w && srcYi >= 0 && srcYi < src->h)
  669. {
  670. Uint32 pixel = srcPixels[srcYi * src->w + srcXi];
  671. dstPixels[y * dst->w + x] = pixel;
  672. }
  673. else
  674. dstPixels[y * dst->w + x] = 0x00000000; // transparent black
  675. }
  676. }
  677. });
  678. if (SDL_MUSTLOCK(src)) SDL_UnlockSurface(src);
  679. if (SDL_MUSTLOCK(dst)) SDL_UnlockSurface(dst);
  680. }
  681. int getLowestNonTransparentY(SDL_Surface* surface)
  682. {
  683. if (SDL_MUSTLOCK(surface)) SDL_LockSurface(surface);
  684. const int w = surface->w;
  685. const int h = surface->h;
  686. const int bpp = surface->format->BytesPerPixel;
  687. auto pixels = static_cast<Uint8*>(surface->pixels);
  688. // Use parallel_reduce to find the max y with non-transparent pixel
  689. int lowestY = tbb::parallel_reduce(
  690. tbb::blocked_range<int>(0, h),
  691. -1, // initial lowestY = -1 (fully transparent)
  692. [&](const tbb::blocked_range<int>& r, int localMaxY) -> int
  693. {
  694. for (int y = r.begin(); y != r.end(); ++y)
  695. {
  696. Uint8* row = pixels + y * surface->pitch;
  697. for (int x = 0; x < w; ++x)
  698. {
  699. Uint32 pixel = *(Uint32*)(row + x * bpp);
  700. Uint8 a = (pixel >> 24) & 0xFF; // Fast path for ARGB8888
  701. if (a > 0)
  702. {
  703. localMaxY = std::max(localMaxY, y);
  704. break; // no need to scan rest of row
  705. }
  706. }
  707. }
  708. return localMaxY;
  709. },
  710. [](int a, int b) -> int
  711. {
  712. return std::max(a, b);
  713. }
  714. );
  715. if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface);
  716. return lowestY;
  717. }
  718. void fillAlphaPixelWithRGBA(SDL_Surface* surface, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
  719. {
  720. if (SDL_MUSTLOCK(surface)) SDL_LockSurface(surface);
  721. auto pixels = (Uint32*)surface->pixels;
  722. int pixelCount = surface->w * surface->h;
  723. tbb::parallel_for(tbb::blocked_range<size_t>(0, pixelCount), [&](const tbb::blocked_range<size_t>& range)
  724. {
  725. for(int i = range.begin(); i != range.end(); ++i)
  726. {
  727. Uint32 pixel = pixels[i];
  728. Uint8 pr;
  729. Uint8 pg;
  730. Uint8 pb;
  731. Uint8 pa;
  732. // Extract existing RGBA components using SDL_GetRGBA
  733. SDL_GetRGBA(pixel, surface->format, &pr, &pg, &pb, &pa);
  734. Uint32 newPixel = SDL_MapRGBA(surface->format, r, g, b, a);
  735. if(pa < 128)
  736. newPixel = SDL_MapRGBA(surface->format, 0, 0, 0, 0);
  737. pixels[i] = newPixel;
  738. }
  739. });
  740. if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface);
  741. }
  742. void boxBlur(SDL_Surface* surface)
  743. {
  744. if (SDL_MUSTLOCK(surface)) SDL_LockSurface(surface);
  745. int width = surface->w;
  746. int height = surface->h;
  747. int pixelCount = width * height;
  748. Uint32* pixels = static_cast<Uint32*>(surface->pixels);
  749. std::vector<Uint32> temp(pixelCount);
  750. tbb::parallel_for(0, height, [&](int y)
  751. {
  752. for (int x = 0; x < width; ++x)
  753. {
  754. int sumR = 0;
  755. int sumG = 0;
  756. int sumB = 0;
  757. int sumA = 0;
  758. int count = 0;
  759. for (int ky = -1; ky <= 1; ++ky)
  760. {
  761. int ny = std::clamp(y + ky, 0, height - 1);
  762. for (int kx = -1; kx <= 1; ++kx)
  763. {
  764. int nx = std::clamp(x + kx, 0, width - 1);
  765. Uint32 pixel = pixels[ny * width + nx];
  766. sumA += (pixel >> 24) & 0xFF;
  767. sumR += (pixel >> 16) & 0xFF;
  768. sumG += (pixel >> 8) & 0xFF;
  769. sumB += (pixel >> 0) & 0xFF;
  770. ++count;
  771. }
  772. }
  773. Uint8 a = sumA / count;
  774. Uint8 r = sumR / count;
  775. Uint8 g = sumG / count;
  776. Uint8 b = sumB / count;
  777. temp[y * width + x] = (a << 24) | (r << 16) | (g << 8) | b;
  778. }
  779. });
  780. std::copy(temp.begin(), temp.end(), pixels);
  781. if (SDL_MUSTLOCK(surface)) SDL_UnlockSurface(surface);
  782. }
  783. SDL_Surface * CSDL_Ext::drawShadow(SDL_Surface * sourceSurface, bool doSheer)
  784. {
  785. SDL_Surface *destSurface = newSurface(Point(sourceSurface->w, sourceSurface->h));
  786. double shearX = doSheer ? 0.5 : 0.0;
  787. double scaleY = doSheer ? 0.5 : 0.25;
  788. int lowestSource = getLowestNonTransparentY(sourceSurface);
  789. int lowestTransformed = lowestSource * scaleY;
  790. // Parameters for applyAffineTransform
  791. double a = 1.0;
  792. double b = shearX;
  793. double c = 0.0;
  794. double d = scaleY;
  795. double tx = -shearX * lowestSource;
  796. double ty = lowestSource - lowestTransformed;
  797. applyAffineTransform(sourceSurface, destSurface, a, b, c, d, tx, ty);
  798. fillAlphaPixelWithRGBA(destSurface, 0, 0, 0, 128);
  799. boxBlur(destSurface);
  800. return destSurface;
  801. }