Added some m_ prefixes to member variables in GLRenderer and related classes
[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_painter.hpp"
29 #include "video/gl/gl_surface_data.hpp"
30 #include "video/gl/gl_texture.hpp"
31 #include "video/util.hpp"
32
33 #define LIGHTMAP_DIV 5
34
35 #ifdef GL_VERSION_ES_CM_1_0
36 #  define glOrtho glOrthof
37 #endif
38
39 GLRenderer::GLRenderer() :
40   m_window(),
41   m_glcontext(),
42   m_viewport(),
43   m_desktop_size(0, 0),
44   m_fullscreen_active(false)
45 {
46   Renderer::instance_ = this;
47
48   SDL_DisplayMode mode;
49   SDL_GetCurrentDisplayMode(0, &mode);
50   m_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(m_glcontext);
108   SDL_DestroyWindow(m_window);
109 }
110
111 void
112 GLRenderer::do_take_screenshot()
113 {
114   // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it?
115
116   SDL_Surface *shot_surf;
117   // create surface to hold screenshot
118 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
119   shot_surf = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
120 #else
121   shot_surf = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
122 #endif
123   if (!shot_surf) {
124     log_warning << "Could not create RGB Surface to contain screenshot" << std::endl;
125     return;
126   }
127
128   // read pixels into array
129   char* pixels = new char[3 * SCREEN_WIDTH * SCREEN_HEIGHT];
130   if (!pixels) {
131     log_warning << "Could not allocate memory to store screenshot" << std::endl;
132     SDL_FreeSurface(shot_surf);
133     return;
134   }
135   glPixelStorei(GL_PACK_ALIGNMENT, 1);
136   glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
137
138   // copy array line-by-line
139   for (int i = 0; i < SCREEN_HEIGHT; i++) {
140     char* src = pixels + (3 * SCREEN_WIDTH * (SCREEN_HEIGHT - i - 1));
141     if(SDL_MUSTLOCK(shot_surf))
142     {
143       SDL_LockSurface(shot_surf);
144     }
145     char* dst = ((char*)shot_surf->pixels) + i * shot_surf->pitch;
146     memcpy(dst, src, 3 * SCREEN_WIDTH);
147     if(SDL_MUSTLOCK(shot_surf))
148     {
149       SDL_UnlockSurface(shot_surf);
150     }
151   }
152
153   // free array
154   delete[](pixels);
155
156   // save screenshot
157   static const std::string writeDir = PHYSFS_getWriteDir();
158   static const std::string dirSep = PHYSFS_getDirSeparator();
159   static const std::string baseName = "screenshot";
160   static const std::string fileExt = ".bmp";
161   std::string fullFilename;
162   for (int num = 0; num < 1000; num++) {
163     std::ostringstream oss;
164     oss << baseName;
165     oss << std::setw(3) << std::setfill('0') << num;
166     oss << fileExt;
167     std::string fileName = oss.str();
168     fullFilename = writeDir + dirSep + fileName;
169     if (!PHYSFS_exists(fileName.c_str())) {
170       SDL_SaveBMP(shot_surf, fullFilename.c_str());
171       log_debug << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl;
172       SDL_FreeSurface(shot_surf);
173       return;
174     }
175   }
176   log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl;
177   SDL_FreeSurface(shot_surf);
178 }
179
180 void
181 GLRenderer::flip()
182 {
183   assert_gl("drawing");
184   SDL_GL_SwapWindow(m_window);
185 }
186
187 void
188 GLRenderer::resize(int w, int h)
189 {
190   g_config->window_size = Size(w, h);
191
192   apply_config();
193 }
194
195 void
196 GLRenderer::apply_config()
197 {
198   apply_video_mode();
199
200   Size target_size = g_config->use_fullscreen ?
201     ((g_config->fullscreen_size == Size(0, 0)) ? m_desktop_size : g_config->fullscreen_size) :
202     g_config->window_size;
203
204   float pixel_aspect_ratio = 1.0f;
205   if (g_config->aspect_size != Size(0, 0))
206   {
207     pixel_aspect_ratio = calculate_pixel_aspect_ratio(m_desktop_size,
208                                                       g_config->aspect_size);
209   }
210   else if (g_config->use_fullscreen)
211   {
212     pixel_aspect_ratio = calculate_pixel_aspect_ratio(m_desktop_size,
213                                                       target_size);
214   }
215
216   Size max_size(1280, 800);
217   Size min_size(640, 480);
218
219   Vector scale;
220   Size logical_size;
221   calculate_viewport(min_size, max_size, target_size,
222                      pixel_aspect_ratio,
223                      g_config->magnification,
224                      scale,
225                      logical_size,
226                      m_viewport);
227
228   SCREEN_WIDTH = logical_size.width;
229   SCREEN_HEIGHT = logical_size.height;
230
231   if (m_viewport.x != 0 || m_viewport.y != 0)
232   {
233     // Clear both buffers so that we get a clean black border without junk
234     glClear(GL_COLOR_BUFFER_BIT);
235     SDL_GL_SwapWindow(m_window);
236     glClear(GL_COLOR_BUFFER_BIT);
237     SDL_GL_SwapWindow(m_window);
238   }
239
240   glViewport(m_viewport.x, m_viewport.y, m_viewport.w, m_viewport.h);
241
242   glMatrixMode(GL_PROJECTION);
243   glLoadIdentity();
244
245   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1);
246
247   glMatrixMode(GL_MODELVIEW);
248   glLoadIdentity();
249   glTranslatef(0, 0, 0);
250   check_gl_error("Setting up view matrices");
251 }
252
253 void
254 GLRenderer::apply_video_mode()
255 {
256   if (m_window)
257   {
258     if (!g_config->use_fullscreen)
259     {
260       SDL_SetWindowFullscreen(m_window, 0);
261     }
262     else
263     {
264       if (g_config->fullscreen_size.width == 0 &&
265           g_config->fullscreen_size.height == 0)
266       {
267         if (SDL_SetWindowFullscreen(m_window, SDL_WINDOW_FULLSCREEN_DESKTOP) != 0)
268         {
269           log_warning << "failed to switch to desktop fullscreen mode: "
270                       << SDL_GetError() << std::endl;
271         }
272         else
273         {
274           log_info << "switched to desktop fullscreen mode" << std::endl;
275         }
276       }
277       else
278       {
279         SDL_DisplayMode mode;
280         mode.format = SDL_PIXELFORMAT_RGB888;
281         mode.w = g_config->fullscreen_size.width;
282         mode.h = g_config->fullscreen_size.height;
283         mode.refresh_rate = g_config->fullscreen_refresh_rate;
284         mode.driverdata = 0;
285
286         if (SDL_SetWindowDisplayMode(m_window, &mode) != 0)
287         {
288           log_warning << "failed to set display mode: "
289                       << mode.w << "x" << mode.h << "@" << mode.refresh_rate << ": "
290                       << SDL_GetError() << std::endl;
291         }
292         else
293         {
294           if (SDL_SetWindowFullscreen(m_window, SDL_WINDOW_FULLSCREEN) != 0)
295           {
296             log_warning << "failed to switch to fullscreen mode: "
297                         << mode.w << "x" << mode.h << "@" << mode.refresh_rate << ": "
298                         << SDL_GetError() << std::endl;
299           }
300           else
301           {
302             log_info << "switched to fullscreen mode: "
303                      << mode.w << "x" << mode.h << "@" << mode.refresh_rate << std::endl;
304           }
305         }
306       }
307     }
308   }
309   else
310   {
311     int flags = SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE;
312     Size size;
313     if (g_config->use_fullscreen)
314     {
315       if (g_config->fullscreen_size == Size(0, 0))
316       {
317         flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
318         size = m_desktop_size;
319       }
320       else
321       {
322         flags |= SDL_WINDOW_FULLSCREEN;
323         size.width  = g_config->fullscreen_size.width;
324         size.height = g_config->fullscreen_size.height;
325       }
326     }
327     else
328     {
329       size = g_config->window_size;
330     }
331
332     m_window = SDL_CreateWindow("SuperTux",
333                               SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
334                               size.width, size.height,
335                               flags);
336     if (!m_window)
337     {
338       std::ostringstream msg;
339       msg << "Couldn't set video mode " << size.width << "x" << size.height << ": " << SDL_GetError();
340       throw std::runtime_error(msg.str());
341     }
342     else
343     {
344       m_glcontext = SDL_GL_CreateContext(m_window);
345
346       SCREEN_WIDTH = size.width;
347       SCREEN_HEIGHT = size.height;
348
349       m_fullscreen_active = g_config->use_fullscreen;
350     }
351   }
352 }
353
354 void
355 GLRenderer::start_draw()
356 {
357 }
358
359 void
360 GLRenderer::end_draw()
361 {
362 }
363
364 void
365 GLRenderer::draw_surface(const DrawingRequest& request)
366 {
367   GLPainter::draw_surface(request);
368 }
369
370 void
371 GLRenderer::draw_surface_part(const DrawingRequest& request)
372 {
373   GLPainter::draw_surface_part(request);
374 }
375
376 void
377 GLRenderer::draw_gradient(const DrawingRequest& request)
378 {
379   GLPainter::draw_gradient(request);
380 }
381
382 void
383 GLRenderer::draw_filled_rect(const DrawingRequest& request)
384 {
385   GLPainter::draw_filled_rect(request);
386 }
387
388 void
389 GLRenderer::draw_inverse_ellipse(const DrawingRequest& request)
390 {
391   GLPainter::draw_inverse_ellipse(request);
392 }
393
394 Vector
395 GLRenderer::to_logical(int physical_x, int physical_y)
396 {
397   return Vector(static_cast<float>(physical_x - m_viewport.x) * SCREEN_WIDTH / m_viewport.w,
398                 static_cast<float>(physical_y - m_viewport.y) * SCREEN_HEIGHT / m_viewport.h);
399 }
400
401 void
402 GLRenderer::set_gamma(float gamma)
403 {
404   Uint16 ramp[256];
405   SDL_CalculateGammaRamp(gamma, ramp);
406   SDL_SetWindowGammaRamp(m_window, ramp, ramp, ramp);
407 }
408
409 /* EOF */