Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/graphics/graphics_engine.cc @ 7250

Last change on this file since 7250 was 7221, checked in by bensch, 19 years ago

orxonox/trunk: merged the std-branche back, it runs on windows and Linux

svn merge https://svn.orxonox.net/orxonox/branches/std . -r7202:HEAD

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