264278885399a3e39fbe738c505296145fd3f5d0
[supertux.git] / src / video / gl / gl_renderer.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include "video/gl/gl_renderer.hpp"
18
19 #include <iomanip>
20 #include <iostream>
21 #include <physfs.h>
22
23 #include "supertux/gameconfig.hpp"
24 #include "supertux/globals.hpp"
25 #include "video/drawing_request.hpp"
26 #include "video/gl/gl_surface_data.hpp"
27 #include "video/gl/gl_texture.hpp"
28 #define LIGHTMAP_DIV 5
29
30 #ifdef GL_VERSION_ES_CM_1_0
31 #  define glOrtho glOrthof
32 #endif
33
34 GLRenderer::GLRenderer() :
35   desktop_size(-1, -1),
36   screen_size(-1, -1),
37   fullscreen_active(false)
38 {
39   Renderer::instance_ = this;
40
41 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
42   // unfortunately only newer SDLs have these infos.
43   // This must be called before SDL_SetVideoMode() or it will return
44   // the window size instead of the desktop size.
45   const SDL_VideoInfo *info = SDL_GetVideoInfo();
46   if (info)
47   {
48     desktop_size = Size(info->current_w, info->current_h);
49   }
50 #endif
51
52   if(texture_manager != 0)
53     texture_manager->save_textures();
54
55 #ifdef SDL_GL_SWAP_CONTROL
56   if(config->try_vsync) {
57     /* we want vsync for smooth scrolling */
58     SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
59   }
60 #endif
61
62   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
63
64   // FIXME: Hu? 16bit rendering?
65   SDL_GL_SetAttribute(SDL_GL_RED_SIZE,   5);
66   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
67   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE,  5);
68
69   if(g_config->use_fullscreen)
70   {
71     apply_video_mode(g_config->fullscreen_size, true);
72   }
73   else
74   {
75     apply_video_mode(g_config->window_size, false);
76   }
77
78   // setup opengl state and transform
79   glDisable(GL_DEPTH_TEST);
80   glDisable(GL_CULL_FACE);
81   glEnable(GL_TEXTURE_2D);
82   glEnable(GL_BLEND);
83   glEnableClientState(GL_VERTEX_ARRAY);
84   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
85   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
86
87   // Init the projection matrix, viewport and stuff
88   apply_config();
89   
90   if(texture_manager == 0)
91     texture_manager = new TextureManager();
92   else
93     texture_manager->reload_textures();
94   
95 #ifndef GL_VERSION_ES_CM_1_0
96   GLenum err = glewInit();
97   if (GLEW_OK != err)
98   {
99     std::ostringstream out;
100     out << "GLRenderer: " << glewGetErrorString(err);
101     throw std::runtime_error(out.str());
102   }
103   log_info << "Using GLEW " << glewGetString(GLEW_VERSION) << std::endl;
104   log_info << "GLEW_ARB_texture_non_power_of_two: " << static_cast<int>(GLEW_ARB_texture_non_power_of_two) << std::endl;
105 #endif
106 }
107
108 GLRenderer::~GLRenderer()
109 {
110 }
111
112 void
113 GLRenderer::draw_surface(const DrawingRequest& request)
114 {
115   const Surface* surface = (const Surface*) request.request_data;
116   GLTexture* gltexture = static_cast<GLTexture*>(surface->get_texture().get());
117   GLSurfaceData *surface_data = static_cast<GLSurfaceData*>(surface->get_surface_data());
118
119   glBindTexture(GL_TEXTURE_2D, gltexture->get_handle());
120   intern_draw(request.pos.x, request.pos.y,
121               request.pos.x + surface->get_width(),
122               request.pos.y + surface->get_height(),
123               surface_data->get_uv_left(),
124               surface_data->get_uv_top(),
125               surface_data->get_uv_right(),
126               surface_data->get_uv_bottom(),
127               request.angle,
128               request.alpha,
129               request.color,
130               request.blend,
131               request.drawing_effect);
132 }
133
134 void
135 GLRenderer::draw_surface_part(const DrawingRequest& request)
136 {
137   const SurfacePartRequest* surfacepartrequest
138     = (SurfacePartRequest*) request.request_data;
139   const Surface* surface = surfacepartrequest->surface;
140   boost::shared_ptr<GLTexture> gltexture = boost::dynamic_pointer_cast<GLTexture>(surface->get_texture());
141   GLSurfaceData *surface_data = reinterpret_cast<GLSurfaceData *>(surface->get_surface_data());
142
143   float uv_width = surface_data->get_uv_right() - surface_data->get_uv_left();
144   float uv_height = surface_data->get_uv_bottom() - surface_data->get_uv_top();
145
146   float uv_left = surface_data->get_uv_left() + (uv_width * surfacepartrequest->source.x) / surface->get_width();
147   float uv_top = surface_data->get_uv_top() + (uv_height * surfacepartrequest->source.y) / surface->get_height();
148   float uv_right = surface_data->get_uv_left() + (uv_width * (surfacepartrequest->source.x + surfacepartrequest->size.x)) / surface->get_width();
149   float uv_bottom = surface_data->get_uv_top() + (uv_height * (surfacepartrequest->source.y + surfacepartrequest->size.y)) / surface->get_height();
150
151   glBindTexture(GL_TEXTURE_2D, gltexture->get_handle());
152   intern_draw(request.pos.x, request.pos.y,
153               request.pos.x + surfacepartrequest->size.x,
154               request.pos.y + surfacepartrequest->size.y,
155               uv_left,
156               uv_top,
157               uv_right,
158               uv_bottom,
159               0.0,
160               request.alpha,
161               request.color,
162               Blend(),
163               request.drawing_effect);
164 }
165
166 void
167 GLRenderer::draw_gradient(const DrawingRequest& request)
168 {
169   const GradientRequest* gradientrequest 
170     = (GradientRequest*) request.request_data;
171   const Color& top = gradientrequest->top;
172   const Color& bottom = gradientrequest->bottom;
173
174   glDisable(GL_TEXTURE_2D);
175   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
176   glEnableClientState(GL_COLOR_ARRAY);
177
178   float vertices[] = {
179     0, 0,
180     SCREEN_WIDTH, 0,
181     SCREEN_WIDTH, SCREEN_HEIGHT,
182     0, SCREEN_HEIGHT
183   };
184   glVertexPointer(2, GL_FLOAT, 0, vertices);
185
186   float colors[] = {
187     top.red, top.green, top.blue, top.alpha,
188     top.red, top.green, top.blue, top.alpha,
189     bottom.red, bottom.green, bottom.blue, bottom.alpha,
190     bottom.red, bottom.green, bottom.blue, bottom.alpha,
191   };
192   glColorPointer(4, GL_FLOAT, 0, colors);
193
194   glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
195
196   glDisableClientState(GL_COLOR_ARRAY);
197   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
198
199   glEnable(GL_TEXTURE_2D);
200   glColor4f(1, 1, 1, 1);
201 }
202
203 void
204 GLRenderer::draw_filled_rect(const DrawingRequest& request)
205 {
206   const FillRectRequest* fillrectrequest
207     = (FillRectRequest*) request.request_data;
208
209   glDisable(GL_TEXTURE_2D);
210   glColor4f(fillrectrequest->color.red, fillrectrequest->color.green,
211             fillrectrequest->color.blue, fillrectrequest->color.alpha);
212   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
213   
214   if (fillrectrequest->radius != 0.0f)
215   {
216     // draw round rect
217     // Keep radius in the limits, so that we get a circle instead of
218     // just graphic junk
219     float radius = std::min(fillrectrequest->radius,
220                             std::min(fillrectrequest->size.x/2,
221                                      fillrectrequest->size.y/2));
222
223     // inner rectangle
224     Rectf irect(request.pos.x    + radius,
225                request.pos.y    + radius,
226                request.pos.x + fillrectrequest->size.x - radius,
227                request.pos.y + fillrectrequest->size.y - radius);
228
229     int n = 8;
230     int p = 0;
231     std::vector<float> vertices((n+1) * 4 * 2);
232
233     for(int i = 0; i <= n; ++i)
234     {
235       float x = sinf(i * (M_PI/2) / n) * radius;
236       float y = cosf(i * (M_PI/2) / n) * radius;
237
238       vertices[p++] = irect.get_left() - x;
239       vertices[p++] = irect.get_top()  - y;
240
241       vertices[p++] = irect.get_right() + x;
242       vertices[p++] = irect.get_top()   - y;
243     }
244
245     for(int i = 0; i <= n; ++i)
246     {
247       float x = cosf(i * (M_PI/2) / n) * radius;
248       float y = sinf(i * (M_PI/2) / n) * radius;
249
250       vertices[p++] = irect.get_left()   - x;
251       vertices[p++] = irect.get_bottom() + y;
252
253       vertices[p++] = irect.get_right()  + x;
254       vertices[p++] = irect.get_bottom() + y;
255     }
256
257     glVertexPointer(2, GL_FLOAT, 0, &*vertices.begin());
258     glDrawArrays(GL_TRIANGLE_STRIP, 0,  vertices.size()/2);
259   }
260   else
261   {
262     float x = request.pos.x;
263     float y = request.pos.y;
264     float w = fillrectrequest->size.x;
265     float h = fillrectrequest->size.y;
266
267     float vertices[] = {
268       x,   y,
269       x+w, y,
270       x+w, y+h,
271       x,   y+h
272     };
273     glVertexPointer(2, GL_FLOAT, 0, vertices);
274
275     glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
276   }
277
278   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
279   glEnable(GL_TEXTURE_2D);
280   glColor4f(1, 1, 1, 1);
281 }
282
283 void
284 GLRenderer::draw_inverse_ellipse(const DrawingRequest& request)
285 {
286   const InverseEllipseRequest* ellipse = (InverseEllipseRequest*)request.request_data;
287
288   glDisable(GL_TEXTURE_2D);
289   glColor4f(ellipse->color.red,  ellipse->color.green,
290             ellipse->color.blue, ellipse->color.alpha);
291     
292   float x = request.pos.x;
293   float y = request.pos.y;
294   float w = ellipse->size.x/2.0f;
295   float h = ellipse->size.y/2.0f;
296
297   static const int slices = 16;
298   static const int points = (slices+1) * 12;
299
300   float vertices[points * 2];
301   int   p = 0;
302
303   // Bottom
304   vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
305   vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
306   vertices[p++] = x;            vertices[p++] = y+h;
307
308   // Top
309   vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
310   vertices[p++] = 0;            vertices[p++] = 0;
311   vertices[p++] = x;            vertices[p++] = y-h;
312
313   // Left
314   vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
315   vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
316   vertices[p++] = x+w;          vertices[p++] = y;
317
318   // Right
319   vertices[p++] = 0;            vertices[p++] = 0;
320   vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
321   vertices[p++] = x-w;          vertices[p++] = y;
322
323   for(int i = 0; i < slices; ++i)
324   {
325     float ex1 = sinf(M_PI/2 / slices * i) * w;
326     float ey1 = cosf(M_PI/2 / slices * i) * h;
327
328     float ex2 = sinf(M_PI/2 / slices * (i+1)) * w;
329     float ey2 = cosf(M_PI/2 / slices * (i+1)) * h;
330
331     // Bottom/Right
332     vertices[p++] = SCREEN_WIDTH; vertices[p++] = SCREEN_HEIGHT;
333     vertices[p++] = x + ex1;      vertices[p++] = y + ey1;
334     vertices[p++] = x + ex2;      vertices[p++] = y + ey2;
335
336     // Top/Left
337     vertices[p++] = 0;            vertices[p++] = 0;
338     vertices[p++] = x - ex1;      vertices[p++] = y - ey1;
339     vertices[p++] = x - ex2;      vertices[p++] = y - ey2;
340
341     // Top/Right
342     vertices[p++] = SCREEN_WIDTH; vertices[p++] = 0;
343     vertices[p++] = x + ex1;      vertices[p++] = y - ey1;
344     vertices[p++] = x + ex2;      vertices[p++] = y - ey2;
345
346     // Bottom/Left
347     vertices[p++] = 0;            vertices[p++] = SCREEN_HEIGHT;
348     vertices[p++] = x - ex1;      vertices[p++] = y + ey1;
349     vertices[p++] = x - ex2;      vertices[p++] = y + ey2;
350   }
351
352   glDisableClientState(GL_TEXTURE_COORD_ARRAY);
353   glVertexPointer(2, GL_FLOAT, 0, vertices);
354
355   glDrawArrays(GL_TRIANGLES, 0, points);
356
357   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
358
359   glEnable(GL_TEXTURE_2D);
360   glColor4f(1, 1, 1, 1);    
361 }
362
363 void 
364 GLRenderer::do_take_screenshot()
365 {
366   // [Christoph] TODO: Yes, this method also takes care of the actual disk I/O. Split it?
367
368   SDL_Surface *shot_surf;
369   // create surface to hold screenshot
370 #if SDL_BYTEORDER == SDL_BIG_ENDIAN
371   shot_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x00FF0000, 0x0000FF00, 0x000000FF, 0);
372 #else
373   shot_surf = SDL_CreateRGBSurface(SDL_SWSURFACE, SCREEN_WIDTH, SCREEN_HEIGHT, 24, 0x000000FF, 0x0000FF00, 0x00FF0000, 0);
374 #endif
375   if (!shot_surf) {
376     log_warning << "Could not create RGB Surface to contain screenshot" << std::endl;
377     return;
378   }
379
380   // read pixels into array
381   char* pixels = new char[3 * SCREEN_WIDTH * SCREEN_HEIGHT];
382   if (!pixels) {
383     log_warning << "Could not allocate memory to store screenshot" << std::endl;
384     SDL_FreeSurface(shot_surf);
385     return;
386   }
387   glPixelStorei(GL_PACK_ALIGNMENT, 1);
388   glReadPixels(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, GL_RGB, GL_UNSIGNED_BYTE, pixels);
389
390   // copy array line-by-line
391   for (int i = 0; i < SCREEN_HEIGHT; i++) {
392     char* src = pixels + (3 * SCREEN_WIDTH * (SCREEN_HEIGHT - i - 1));
393     if(SDL_MUSTLOCK(shot_surf))
394     {
395       SDL_LockSurface(shot_surf);
396     }
397     char* dst = ((char*)shot_surf->pixels) + i * shot_surf->pitch;
398     memcpy(dst, src, 3 * SCREEN_WIDTH);
399     if(SDL_MUSTLOCK(shot_surf))
400     {
401       SDL_UnlockSurface(shot_surf);
402     }
403   }
404
405   // free array
406   delete[](pixels);
407
408   // save screenshot
409   static const std::string writeDir = PHYSFS_getWriteDir();
410   static const std::string dirSep = PHYSFS_getDirSeparator();
411   static const std::string baseName = "screenshot";
412   static const std::string fileExt = ".bmp";
413   std::string fullFilename;
414   for (int num = 0; num < 1000; num++) {
415     std::ostringstream oss;
416     oss << baseName;
417     oss << std::setw(3) << std::setfill('0') << num;
418     oss << fileExt;
419     std::string fileName = oss.str();
420     fullFilename = writeDir + dirSep + fileName;
421     if (!PHYSFS_exists(fileName.c_str())) {
422       SDL_SaveBMP(shot_surf, fullFilename.c_str());
423       log_debug << "Wrote screenshot to \"" << fullFilename << "\"" << std::endl;
424       SDL_FreeSurface(shot_surf);
425       return;
426     }
427   }
428   log_warning << "Did not save screenshot, because all files up to \"" << fullFilename << "\" already existed" << std::endl;
429   SDL_FreeSurface(shot_surf);
430 }
431
432 void
433 GLRenderer::flip()
434 {
435   assert_gl("drawing");
436   SDL_GL_SwapBuffers();
437 }
438
439 void
440 GLRenderer::resize(int w, int h)
441 {
442   // This causes the screen to go black, which is annoying, but seems
443   // unavoidable with SDL at the moment
444   SDL_SetVideoMode(w, h, 0, SDL_OPENGL | SDL_RESIZABLE);
445
446   g_config->window_size = Size(w, h);
447
448   apply_config();
449 }
450
451 void
452 GLRenderer::apply_config()
453 {    
454   if (false)
455   {
456     log_info << "Applying Config:" 
457              << "\n  Desktop: " << desktop_size.width << "x" << desktop_size.height
458              << "\n  Window:  " << g_config->window_size
459              << "\n  FullRes: " << g_config->fullscreen_size
460              << "\n  Aspect:  " << g_config->aspect_size
461              << "\n  Magnif:  " << g_config->magnification
462              << std::endl;
463   }
464
465   float target_aspect = static_cast<float>(desktop_size.width) / static_cast<float>(desktop_size.height);
466   if (g_config->aspect_size != Size(0, 0))
467   {
468     target_aspect = float(g_config->aspect_size.width) / float(g_config->aspect_size.height);
469   }
470
471   float desktop_aspect = 4.0f / 3.0f; // random default fallback guess
472   if (desktop_size.width != -1 && desktop_size.height != -1)
473   {
474     desktop_aspect = float(desktop_size.width) / float(desktop_size.height);
475   }
476
477   Size screen_size;
478
479   // Get the screen width
480   if (g_config->use_fullscreen)
481   {
482     screen_size = g_config->fullscreen_size;
483     desktop_aspect = float(screen_size.width) / float(screen_size.height);
484   }
485   else
486   {
487     screen_size = g_config->window_size;
488   }
489
490   apply_video_mode(screen_size, g_config->use_fullscreen);
491
492   if (target_aspect > 1.0f)
493   {
494     SCREEN_WIDTH  = static_cast<int>(screen_size.width * (target_aspect / desktop_aspect));
495     SCREEN_HEIGHT = static_cast<int>(screen_size.height);
496   }
497   else
498   {
499     SCREEN_WIDTH  = static_cast<int>(screen_size.width);
500     SCREEN_HEIGHT = static_cast<int>(screen_size.height  * (target_aspect / desktop_aspect));
501   }
502
503   Size max_size(1280, 800);
504
505   if (g_config->magnification == 0.0f) // Magic value that means 'minfill'
506   {
507     // This scales SCREEN_WIDTH/SCREEN_HEIGHT so that they never excede
508     // max_size.width/max_size.height
509     if (SCREEN_WIDTH > max_size.width || SCREEN_HEIGHT > max_size.height)
510     {
511       float scale1  = float(max_size.width)/SCREEN_WIDTH;
512       float scale2  = float(max_size.height)/SCREEN_HEIGHT;
513       float scale   = (scale1 < scale2) ? scale1 : scale2;
514       SCREEN_WIDTH  = static_cast<int>(SCREEN_WIDTH  * scale);
515       SCREEN_HEIGHT = static_cast<int>(SCREEN_HEIGHT * scale);
516     }
517
518     glViewport(0, 0, screen_size.width, screen_size.height);
519   }
520   else
521   {
522     SCREEN_WIDTH  = static_cast<int>(SCREEN_WIDTH  / g_config->magnification);
523     SCREEN_HEIGHT = static_cast<int>(SCREEN_HEIGHT / g_config->magnification);
524
525     // This works by adding black borders around the screen to limit
526     // SCREEN_WIDTH/SCREEN_HEIGHT to max_size.width/max_size.height
527     Size new_size = screen_size;
528
529     if (SCREEN_WIDTH > max_size.width)
530     {
531       new_size.width = static_cast<int>((float) new_size.width * float(max_size.width)/SCREEN_WIDTH);
532       SCREEN_WIDTH = static_cast<int>(max_size.width);
533     }
534
535     if (SCREEN_HEIGHT > max_size.height)
536     {
537       new_size.height = static_cast<int>((float) new_size.height * float(max_size.height)/SCREEN_HEIGHT);
538       SCREEN_HEIGHT = static_cast<int>(max_size.height);
539     }
540
541     // Clear both buffers so that we get a clean black border without junk
542     glClear(GL_COLOR_BUFFER_BIT);
543     SDL_GL_SwapBuffers();
544     glClear(GL_COLOR_BUFFER_BIT);
545     SDL_GL_SwapBuffers();
546
547     glViewport(std::max(0, (screen_size.width  - new_size.width)  / 2),
548                std::max(0, (screen_size.height - new_size.height) / 2),
549                std::min(new_size.width,  screen_size.width),
550                std::min(new_size.height, screen_size.height));
551   }
552
553   glMatrixMode(GL_PROJECTION);
554   glLoadIdentity();
555
556   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1, 1);
557
558   glMatrixMode(GL_MODELVIEW);
559   glLoadIdentity();
560   glTranslatef(0, 0, 0);
561   check_gl_error("Setting up view matrices");
562 }
563
564 void
565 GLRenderer::apply_video_mode(const Size& size, bool fullscreen)
566 {
567   // Only change video mode when its different from the current one
568   if (screen_size != size || fullscreen_active != fullscreen)
569   {
570     int flags = SDL_OPENGL;
571
572     if (fullscreen)
573     {
574       flags |= SDL_FULLSCREEN;
575     }
576     else
577     {
578       flags |= SDL_RESIZABLE;
579     }
580
581     if (SDL_Surface *screen = SDL_SetVideoMode(size.width, size.height, 0, flags))
582     {
583       screen_size = Size(screen->w, screen->h);
584       fullscreen_active = fullscreen; 
585     }
586     else
587     {
588       std::ostringstream msg;
589       msg << "Couldn't set video mode " << size.width << "x" << size.height << ": " << SDL_GetError();
590       throw std::runtime_error(msg.str());
591     }
592   }
593 }
594
595 /* EOF */