More fixes, SetAlpha problems remaining
[supertux.git] / src / video / sdl / sdl_renderer.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //      Updated by GiBy 2013 for SDL2 <giby_the_kid@yahoo.fr>
4 //
5 //  This program is free software: you can redistribute it and/or modify
6 //  it under the terms of the GNU General Public License as published by
7 //  the Free Software Foundation, either version 3 of the License, or
8 //  (at your option) any later version.
9 //
10 //  This program is distributed in the hope that it will be useful,
11 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 //  GNU General Public License for more details.
14 //
15 //  You should have received a copy of the GNU General Public License
16 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 #include "video/sdl/sdl_renderer.hpp"
19
20 #include "video/drawing_request.hpp"
21 #include "video/sdl/sdl_surface_data.hpp"
22 #include "video/sdl/sdl_texture.hpp"
23
24 #include <iomanip>
25 #include <iostream>
26 #include <physfs.h>
27 #include <sstream>
28 #include <stdexcept>
29 #include "SDL2/SDL_video.h"
30 //#include "SDL/SDL.h"
31 //#include "SDL/SDL_opengl.h"
32
33
34 namespace {
35
36 SDL_Surface *apply_alpha(SDL_Surface *src, float alpha_factor)
37 {
38   // FIXME: This is really slow
39   assert(src->format->Amask);
40   int alpha = (int) (alpha_factor * 256);
41   SDL_Surface *dst = SDL_CreateRGBSurface(src->flags, src->w, src->h, src->format->BitsPerPixel, src->format->Rmask,  src->format->Gmask, src->format->Bmask, src->format->Amask);
42   int bpp = dst->format->BytesPerPixel;
43   if(SDL_MUSTLOCK(src))
44   {
45     SDL_LockSurface(src);
46   }
47   if(SDL_MUSTLOCK(dst))
48   {
49     SDL_LockSurface(dst);
50   }
51   for(int y = 0;y < dst->h;y++) {
52     for(int x = 0;x < dst->w;x++) {
53       Uint8 *srcpixel = (Uint8 *) src->pixels + y * src->pitch + x * bpp;
54       Uint8 *dstpixel = (Uint8 *) dst->pixels + y * dst->pitch + x * bpp;
55       Uint32 mapped = 0;
56       switch(bpp) {
57         case 1:
58           mapped = *srcpixel;
59           break;
60         case 2:
61           mapped = *(Uint16 *)srcpixel;
62           break;
63         case 3:
64 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
65           mapped |= srcpixel[0] << 16;
66           mapped |= srcpixel[1] << 8;
67           mapped |= srcpixel[2] << 0;
68 #else
69           mapped |= srcpixel[0] << 0;
70           mapped |= srcpixel[1] << 8;
71           mapped |= srcpixel[2] << 16;
72 #endif
73           break;
74         case 4:
75           mapped = *(Uint32 *)srcpixel;
76           break;
77       }
78       Uint8 r, g, b, a;
79       SDL_GetRGBA(mapped, src->format, &r, &g, &b, &a);
80       mapped = SDL_MapRGBA(dst->format, r, g, b, (a * alpha) >> 8);
81       switch(bpp) {
82         case 1:
83           *dstpixel = mapped;
84           break;
85         case 2:
86           *(Uint16 *)dstpixel = mapped;
87           break;
88         case 3:
89 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
90           dstpixel[0] = (mapped >> 16) & 0xff;
91           dstpixel[1] = (mapped >> 8) & 0xff;
92           dstpixel[2] = (mapped >> 0) & 0xff;
93 #else
94           dstpixel[0] = (mapped >> 0) & 0xff;
95           dstpixel[1] = (mapped >> 8) & 0xff;
96           dstpixel[2] = (mapped >> 16) & 0xff;
97 #endif
98           break;
99         case 4:
100           *(Uint32 *)dstpixel = mapped;
101           break;
102       }
103     }
104   }
105   if(SDL_MUSTLOCK(dst))
106   {
107     SDL_UnlockSurface(dst);
108   }
109   if(SDL_MUSTLOCK(src))
110   {
111     SDL_UnlockSurface(src);
112   }
113   return dst;
114 }
115
116 } // namespace
117
118 SDLRenderer::SDLRenderer() :
119   screen(),
120   numerator(),
121   denominator()
122 {
123   Renderer::instance_ = this;
124
125   // Cannot currently find a way to do this with SDL2
126   //const SDL_VideoInfo *info = SDL_GetVideoInfo();
127   //log_info << "Hardware surfaces are " << (info->hw_available ? "" : "not ") << "available." << std::endl;
128   //log_info << "Hardware to hardware blits are " << (info->blit_hw ? "" : "not ") << "accelerated." << std::endl;
129   //log_info << "Hardware to hardware blits with colorkey are " << (info->blit_hw_CC ? "" : "not ") << "accelerated." << std::endl;
130   //log_info << "Hardware to hardware blits with alpha are " << (info->blit_hw_A ? "" : "not ") << "accelerated." << std::endl;
131   //log_info << "Software to hardware blits are " << (info->blit_sw ? "" : "not ") << "accelerated." << std::endl;
132   //log_info << "Software to hardware blits with colorkey are " << (info->blit_sw_CC ? "" : "not ") << "accelerated." << std::endl;
133   //log_info << "Software to hardware blits with alpha are " << (info->blit_sw_A ? "" : "not ") << "accelerated." << std::endl;
134   //log_info << "Color fills are " << (info->blit_fill ? "" : "not ") << "accelerated." << std::endl;
135
136  // int flags = SDL_SWSURFACE | SDL_ANYFORMAT;
137  // if(g_config->use_fullscreen)
138  //   flags |= SDL_FULLSCREEN;
139     
140   int width  = 800; //FIXME: config->screenwidth;
141   int height = 600; //FIXME: config->screenheight;
142         
143         SDL_Init(SDL_INIT_VIDEO);   // Initialize SDL2
144
145   window = SDL_CreateWindow(
146                             "SuperTux",
147                             SDL_WINDOWPOS_UNDEFINED,
148                             SDL_WINDOWPOS_UNDEFINED,
149                             width, height,
150                             SDL_WINDOW_OPENGL );
151           SDL_GLContext glcontext = SDL_GL_CreateContext(window);
152     renderer = SDL_CreateRenderer(window, -1, 0);
153
154         
155   if(window == 0) {
156     std::stringstream msg;
157     msg << "Couldn't set video mode (" << width << "x" << height
158         << "): " << SDL_GetError();
159     throw std::runtime_error(msg.str());
160   }
161
162   numerator   = 1;
163   denominator = 1;
164   /* FIXME: 
165      float xfactor = (float) config->screenwidth / SCREEN_WIDTH;
166      float yfactor = (float) config->screenheight / SCREEN_HEIGHT;
167      if(xfactor < yfactor)
168      {
169      numerator = config->screenwidth;
170      denominator = SCREEN_WIDTH;
171      }
172      else
173      {
174      numerator = config->screenheight;
175      denominator = SCREEN_HEIGHT;
176      }
177   */
178   if(texture_manager == 0)
179     texture_manager = new TextureManager();
180 }
181
182 SDLRenderer::~SDLRenderer()
183 {
184 }
185
186 void
187 SDLRenderer::draw_surface(const DrawingRequest& request)
188 {
189   //FIXME: support parameters request.alpha, request.angle, request.blend
190   const Surface* surface = (const Surface*) request.request_data;
191   boost::shared_ptr<SDLTexture> sdltexture = boost::dynamic_pointer_cast<SDLTexture>(surface->get_texture());
192   SDLSurfaceData *surface_data = reinterpret_cast<SDLSurfaceData *>(surface->get_surface_data());
193
194   DrawingEffect effect = request.drawing_effect;
195   if (surface->get_flipx()) effect = HORIZONTAL_FLIP;
196
197   SDL_Surface *transform = sdltexture->get_transform(request.color, effect);
198
199   // get and check SDL_Surface
200   if (transform == 0) {
201     std::cerr << "Warning: Tried to draw NULL surface, skipped draw" << std::endl;
202     return;
203   }
204
205   SDL_Rect *src_rect = surface_data->get_src_rect(effect);
206   SDL_Rect dst_rect;
207   dst_rect.x = (int) request.pos.x * numerator / denominator;
208   dst_rect.y = (int) request.pos.y * numerator / denominator;
209
210   Uint8 alpha = 0;
211   if(request.alpha != 1.0)
212   {
213     if(!transform->format->Amask)
214     {
215       if(transform->flags & SDL_SRCALPHA)
216       {
217         alpha = transform->format->alpha;
218       }
219       else
220       {
221         alpha = 255;
222       }
223       SDL_SetSurfaceAlphaMod(transform, (Uint8) (request.alpha * alpha));
224     }
225     /*else
226       {
227       transform = apply_alpha(transform, request.alpha);
228       }*/
229   }
230
231   SDL_BlitSurface(transform, src_rect, screen, &dst_rect);
232
233   if(request.alpha != 1.0)
234   {
235     if(!transform->format->Amask)
236     {
237       if(alpha == 255)
238       {
239         SDL_SetAlpha(transform, SDL_RLEACCEL, 0);
240       }
241       else
242       {
243         SDL_SetAlpha(transform, SDL_SRCALPHA | SDL_RLEACCEL, alpha);
244       }
245     }
246     /*else
247       {
248       SDL_FreeSurface(transform);
249       }*/
250   }
251 }
252
253 void
254 SDLRenderer::draw_surface_part(const DrawingRequest& request)
255 {
256   const SurfacePartRequest* surfacepartrequest
257     = (SurfacePartRequest*) request.request_data;
258
259   const Surface* surface = surfacepartrequest->surface;
260   boost::shared_ptr<SDLTexture> sdltexture = boost::dynamic_pointer_cast<SDLTexture>(surface->get_texture());
261
262   DrawingEffect effect = request.drawing_effect;
263   if (surface->get_flipx()) effect = HORIZONTAL_FLIP;
264
265   SDL_Surface *transform = sdltexture->get_transform(request.color, effect);
266
267   // get and check SDL_Surface
268   if (transform == 0) {
269     std::cerr << "Warning: Tried to draw NULL surface, skipped draw" << std::endl;
270     return;
271   }
272
273   int ox, oy;
274   if (effect == HORIZONTAL_FLIP)
275   {
276     ox = sdltexture->get_texture_width() - surface->get_x() - (int) surfacepartrequest->size.x;
277   }
278   else
279   {
280     ox = surface->get_x();
281   }
282   if (effect == VERTICAL_FLIP)
283   {
284     oy = sdltexture->get_texture_height() - surface->get_y() - (int) surfacepartrequest->size.y;
285   }
286   else
287   {
288     oy = surface->get_y();
289   }
290
291   SDL_Rect src_rect;
292   src_rect.x = (ox + (int) surfacepartrequest->source.x) * numerator / denominator;
293   src_rect.y = (oy + (int) surfacepartrequest->source.y) * numerator / denominator;
294   src_rect.w = (int) surfacepartrequest->size.x * numerator / denominator;
295   src_rect.h = (int) surfacepartrequest->size.y * numerator / denominator;
296
297   SDL_Rect dst_rect;
298   dst_rect.x = (int) request.pos.x * numerator / denominator;
299   dst_rect.y = (int) request.pos.y * numerator / denominator;
300
301   Uint8 alpha = 0;
302   if(request.alpha != 1.0)
303   {
304     if(!transform->format->Amask)
305     {
306       if(transform->flags & SDL_SRCALPHA)
307       {
308         alpha = transform->format->alpha;
309       }
310       else
311       {
312         alpha = 255;
313       }
314       SDL_SetAlpha(transform, SDL_SRCALPHA, (Uint8) (request.alpha * alpha));
315     }
316     /*else
317       {
318       transform = apply_alpha(transform, request.alpha);
319       }*/
320   }
321
322   SDL_BlitSurface(transform, &src_rect, screen, &dst_rect);
323
324   if(request.alpha != 1.0)
325   {
326     if(!transform->format->Amask)
327     {
328       if(alpha == 255)
329       {
330         SDL_SetAlpha(transform, SDL_RLEACCEL, 0);
331       }
332       else
333       {
334         SDL_SetAlpha(transform, SDL_SRCALPHA | SDL_RLEACCEL, alpha);
335       }
336     }
337     /*else
338       {
339       SDL_FreeSurface(transform);
340       }*/
341   }
342 }
343
344 void
345 SDLRenderer::draw_gradient(const DrawingRequest& request)
346 {
347   const GradientRequest* gradientrequest 
348     = (GradientRequest*) request.request_data;
349   const Color& top = gradientrequest->top;
350   const Color& bottom = gradientrequest->bottom;
351
352   for(int y = 0;y < screen->h;++y)
353   {
354     Uint8 r = (Uint8)((((float)(top.red-bottom.red)/(0-screen->h)) * y + top.red) * 255);
355     Uint8 g = (Uint8)((((float)(top.green-bottom.green)/(0-screen->h)) * y + top.green) * 255);
356     Uint8 b = (Uint8)((((float)(top.blue-bottom.blue)/(0-screen->h)) * y + top.blue) * 255);
357     Uint8 a = (Uint8)((((float)(top.alpha-bottom.alpha)/(0-screen->h)) * y + top.alpha) * 255);
358     Uint32 color = SDL_MapRGB(screen->format, r, g, b);
359
360     SDL_Rect rect;
361     rect.x = 0;
362     rect.y = y;
363     rect.w = screen->w;
364     rect.h = 1;
365
366     if(a == SDL_ALPHA_OPAQUE) {
367       SDL_FillRect(screen, &rect, color);
368     } else if(a != SDL_ALPHA_TRANSPARENT) {
369       SDL_Surface *temp = SDL_CreateRGBSurface(screen->flags, rect.w, rect.h, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask);
370
371       SDL_FillRect(temp, 0, color);
372       SDL_SetAlpha(temp, SDL_SRCALPHA | SDL_RLEACCEL, a);
373       SDL_BlitSurface(temp, 0, screen, &rect);
374       SDL_FreeSurface(temp);
375     }
376   }
377 }
378
379 void
380 SDLRenderer::draw_filled_rect(const DrawingRequest& request)
381 {
382   const FillRectRequest* fillrectrequest
383     = (FillRectRequest*) request.request_data;
384
385   SDL_Rect rect;
386   rect.x = (Sint16)request.pos.x * screen->w / SCREEN_WIDTH;
387   rect.y = (Sint16)request.pos.y * screen->h / SCREEN_HEIGHT;
388   rect.w = (Uint16)fillrectrequest->size.x * screen->w / SCREEN_WIDTH;
389   rect.h = (Uint16)fillrectrequest->size.y * screen->h / SCREEN_HEIGHT;
390   if((rect.w == 0) || (rect.h == 0)) {
391     return;
392   }
393   Uint8 r = static_cast<Uint8>(fillrectrequest->color.red * 255);
394   Uint8 g = static_cast<Uint8>(fillrectrequest->color.green * 255);
395   Uint8 b = static_cast<Uint8>(fillrectrequest->color.blue * 255);
396   Uint8 a = static_cast<Uint8>(fillrectrequest->color.alpha * 255);
397   Uint32 color = SDL_MapRGB(screen->format, r, g, b);
398   if(a == SDL_ALPHA_OPAQUE) {
399     SDL_FillRect(screen, &rect, color);
400   } else if(a != SDL_ALPHA_TRANSPARENT) {
401     SDL_Surface *temp = SDL_CreateRGBSurface(screen->flags, rect.w, rect.h, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask);
402
403     SDL_FillRect(temp, 0, color);
404     SDL_SetAlpha(temp, SDL_SRCALPHA | SDL_RLEACCEL, a);
405     SDL_BlitSurface(temp, 0, screen, &rect);
406     SDL_FreeSurface(temp);
407   }
408 }
409
410 void
411 SDLRenderer::draw_inverse_ellipse(const DrawingRequest&)
412 {
413 }
414
415 void 
416 SDLRenderer::do_take_screenshot()
417 {
418   // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it?
419
420   SDL_Surface *screen = SDL_GetWindowSurface(window);
421
422   // save screenshot
423   static const std::string writeDir = PHYSFS_getWriteDir();
424   static const std::string dirSep = PHYSFS_getDirSeparator();
425   static const std::string baseName = "screenshot";
426   static const std::string fileExt = ".bmp";
427   std::string fullFilename;
428   for (int num = 0; num < 1000; num++) {
429     std::ostringstream oss;
430     oss << baseName;
431     oss << std::setw(3) << std::setfill('0') << num;
432     oss << fileExt;
433     std::string fileName = oss.str();
434     fullFilename = writeDir + dirSep + fileName;
435     if (!PHYSFS_exists(fileName.c_str())) {
436       SDL_SaveBMP(screen, fullFilename.c_str());
437       log_debug << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl;
438       return;
439     }
440   }
441   log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl;
442 }
443
444 void
445 SDLRenderer::flip()
446 {
447   SDL_RenderPresent(renderer);
448 }
449
450 void
451 SDLRenderer::resize(int, int)
452 {
453     
454 }
455
456 /* EOF */