Made WARNING build option usable again
[supertux.git] / src / video / gl / gl_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/gl/gl_renderer.hpp"
19
20 #include <iomanip>
21 #include <iostream>
22 #include <physfs.h>
23 #include "SDL.h"
24
25 #include "supertux/gameconfig.hpp"
26 #include "supertux/globals.hpp"
27 #include "video/drawing_request.hpp"
28 #include "video/gl/gl_surface_data.hpp"
29 #include "video/gl/gl_texture.hpp"
30 #include "video/util.hpp"
31
32 #define LIGHTMAP_DIV 5
33
34 #ifdef GL_VERSION_ES_CM_1_0
35 #  define glOrtho glOrthof
36 #endif
37
38 GLRenderer::GLRenderer() :
39   window(),
40   glcontext(),
41   viewport(),
42   desktop_size(0, 0),
43   fullscreen_active(false),
44   last_texture(static_cast<GLuint> (-1))
45 {
46   Renderer::instance_ = this;
47
48   SDL_DisplayMode mode;
49   SDL_GetCurrentDisplayMode(0, &mode);
50   desktop_size = Size(mode.w, mode.h);
51
52   if(texture_manager != 0)
53     texture_manager->save_textures();
54
55   if(g_config->try_vsync) {
56     /* we want vsync for smooth scrolling */
57     if (SDL_GL_SetSwapInterval(-1) != 0)
58     {
59       log_info << "no support for late swap tearing vsync: " << SDL_GetError() << std::endl;
60       if (SDL_GL_SetSwapInterval(1))
61       {
62         log_info << "no support for vsync: " << SDL_GetError() << std::endl;
63       }
64     }
65   }
66
67   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
68
69   SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   5);
70   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
71   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  5);
72
73   apply_video_mode();
74
75   // setup opengl state and transform
76   glDisable(GL_DEPTH_TEST);
77   glDisable(GL_CULL_FACE);
78   glEnable(GL_TEXTURE_2D);
79   glEnable(GL_BLEND);
80   glEnableClientState(GL_VERTEX_ARRAY);
81   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
82   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
83
84   // Init the projection matrix, viewport and stuff
85   apply_config();
86
87   if(texture_manager == 0)
88     texture_manager = new TextureManager();
89   else
90     texture_manager->reload_textures();
91
92 #ifndef GL_VERSION_ES_CM_1_0
93   GLenum err = glewInit();
94   if (GLEW_OK != err)
95   {
96     std::ostringstream out;
97     out << "GLRenderer: " << glewGetErrorString(err);
98     throw std::runtime_error(out.str());
99   }
100   log_info << "Using GLEW " << glewGetString(GLEW_VERSION) << std::endl;
101   log_info << "GLEW_ARB_texture_non_power_of_two: " << static_cast<int>(GLEW_ARB_texture_non_power_of_two) << std::endl;
102 #endif
103 }
104
105 GLRenderer::~GLRenderer()
106 {
107   SDL_GL_DeleteContext(glcontext);
108   SDL_DestroyWindow(window);
109 }
110
111 void
112 GLRenderer::draw_surface(const DrawingRequest& request)
113 {
114   const Surface* surface = (const Surface*) request.request_data;
115   if(surface == NULL)
116   {
117     return;
118   }
119   GLTexture* gltexture = static_cast<GLTexture*>(surface->get_texture().get());
120   if(gltexture == NULL)
121   {
122     return;
123   }
124   GLSurfaceData *surface_data = static_cast<GLSurfaceData*>(surface->get_surface_data());
125   if(surface_data == NULL)
126   {
127     return;
128   }
129
130   GLuint th = gltexture->get_handle();
131   if (th != last_texture) {
132     last_texture = th;
133     glBindTexture(GL_TEXTURE_2D, th);
134   }
135   intern_draw(request.pos.x, request.pos.y,
136               request.pos.x + surface->get_width(),
137               request.pos.y + surface->get_height(),
138               surface_data->get_uv_left(),
139               surface_data->get_uv_top(),
140               surface_data->get_uv_right(),
141               surface_data->get_uv_bottom(),
142               request.angle,
143               request.alpha,
144               request.color,
145               request.blend,
146               request.drawing_effect);
147 }
148
149 void
150 GLRenderer::draw_surface_part(const DrawingRequest& request)
151 {
152   const SurfacePartRequest* surfacepartrequest
153     = (SurfacePartRequest*) request.request_data;
154   const Surface* surface = surfacepartrequest->surface;
155   boost::shared_ptr<GLTexture> gltexture = boost::dynamic_pointer_cast<GLTexture>(surface->get_texture());
156   GLSurfaceData *surface_data = reinterpret_cast<GLSurfaceData *>(surface->get_surface_data());
157
158   float uv_width = surface_data->get_uv_right() - surface_data->get_uv_left();
159   float uv_height = surface_data->get_uv_bottom() - surface_data->get_uv_top();
160
161   float uv_left = surface_data->get_uv_left() + (uv_width * surfacepartrequest->source.x) / surface->get_width();
162   float uv_top = surface_data->get_uv_top() + (uv_height * surfacepartrequest->source.y) / surface->get_height();
163   float uv_right = surface_data->get_uv_left() + (uv_width * (surfacepartrequest->source.x + surfacepartrequest->size.x)) / surface->get_width();
164   float uv_bottom = surface_data->get_uv_top() + (uv_height * (surfacepartrequest->source.y + surfacepartrequest->size.y)) / surface->get_height();
165
166   GLuint th = gltexture->get_handle();
167   if (th != last_texture) {
168     last_texture = th;
169     glBindTexture(GL_TEXTURE_2D, th);
170   }
171   intern_draw(request.pos.x, request.pos.y,
172               request.pos.x + surfacepartrequest->size.x,
173               request.pos.y + surfacepartrequest->size.y,
174               uv_left,
175               uv_top,
176               uv_right,
177               uv_bottom,
178               0.0,
179               request.alpha,
180               request.color,
181               Blend(),
182               request.drawing_effect);
183 }
184
185 void
186 GLRenderer::draw_gradient(const DrawingRequest& request)
187 {
188   const GradientRequest* gradientrequest
189     = (GradientRequest*) request.request_data;
190   const Color& top = gradientrequest->top;
191   const Color& bottom = gradientrequest->bottom;
192
193   glDisable(GL_TEXTURE_2D);
194   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
195   glEnableClientState(GL_COLOR_ARRAY);
196
197   float vertices[] = {
198     0, 0,
199     float(SCREEN_WIDTH), 0,
200     float(SCREEN_WIDTH), float(SCREEN_HEIGHT),
201     0, float(SCREEN_HEIGHT)
202   };
203   glVertexPointer(2, GL_FLOAT, 0, vertices);
204
205   float colors[] = {
206     top.red, top.green, top.blue, top.alpha,
207     top.red, top.green, top.blue, top.alpha,
208     bottom.red, bottom.green, bottom.blue, bottom.alpha,
209     bottom.red, bottom.green, bottom.blue, bottom.alpha,
210   };
211   glColorPointer(4, GL_FLOAT, 0, colors);
212
213   glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
214
215   glDisableClientState(GL_COLOR_ARRAY);
216   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
217
218   glEnable(GL_TEXTURE_2D);
219   glColor4f(1, 1, 1, 1);
220 }
221
222 void
223 GLRenderer::draw_filled_rect(const DrawingRequest& request)
224 {
225   const FillRectRequest* fillrectrequest
226     = (FillRectRequest*) request.request_data;
227
228   glDisable(GL_TEXTURE_2D);
229   glColor4f(fillrectrequest->color.red, fillrectrequest->color.green,
230             fillrectrequest->color.blue, fillrectrequest->color.alpha);
231   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
232
233   if (fillrectrequest->radius != 0.0f)
234   {
235     // draw round rect
236     // Keep radius in the limits, so that we get a circle instead of
237     // just graphic junk
238     float radius = std::min(fillrectrequest->radius,
239                             std::min(fillrectrequest->size.x/2,
240                                      fillrectrequest->size.y/2));
241
242     // inner rectangle
243     Rectf irect(request.pos.x    + radius,
244                 request.pos.y    + radius,
245                 request.pos.x + fillrectrequest->size.x - radius,
246                 request.pos.y + fillrectrequest->size.y - radius);
247
248     int n = 8;
249     int p = 0;
250     std::vector<float> vertices((n+1) * 4 * 2);
251
252     for(int i = 0; i <= n; ++i)
253     {
254       float x = sinf(i * (M_PI/2) / n) * radius;
255       float y = cosf(i * (M_PI/2) / n) * radius;
256
257       vertices[p++] = irect.get_left() - x;
258       vertices[p++] = irect.get_top()  - y;
259
260       vertices[p++] = irect.get_right() + x;
261       vertices[p++] = irect.get_top()   - y;
262     }
263
264     for(int i = 0; i <= n; ++i)
265     {
266       float x = cosf(i * (M_PI/2) / n) * radius;
267       float y = sinf(i * (M_PI/2) / n) * radius;
268
269       vertices[p++] = irect.get_left()   - x;
270       vertices[p++] = irect.get_bottom() + y;
271
272       vertices[p++] = irect.get_right()  + x;
273       vertices[p++] = irect.get_bottom() + y;
274     }
275
276     glVertexPointer(2, GL_FLOAT, 0, &*vertices.begin());
277     glDrawArrays(GL_TRIANGLE_STRIP, 0,  vertices.size()/2);
278   }
279   else
280   {
281     float x = request.pos.x;
282     float y = request.pos.y;
283     float w = fillrectrequest->size.x;
284     float h = fillrectrequest->size.y;
285
286     float vertices[] = {
287       x,   y,
288       x+w, y,
289       x+w, y+h,
290       x,   y+h
291     };
292     glVertexPointer(2, GL_FLOAT, 0, vertices);
293
294     glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
295   }
296
297   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
298   glEnable(GL_TEXTURE_2D);
299   glColor4f(1, 1, 1, 1);
300 }
301
302 void
303 GLRenderer::draw_inverse_ellipse(const DrawingRequest& request)
304 {
305   const InverseEllipseRequest* ellipse = (InverseEllipseRequest*)request.request_data;
306
307   glDisable(GL_TEXTURE_2D);
308   glColor4f(ellipse->color.red,  ellipse->color.green,
309             ellipse->color.blue, ellipse->color.alpha);
310
311   float x = request.pos.x;
312   float y = request.pos.y;
313   float w = ellipse->size.x/2.0f;
314   float h = ellipse->size.y/2.0f;
315
316   static const int slices = 16;
317   static const int points = (slices+1) * 12;
318
319   float vertices[points * 2];
320   int   p = 0;
321
322   // Bottom
323   vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
324   vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
325   vertices[p++] = x;            vertices[p++] = y+h;
326
327   // Top
328   vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
329   vertices[p++] = 0;            vertices[p++] = 0;
330   vertices[p++] = x;            vertices[p++] = y-h;
331
332   // Left
333   vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
334   vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
335   vertices[p++] = x+w;          vertices[p++] = y;
336
337   // Right
338   vertices[p++] = 0;            vertices[p++] = 0;
339   vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
340   vertices[p++] = x-w;          vertices[p++] = y;
341
342   for(int i = 0; i < slices; ++i)
343   {
344     float ex1 = sinf(M_PI/2 / slices * i) * w;
345     float ey1 = cosf(M_PI/2 / slices * i) * h;
346
347     float ex2 = sinf(M_PI/2 / slices * (i+1)) * w;
348     float ey2 = cosf(M_PI/2 / slices * (i+1)) * h;
349
350     // Bottom/Right
351     vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
352     vertices[p++] = x + ex1;      vertices[p++] = y + ey1;
353     vertices[p++] = x + ex2;      vertices[p++] = y + ey2;
354
355     // Top/Left
356     vertices[p++] = 0;            vertices[p++] = 0;
357     vertices[p++] = x - ex1;      vertices[p++] = y - ey1;
358     vertices[p++] = x - ex2;      vertices[p++] = y - ey2;
359
360     // Top/Right
361     vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
362     vertices[p++] = x + ex1;      vertices[p++] = y - ey1;
363     vertices[p++] = x + ex2;      vertices[p++] = y - ey2;
364
365     // Bottom/Left
366     vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
367     vertices[p++] = x - ex1;      vertices[p++] = y + ey1;
368     vertices[p++] = x - ex2;      vertices[p++] = y + ey2;
369   }
370
371   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
372   glVertexPointer(2, GL_FLOAT, 0, vertices);
373
374   glDrawArrays(GL_TRIANGLES, 0, points);
375
376   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
377
378   glEnable(GL_TEXTURE_2D);
379   glColor4f(1, 1, 1, 1);
380 }
381
382 void
383 GLRenderer::do_take_screenshot()
384 {
385   // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it?
386
387   SDL_Surface *shot_surf;
388   // create surface to hold screenshot
389 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
390   shot_surf = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
391 #else
392   shot_surf = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
393 #endif
394   if (!shot_surf) {
395     log_warning << "Could not create RGB Surface to contain screenshot" << std::endl;
396     return;
397   }
398
399   // read pixels into array
400   char* pixels = new char[3 * SCREEN_WIDTH * SCREEN_HEIGHT];
401   if (!pixels) {
402     log_warning << "Could not allocate memory to store screenshot" << std::endl;
403     SDL_FreeSurface(shot_surf);
404     return;
405   }
406   glPixelStorei(GL_PACK_ALIGNMENT, 1);
407   glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
408
409   // copy array line-by-line
410   for (int i = 0; i < SCREEN_HEIGHT; i++) {
411     char* src = pixels + (3 * SCREEN_WIDTH * (SCREEN_HEIGHT - i - 1));
412     if(SDL_MUSTLOCK(shot_surf))
413     {
414       SDL_LockSurface(shot_surf);
415     }
416     char* dst = ((char*)shot_surf->pixels) + i * shot_surf->pitch;
417     memcpy(dst, src, 3 * SCREEN_WIDTH);
418     if(SDL_MUSTLOCK(shot_surf))
419     {
420       SDL_UnlockSurface(shot_surf);
421     }
422   }
423
424   // free array
425   delete[](pixels);
426
427   // save screenshot
428   static const std::string writeDir = PHYSFS_getWriteDir();
429   static const std::string dirSep = PHYSFS_getDirSeparator();
430   static const std::string baseName = "screenshot";
431   static const std::string fileExt = ".bmp";
432   std::string fullFilename;
433   for (int num = 0; num < 1000; num++) {
434     std::ostringstream oss;
435     oss << baseName;
436     oss << std::setw(3) << std::setfill('0') << num;
437     oss << fileExt;
438     std::string fileName = oss.str();
439     fullFilename = writeDir + dirSep + fileName;
440     if (!PHYSFS_exists(fileName.c_str())) {
441       SDL_SaveBMP(shot_surf, fullFilename.c_str());
442       log_debug << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl;
443       SDL_FreeSurface(shot_surf);
444       return;
445     }
446   }
447   log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl;
448   SDL_FreeSurface(shot_surf);
449 }
450
451 void
452 GLRenderer::flip()
453 {
454   assert_gl("drawing");
455   SDL_GL_SwapWindow(window);
456 }
457
458 void
459 GLRenderer::resize(int w, int h)
460 {
461   g_config->window_size = Size(w, h);
462
463   apply_config();
464 }
465
466 void
467 GLRenderer::apply_config()
468 {
469   apply_video_mode();
470
471   Size target_size = g_config->use_fullscreen ?
472     ((g_config->fullscreen_size == Size(0, 0)) ? desktop_size : g_config->fullscreen_size) :
473     g_config->window_size;
474
475   float pixel_aspect_ratio = 1.0f;
476   if (g_config->aspect_size != Size(0, 0))
477   {
478     pixel_aspect_ratio = calculate_pixel_aspect_ratio(desktop_size,
479                                                       g_config->aspect_size);
480   }
481   else if (g_config->use_fullscreen)
482   {
483     pixel_aspect_ratio = calculate_pixel_aspect_ratio(desktop_size,
484                                                       target_size);
485   }
486
487   Size max_size(1280, 800);
488   Size min_size(640, 480);
489
490   Vector scale;
491   Size logical_size;
492   calculate_viewport(min_size, max_size, target_size,
493                      pixel_aspect_ratio,
494                      g_config->magnification,
495                      scale,
496                      logical_size,
497                      viewport);
498
499   SCREEN_WIDTH = logical_size.width;
500   SCREEN_HEIGHT = logical_size.height;
501
502   if (viewport.x != 0 || viewport.y != 0)
503   {
504     // Clear both buffers so that we get a clean black border without junk
505     glClear(GL_COLOR_BUFFER_BIT);
506     SDL_GL_SwapWindow(window);
507     glClear(GL_COLOR_BUFFER_BIT);
508     SDL_GL_SwapWindow(window);
509   }
510
511   glViewport(viewport.x, viewport.y, viewport.w, viewport.h);
512
513   glMatrixMode(GL_PROJECTION);
514   glLoadIdentity();
515
516   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1);
517
518   glMatrixMode(GL_MODELVIEW);
519   glLoadIdentity();
520   glTranslatef(0, 0, 0);
521   check_gl_error("Setting up view matrices");
522 }
523
524 void
525 GLRenderer::apply_video_mode()
526 {
527   if (window)
528   {
529     if (!g_config->use_fullscreen)
530     {
531       SDL_SetWindowFullscreen(window, 0);
532     }
533     else
534     {
535       if (g_config->fullscreen_size.width == 0 &&
536           g_config->fullscreen_size.height == 0)
537       {
538         if (SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP) != 0)
539         {
540           log_warning << "failed to switch to desktop fullscreen mode: "
541                       << SDL_GetError() << std::endl;
542         }
543         else
544         {
545           log_info << "switched to desktop fullscreen mode" << std::endl;
546         }
547       }
548       else
549       {
550         SDL_DisplayMode mode;
551         mode.format = SDL_PIXELFORMAT_RGB888;
552         mode.w = g_config->fullscreen_size.width;
553         mode.h = g_config->fullscreen_size.height;
554         mode.refresh_rate = g_config->fullscreen_refresh_rate;
555         mode.driverdata = 0;
556
557         if (SDL_SetWindowDisplayMode(window, &mode) != 0)
558         {
559           log_warning << "failed to set display mode: "
560                       << mode.w << "x" << mode.h << "@" << mode.refresh_rate << ": "
561                       << SDL_GetError() << std::endl;
562         }
563         else
564         {
565           if (SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN) != 0)
566           {
567             log_warning << "failed to switch to fullscreen mode: "
568                         << mode.w << "x" << mode.h << "@" << mode.refresh_rate << ": "
569                         << SDL_GetError() << std::endl;
570           }
571           else
572           {
573             log_info << "switched to fullscreen mode: "
574                      << mode.w << "x" << mode.h << "@" << mode.refresh_rate << std::endl;
575           }
576         }
577       }
578     }
579   }
580   else
581   {
582     int flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
583     Size size;
584     if (g_config->use_fullscreen)
585     {
586       if (g_config->fullscreen_size == Size(0, 0))
587       {
588         flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
589         size = desktop_size;
590       }
591       else
592       {
593         flags |= SDL_WINDOW_FULLSCREEN;
594         size.width  = g_config->fullscreen_size.width;
595         size.height = g_config->fullscreen_size.height;
596       }
597     }
598     else
599     {
600       size = g_config->window_size;
601     }
602
603     window = SDL_CreateWindow("SuperTux",
604                               SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
605                               size.width, size.height,
606                               flags);
607     if (!window)
608     {
609       std::ostringstream msg;
610       msg << "Couldn't set video mode " << size.width << "x" << size.height << ": " << SDL_GetError();
611       throw std::runtime_error(msg.str());
612     }
613     else
614     {
615       glcontext = SDL_GL_CreateContext(window);
616
617       SCREEN_WIDTH = size.width;
618       SCREEN_HEIGHT = size.height;
619
620       fullscreen_active = g_config->use_fullscreen;
621     }
622   }
623 }
624
625 Vector
626 GLRenderer::to_logical(int physical_x, int physical_y)
627 {
628   return Vector(static_cast<float>(physical_x - viewport.x) * SCREEN_WIDTH / viewport.w,
629                 static_cast<float>(physical_y - viewport.y) * SCREEN_HEIGHT / viewport.h);
630 }
631
632 void
633 GLRenderer::set_gamma(float gamma)
634 {
635   Uint16 ramp[256];
636   SDL_CalculateGammaRamp(gamma, ramp);
637   SDL_SetWindowGammaRamp(window, ramp, ramp, ramp);
638 }
639
640 /* EOF */