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