SDL_Extensions.cpp 28 KB

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