Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/terrain/src/lib/graphics/graphics_engine.cc @ 8570

Last change on this file since 8570 was 8308, checked in by ponder, 19 years ago
  • orxonox crashed on osx when a call to the opengl subsystem was done before the window was created. I changed the

order of initialisation in graphics_engine.cc.

  • orxonox.cc contained a bug when debug level is set unter 3
File size: 17.3 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: ...
14*/
15
16#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_GRAPHICS
17
18#include "graphics_engine.h"
19#include "util/loading/resource_manager.h"
20#include "state.h"
21
22#include "world_entity.h"
23
24#include "render_2d.h"
25#include "text_engine.h"
26#include "light.h"
27#include "shader.h"
28#include "debug.h"
29
30#include "util/preferences.h"
31#include "substring.h"
32#include "text.h"
33
34#include "globals.h"
35#include "texture.h"
36
37#include "effects/graphics_effect.h"
38#include "effects/fog_effect.h"
39#include "effects/lense_flare.h"
40
41#include "shell_command.h"
42
43
44#include "parser/tinyxml/tinyxml.h"
45#include "util/loading/load_param.h"
46#include "util/loading/factory.h"
47#include "class_list.h"
48
49#ifdef __WIN32__
50 #include "static_model.h"
51#endif
52using namespace std;
53
54SHELL_COMMAND(wireframe, GraphicsEngine, wireframe);
55
56
57/**
58 * @brief standard constructor
59 */
60GraphicsEngine::GraphicsEngine ()
61{
62  this->setClassID(CL_GRAPHICS_ENGINE, "GraphicsEngine");
63  this->setName("GraphicsEngine");
64
65  this->isInit = false;
66
67  this->bDisplayFPS = false;
68  this->minFPS = 9999;
69  this->maxFPS = 0;
70
71  this->geTextCFPS = NULL;
72  this->geTextMaxFPS = NULL;
73  this->geTextMinFPS = NULL;
74
75  this->fullscreenFlag = 0;
76  this->videoFlags = 0;
77  this->screen = NULL;
78
79  // initialize the Modules
80  TextEngine::getInstance();
81  this->graphicsEffects = NULL;
82
83}
84
85/**
86 * @brief The Pointer to this GraphicsEngine
87 */
88GraphicsEngine* GraphicsEngine::singletonRef = NULL;
89
90/**
91 * @brief destructs the graphicsEngine.
92*/
93GraphicsEngine::~GraphicsEngine ()
94{
95  // delete what has to be deleted here
96  this->displayFPS( false );
97
98  //TextEngine
99  delete TextEngine::getInstance();
100  // render 2D
101  delete Render2D::getInstance();
102
103  SDL_QuitSubSystem(SDL_INIT_VIDEO);
104  //   if (this->screen != NULL)
105  //     SDL_FreeSurface(this->screen);
106
107  GraphicsEngine::singletonRef = NULL;
108}
109
110
111/**
112 * @brief loads the GraphicsEngine Specific Parameters.
113 * @param root: the XML-Element to load the Data From
114 */
115void GraphicsEngine::loadParams(const TiXmlElement* root)
116{
117  LoadParamXML(root, "GraphicsEffect", this, GraphicsEngine, loadGraphicsEffects)
118  .describe("loads a graphics effect");
119}
120
121
122
123
124/**
125 * @param root The XML-element to load GraphicsEffects from
126 */
127void GraphicsEngine::loadGraphicsEffects(const TiXmlElement* root)
128{
129  LOAD_PARAM_START_CYCLE(root, element);
130  {
131    PRINTF(4)("element is: %s\n", element->Value());
132    Factory::fabricate(element);
133  }
134  LOAD_PARAM_END_CYCLE(element);
135}
136
137
138
139/**
140 * @brief initializes the GraphicsEngine with default settings.
141 */
142int GraphicsEngine::init()
143{
144  if (this->isInit)
145    return -1;
146  this->initVideo(640, 480, 16);
147}
148
149/**
150 * @brief loads the GraphicsEngine's settings from a given ini-file and section
151 * @returns nothing usefull
152 */
153int GraphicsEngine::initFromPreferences()
154{
155  // looking if we are in fullscreen-mode
156  MultiType fullscreen = Preferences::getInstance()->getString(CONFIG_SECTION_VIDEO, CONFIG_NAME_FULLSCREEN, "0");
157
158  if (fullscreen.getBool())
159    this->fullscreenFlag = SDL_FULLSCREEN;
160
161  // looking if we are in fullscreen-mode
162  MultiType textures = Preferences::getInstance()->getString(CONFIG_SECTION_VIDEO_ADVANCED, CONFIG_NAME_TEXTURES, "1");
163    Texture::setTextureEnableState(textures.getBool());
164
165  // searching for a usefull resolution
166  SubString resolution(Preferences::getInstance()->getString(CONFIG_SECTION_VIDEO, CONFIG_NAME_RESOLUTION, "640x480").c_str(), 'x'); ///FIXME
167  //resolution.debug();
168  MultiType x = resolution.getString(0), y = resolution.getString(1);
169  this->initVideo(x.getInt(), y.getInt(), 16);
170
171  //   GraphicsEffect* fe = new FogEffect(NULL);
172  //   this->loadGraphicsEffect(fe);
173  //   fe->activate();
174  //   PRINTF(0)("--------------------------------------------------------------\n");
175
176  //LenseFlare* ge = new LenseFlare();
177  //this->loadGraphicsEffect(ge);
178
179  //ge->addFlare("pictures/lense_flare/sun.png"); //sun
180  //ge->addFlare("pictures/lense_flare/lens2.png"); //first halo
181  //ge->addFlare("pictures/lense_flare/lens1.png"); //small birst
182  //ge->addFlare("pictures/lense_flare/lens3.png"); //second halo
183  //ge->addFlare("pictures/lense_flare/lens4.png");
184  //ge->addFlare("pictures/lense_flare/lens1.png");
185  //ge->addFlare("pictures/lense_flare/lens3.png");
186
187  //ge->activate();
188}
189
190
191
192/**
193 * @brief initializes the Video for openGL.
194 *
195 * This has to be done only once when starting orxonox.
196 */
197int GraphicsEngine::initVideo(unsigned int resX, unsigned int resY, unsigned int bbp)
198{
199  if (this->isInit)
200    return -1;
201  //   initialize SDL_VIDEO
202  if (SDL_InitSubSystem(SDL_INIT_VIDEO) == -1)
203  {
204    PRINTF(1)("could not initialize SDL Video\n");
205    //      return -1;
206  }
207  // initialize SDL_GL-settings
208  this->setGLattribs();
209
210  // setting the Video Flags.
211  this->videoFlags = SDL_OPENGL | SDL_HWPALETTE | SDL_RESIZABLE ;
212
213  /* query SDL for information about our video hardware */
214  const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo ();
215  if( videoInfo == NULL)
216  {
217    PRINTF(1)("Failed getting Video Info :%s\n", SDL_GetError());
218    SDL_Quit ();
219  }
220  if( videoInfo->hw_available)
221    this->videoFlags |= SDL_HWSURFACE;
222  else
223    this->videoFlags |= SDL_SWSURFACE;
224  /*
225  if(VideoInfo -> blit_hw)
226    VideoFlags |= SDL_HWACCEL;
227  */
228  // setting up the Resolution
229  this->setResolution(resX, resY, bbp);
230
231  // GRABBING ALL GL-extensions
232  this->grabHardwareSettings();
233
234  // Enable default GL stuff
235  glEnable(GL_DEPTH_TEST);
236  glEnable(GL_CULL_FACE);
237  glCullFace(GL_FRONT);
238  Render2D::getInstance();
239
240  this->isInit = true;
241}
242
243/**
244 * @brief sets the Window Captions and the Name of the icon.
245 * @param windowName The name of the Window
246 * @param icon The name of the Icon on the Disc
247 */
248void GraphicsEngine::setWindowName(const std::string& windowName, const std::string& icon)
249{
250  SDL_Surface* iconSurf = SDL_LoadBMP(icon.c_str());
251  if (iconSurf != NULL)
252  {
253    Uint32 colorkey = SDL_MapRGB(iconSurf->format, 0, 0, 0);
254    SDL_SetColorKey(iconSurf, SDL_SRCCOLORKEY, colorkey);
255    SDL_WM_SetIcon(iconSurf, NULL);
256    SDL_FreeSurface(iconSurf);
257  }
258
259  SDL_WM_SetCaption (windowName.c_str(), icon.c_str());
260}
261
262
263/**
264 * @brief Sets the GL-attributes
265 */
266int GraphicsEngine::setGLattribs()
267{
268  // Set video mode
269  // TO DO: parse arguments for settings
270  //SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
271  //SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
272  //SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
273  //SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
274
275
276  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
277  SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16);
278  SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0);
279  SDL_GL_SetAttribute( SDL_GL_ACCUM_RED_SIZE, 0);
280  SDL_GL_SetAttribute( SDL_GL_ACCUM_GREEN_SIZE, 0);
281  SDL_GL_SetAttribute( SDL_GL_ACCUM_BLUE_SIZE, 0);
282  SDL_GL_SetAttribute( SDL_GL_ACCUM_ALPHA_SIZE, 0);
283
284  SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);      //Use at least 5 bits of Red
285  SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);    //Use at least 5 bits of Green
286  SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);     //Use at least 5 bits of Blue
287  SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);   //Use at least 16 bits for the depth buffer
288  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);  //Enable double buffering
289
290}
291
292/**
293 * @brief grabs the Hardware Specifics
294 *
295 * checks for all the different HW-types
296 */
297void GraphicsEngine::grabHardwareSettings()
298{
299  const char* renderer = (const char*) glGetString(GL_RENDERER);
300  const char* vendor   = (const char*) glGetString(GL_VENDOR);
301  const char* version  = (const char*) glGetString(GL_VERSION);
302  const char* extensions = (const char*) glGetString(GL_EXTENSIONS);
303
304  //  printf("%s %s %s\n %s", renderer, vendor, version, extensions);
305
306  if (renderer != NULL)
307  {
308    this->hwRenderer == renderer;
309  }
310  if (vendor != NULL)
311  {
312    this->hwVendor == vendor;
313  }
314  if (version != NULL)
315  {
316    this->hwVersion == version;
317  }
318
319  if (extensions != NULL)
320    this->hwExtensions.split(extensions, " \n\t,");
321
322  PRINT(4)("Running on : vendor: %s,  renderer: %s,  version:%s\n", vendor, renderer, version);
323  PRINT(4)("Extensions:\n");
324  for (unsigned int i = 0; i < this->hwExtensions.size(); i++)
325    PRINT(4)("%d: %s\n", i, this->hwExtensions[i].c_str());
326
327
328  // inizializing GLEW
329  GLenum err = glewInit();
330  if (GLEW_OK != err)
331  {
332    /* Problem: glewInit failed, something is seriously wrong. */
333    PRINTF(1)("%s\n", glewGetErrorString(err));
334  }
335  PRINTF(4)("Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
336}
337
338
339/**
340 * @brief sets the Resolution of the Screen to display the Graphics to.
341 * @param width The width of the window
342 * @param height The height of the window
343 * @param bpp bits per pixel
344 */
345int GraphicsEngine::setResolution(int width, int height, int bpp)
346{
347  this->resolutionX = width;
348  this->resolutionY = height;
349  this->bitsPerPixel = bpp;
350  State::setResolution( width, height);
351
352  if (this->screen != NULL)
353    SDL_FreeSurface(screen);
354  if((this->screen = SDL_SetVideoMode(this->resolutionX, this->resolutionY, this->bitsPerPixel, this->videoFlags | this->fullscreenFlag)) == NULL)
355  {
356    PRINTF(1)("Could not SDL_SetVideoMode(%d, %d, %d, %d): %s\n", this->resolutionX, this->resolutionY, this->bitsPerPixel, this->videoFlags, SDL_GetError());
357    //    SDL_Quit();
358    //    return -1;
359  }
360  glViewport(0, 0, width, height);                     // Reset The Current Viewport
361
362#ifdef __WIN32__
363  // REBUILDING TEXTURES (ON WINDOWS CONTEXT SWITCH)
364  const std::list<BaseObject*>* texList = ClassList::getList(CL_TEXTURE);
365  if (texList != NULL)
366  {
367    std::list<BaseObject*>::const_iterator reTex;
368    for (reTex = texList->begin(); reTex != texList->end(); reTex++)
369      dynamic_cast<Texture*>(*reTex)->rebuild();
370  }
371  // REBUILDING MODELS
372  const std::list<BaseObject*>* modelList = ClassList::getList(CL_STATIC_MODEL);
373  if (texList != NULL)
374  {
375    std::list<BaseObject*>::const_iterator reModel;
376    for (reModel = modelList->begin(); reModel != modelList->end(); reModel++)
377      dynamic_cast<StaticModel*>(*reModel)->rebuild();
378  }
379#endif /* __WIN32__ */
380}
381
382/**
383 * @brief sets Fullscreen mode
384 * @param fullscreen true if fullscreen, false if windowed
385*/
386void GraphicsEngine::setFullscreen(bool fullscreen)
387{
388  if (fullscreen)
389    this->fullscreenFlag = SDL_FULLSCREEN;
390  else
391    this->fullscreenFlag = 0;
392  this->setResolution(this->resolutionX, this->resolutionY, this->bitsPerPixel);
393}
394
395/**
396 * @brief sets the background color
397 * @param red the red part of the background
398 * @param blue the blue part of the background
399 * @param green the green part of the background
400 * @param alpha the alpha part of the background
401 */
402void GraphicsEngine::setBackgroundColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
403{
404  glClearColor(red, green, blue, alpha);
405}
406
407/**
408 * @brief Signalhandler, for when the resolution has changed
409 * @param resizeInfo SDL information about the size of the new screen size
410 */
411int GraphicsEngine::resolutionChanged(const SDL_ResizeEvent& resizeInfo)
412{
413  this->setResolution(resizeInfo.w, resizeInfo.h, this->bitsPerPixel);
414}
415
416/**
417 * @brief entering 2D Mode
418 * this is a GL-Projection-mode, that is orthogonal, for placing the font in fron of everything else
419 */
420void GraphicsEngine::enter2DMode()
421{
422  //GraphicsEngine::storeMatrices();
423  SDL_Surface *screen = SDL_GetVideoSurface();
424
425  /* Note, there may be other things you need to change,
426     depending on how you have your OpenGL state set up.
427  */
428  glPushAttrib(GL_ENABLE_BIT);
429  glDisable(GL_DEPTH_TEST);
430  glDisable(GL_CULL_FACE);
431  glDisable(GL_LIGHTING);  // will be set back when leaving 2D-mode
432
433  glMatrixMode(GL_PROJECTION);
434  glPushMatrix();
435  glLoadIdentity();
436  glOrtho(0.0, (GLdouble)screen->w, (GLdouble)screen->h, 0.0, 0.0, 1.0);
437
438  glMatrixMode(GL_MODELVIEW);
439  glPushMatrix();
440  glLoadIdentity();
441}
442
443/**
444 * @brief leaves the 2DMode again also @see Font::enter2DMode()
445 */
446void GraphicsEngine::leave2DMode()
447{
448
449  glMatrixMode(GL_MODELVIEW);
450  glPopMatrix();
451
452  glMatrixMode(GL_PROJECTION);
453  glPopMatrix();
454
455  glPopAttrib();
456}
457
458/**
459 * @brief changes to wireframe-mode.
460 */
461void GraphicsEngine::wireframe()
462{
463  glPolygonMode(GL_FRONT, GL_LINE);
464}
465
466/**
467 * @brief stores the GL_matrices
468 */
469void GraphicsEngine::storeMatrices()
470{
471  glGetDoublev(GL_PROJECTION_MATRIX, GraphicsEngine::projMat);
472  glGetDoublev(GL_MODELVIEW_MATRIX, GraphicsEngine::modMat);
473  glGetIntegerv(GL_VIEWPORT, GraphicsEngine::viewPort);
474}
475
476//! the stored ModelView Matrix.
477GLdouble GraphicsEngine::modMat[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
478//! the stored Projection Matrix
479GLdouble GraphicsEngine::projMat[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
480//! The ViewPort
481GLint GraphicsEngine::viewPort[4] = {0,0,0,0};
482
483
484
485/**
486 * @brief outputs all the Fullscreen modes.
487 */
488void GraphicsEngine::listModes()
489{
490  /* Get available fullscreen/hardware modes */
491  this->videoModes=SDL_ListModes(NULL, SDL_FULLSCREEN|SDL_HWSURFACE);
492
493  /* Check is there are any modes available */
494  if(this->videoModes == (SDL_Rect **)0)
495  {
496    PRINTF(1)("No modes available!\n");
497    exit(-1);
498  }
499
500  /* Check if our resolution is restricted */
501  if(this->videoModes == (SDL_Rect **)-1)
502  {
503    PRINTF(2)("All resolutions available.\n");
504  }
505  else
506  {
507    /* Print valid modes */
508    PRINT(0)("Available Resoulution Modes are\n");
509    for(int i = 0; this->videoModes[i]; ++i)
510      PRINT(4)(" |  %d x %d\n", this->videoModes[i]->w, this->videoModes[i]->h);
511  }
512}
513
514/**
515 * @brief checks wether a certain extension is availiable
516 * @param extension the Extension to check for (ex. GL_ARB_texture_env_dot3)
517 * @return true if it is, false otherwise
518 */
519bool GraphicsEngine::hwSupportsEXT(const std::string& extension)
520{
521  for (unsigned int i = 0; i < this->hwExtensions.size(); i++)
522    if ( this->hwExtensions.getString(i) == extension)
523      return true;
524  return false;
525}
526
527/**
528 * @brief updates everything that is to be updated in the GraphicsEngine
529 */
530void GraphicsEngine::update(float dt)
531{
532  Render2D::getInstance()->update(dt);
533}
534
535
536/**
537 * @brief ticks the Text
538 * @param dt the time passed
539 */
540void GraphicsEngine::tick(float dt)
541{
542  if( unlikely(this->bDisplayFPS))
543  {
544    this->currentFPS = 1.0/dt;
545    if( unlikely(this->currentFPS > this->maxFPS)) this->maxFPS = this->currentFPS;
546    if( unlikely(this->currentFPS < this->minFPS)) this->minFPS = this->currentFPS;
547
548#ifndef NO_TEXT
549    char tmpChar1[20];
550    sprintf(tmpChar1, "Current:  %4.0f", this->currentFPS);
551    this->geTextCFPS->setText(tmpChar1);
552    char tmpChar2[20];
553    sprintf(tmpChar2, "Max:    %4.0f", this->maxFPS);
554    this->geTextMaxFPS->setText(tmpChar2);
555    char tmpChar3[20];
556    sprintf(tmpChar3, "Min:    %4.0f", this->minFPS);
557    this->geTextMinFPS->setText(tmpChar3);
558#endif /* NO_TEXT */
559
560  }
561
562  Render2D::getInstance()->tick(dt);
563
564  // tick the graphics effects
565  if (this->graphicsEffects != NULL || (this->graphicsEffects = ClassList::getList(CL_GRAPHICS_EFFECT)) != NULL)
566  {
567    std::list<BaseObject*>::const_iterator it;
568    for (it = this->graphicsEffects->begin(); it != this->graphicsEffects->end(); it++)
569      dynamic_cast<GraphicsEffect*>(*it)->tick(dt);
570  }
571}
572
573/**
574 * @brief draws all Elements that should be displayed on the Background.
575 */
576void GraphicsEngine::drawBackgroundElements() const
577{
578  GraphicsEngine::storeMatrices();
579
580  Render2D::getInstance()->draw(E2D_LAYER_BELOW_ALL, E2D_LAYER_BELOW_ALL);
581}
582
583void GraphicsEngine::draw() const
584{
585  //  LightManager::getInstance()->draw();
586
587  if (this->graphicsEffects != NULL)
588  {
589    //draw the graphics effects
590    list<BaseObject*>::const_iterator it;
591    for (it = this->graphicsEffects->begin(); it != this->graphicsEffects->end(); it++)
592      dynamic_cast<GraphicsEffect*>(*it)->draw();
593  }
594  GraphicsEngine::storeMatrices();
595  Shader::suspendShader();
596  Render2D::getInstance()->draw(E2D_LAYER_BOTTOM, E2D_LAYER_ABOVE_ALL);
597  Shader::restoreShader();
598}
599
600
601/**
602 * @brief displays the Frames per second
603 * @param display if the text should be displayed
604*/
605void GraphicsEngine::displayFPS(bool display)
606{
607#ifndef NO_TEXT
608  if( display )
609  {
610    if (this->geTextCFPS == NULL)
611    {
612      this->geTextCFPS = new Text("fonts/arial_black.ttf", 15);
613      this->geTextCFPS->setName("curFPS");
614      this->geTextCFPS->setAlignment(TEXT_ALIGN_LEFT);
615      this->geTextCFPS->setAbsCoor2D(5, 0);
616    }
617    if (this->geTextMaxFPS == NULL)
618    {
619      this->geTextMaxFPS = new Text("fonts/arial_black.ttf", 15);
620      this->geTextMaxFPS->setName("MaxFPS");
621      this->geTextMaxFPS->setAlignment(TEXT_ALIGN_LEFT);
622      this->geTextMaxFPS->setAbsCoor2D(5, 20);
623    }
624    if (this->geTextMinFPS == NULL)
625    {
626      this->geTextMinFPS = new Text("fonts/arial_black.ttf", 15);
627      this->geTextMinFPS->setName("MinFPS");
628      this->geTextMinFPS->setAlignment(TEXT_ALIGN_LEFT);
629      this->geTextMinFPS->setAbsCoor2D(5, 40);
630    }
631  }
632  else
633  {
634    delete this->geTextCFPS;
635    this->geTextCFPS = NULL;
636    delete this->geTextMaxFPS;
637    this->geTextMaxFPS = NULL;
638    delete this->geTextMinFPS;
639    this->geTextMinFPS = NULL;
640  }
641  this->bDisplayFPS = display;
642#else
643  this->bDisplayFPS = false;
644#endif /* NO_TEXT */
645}
646
647
648/**
649 * @brief processes the events for the GraphicsEngine class
650 * @param the event to handle
651 */
652void GraphicsEngine::process(const Event &event)
653{
654  switch (event.type)
655  {
656  case EV_VIDEO_RESIZE:
657    this->resolutionChanged(event.resize);
658    break;
659  }
660}
Note: See TracBrowser for help on using the repository browser.