Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 6247 was 6222, checked in by bensch, 19 years ago

orxonox/trunk: merged the christmas branche to the trunk
merged with command:
svn merge -r6165:HEAD christmas_branche/ ../trunk/
no conflicts

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