OpenFlipper.cc 29.3 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1 2 3
/*===========================================================================*\
*                                                                            *
*                              OpenFlipper                                   *
Martin Schultz's avatar
Martin Schultz committed
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
 *           Copyright (c) 2001-2015, RWTH-Aachen University                 *
 *           Department of Computer Graphics and Multimedia                  *
 *                          All rights reserved.                             *
 *                            www.openflipper.org                            *
 *                                                                           *
 *---------------------------------------------------------------------------*
 * This file is part of OpenFlipper.                                         *
 *---------------------------------------------------------------------------*
 *                                                                           *
 * Redistribution and use in source and binary forms, with or without        *
 * modification, are permitted provided that the following conditions        *
 * are met:                                                                  *
 *                                                                           *
 * 1. Redistributions of source code must retain the above copyright notice, *
 *    this list of conditions and the following disclaimer.                  *
 *                                                                           *
 * 2. Redistributions in binary form must reproduce the above copyright      *
 *    notice, this list of conditions and the following disclaimer in the    *
 *    documentation and/or other materials provided with the distribution.   *
 *                                                                           *
 * 3. Neither the name of the copyright holder nor the names of its          *
 *    contributors may be used to endorse or promote products derived from   *
 *    this software without specific prior written permission.               *
 *                                                                           *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       *
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           *
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER *
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,  *
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,       *
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR        *
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      *
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        *
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              *
Jan Möbius's avatar
Jan Möbius committed
39 40
*                                                                            *
\*===========================================================================*/
Jan Möbius's avatar
 
Jan Möbius committed
41

Jan Möbius's avatar
Jan Möbius committed
42 43 44 45 46 47 48
/*===========================================================================*\
*                                                                            *
*   $Revision$                                                       *
*   $LastChangedBy$                                                *
*   $Date$                     *
*                                                                            *
\*===========================================================================*/
Jan Möbius's avatar
 
Jan Möbius committed
49 50 51 52 53 54



// Mainwindow

#include "OpenFlipper/Core/Core.hh"
Hans-Christian Ebke's avatar
Hans-Christian Ebke committed
55
#include "common/glew_wrappers.hh"
56
#include "OpenFlipper/BasePlugin/PluginFunctionsCore.hh"
Jan Möbius's avatar
 
Jan Möbius committed
57 58 59 60 61 62

// Qt
#include <qgl.h>

// stdc++
#include <csignal>
63
#include <regex>
64 65

#include <QCommandLineParser>
Jan Möbius's avatar
 
Jan Möbius committed
66

Matthias Möller's avatar
Matthias Möller committed
67
#if ( defined(WIN32))
Mike Kremer's avatar
Mike Kremer committed
68 69 70 71
  #define NO_EXECINFO
#endif

#ifndef NO_EXECINFO
72
#include <execinfo.h>
Jan Möbius's avatar
 
Jan Möbius committed
73 74 75 76 77
#endif

#ifdef USE_OPENMP
#endif

78 79 80 81 82 83 84 85
/* ==========================================================
 *
 * Stackwalker code. Used to get a backtrace if OpenFlipper
 * crashes under windows
 *
 * ==========================================================*/


86 87
#ifdef WIN32
  #include "StackWalker/StackWalker.hh"
88
  #include <fstream>
89 90 91 92 93 94

  class StackWalkerToConsole : public StackWalker
  {
  protected:
	  virtual void OnOutput(LPCSTR szText)
    	{
95 96 97
			// Writes crash dump to .OpenFlipper config directory
			std::ofstream crashFile;
			QString crashName = OpenFlipper::Options::configDirStr() + QDir::separator() + "CrashDump.txt";
Jan Möbius's avatar
Jan Möbius committed
98
			crashFile.open(crashName.toLatin1(),std::ios::out | std::ios::app);
99 100
			crashFile << szText;
			crashFile.close();
Jan Möbius's avatar
Jan Möbius committed
101 102 103

			// Write crash dump to console as well
			StackWalker::OnOutput(szText);
104 105 106 107
	  }
  };
#endif

108 109 110 111 112 113 114 115 116

/* ==========================================================
 *
 * Console for Windows to get additional output written via
 * cerr, cout, ... that is not forwarded to log window
 *
 * ==========================================================*/

#ifdef WIN32
117

118 119 120 121 122 123 124 125 126 127 128 129 130
void connect_console()
{
  FILE* check = freopen("CONIN$", "r", stdin);
  if (check) {
    std::cerr << "Error reopening stdin" << std::endl;
  }
  check = freopen("CONOUT$", "w", stdout);
  if (check) {
    std::cerr << "Error reopening stdout" << std::endl;
  }
  check = freopen("CONOUT$", "w", stderr);
  if (check) {
    std::cerr << "Error reopening stderr" << std::endl;
131
  }
132 133 134 135 136 137
  std::cout.clear();
  std::cerr.clear();
  std::cin.clear();
  std::wcout.clear();
  std::wcerr.clear();
  std::wcin.clear();
138
}
139

Martin Schultz's avatar
Martin Schultz committed
140
  void attachConsole()
Jan Möbius's avatar
Jan Möbius committed
141 142 143 144 145
   {
     //try to attach the console of the parent process
     if (AttachConsole(-1))
     {
       //if the console was attached change stdinput and output
146
       connect_console();
Jan Möbius's avatar
Jan Möbius committed
147 148 149 150 151 152
     }
     else
     {
       //create and attach a new console if needed
 #ifndef NDEBUG
       //always open a console in debug mode
153
       AllocConsole();     
154
       connect_console();
Jan Möbius's avatar
Jan Möbius committed
155 156 157 158 159 160

       return;
 #endif
       if (OpenFlipper::Options::logToConsole())
       {
         AllocConsole();
161
         connect_console();
Jan Möbius's avatar
Jan Möbius committed
162 163 164
       }
     }
   }
165

166 167 168 169 170 171 172 173
#endif

/* ==========================================================
 *
 * Linux function printing a full stack trace to the console
 *
 * ==========================================================*/
#ifndef NO_EXECINFO
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

#if defined(__GLIBCXX__) || defined(__GLIBCPP__)
// GCC: implement demangling using cxxabi
#include <cxxabi.h>
std::string demangle(const std::string& _symbol)
{
    int status;
    char* demangled = abi::__cxa_demangle(_symbol.c_str(), nullptr, nullptr, &status);
    if (demangled) {
        std::string result{demangled};
        free(demangled);
        if (status == 0) {
            return result;
        }
        else {
            return _symbol;
        }
    }
    else {
        return _symbol;
    }
}
#else
// other compiler environment: no demangling
std::string demangle(const std::string& _symbol)
199
{
200 201 202
    return _symbol;
}
#endif
203

204 205 206 207
void backtrace()
{
    void *addresses[20];
    char **strings;
Jan Möbius's avatar
Jan Möbius committed
208

209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    int size = backtrace(addresses, 20);
    strings = backtrace_symbols(addresses, size);
    std::cerr << "Stack frames: " << size << std::endl;
    // line format:
    // <path>(<mangled_name>+<offset>) [<address>]
    std::regex line_format{R"(^\s*(.+)\((([^()]+)?\+(0x[0-9a-f]+))?\)\s+\[(0x[0-9a-f]+)\]\s*$)"};
    for(int i = 0; i < size; i++) {
        std::string line{strings[i]};
        std::smatch match;
        std::regex_match(line, match, line_format);
        if (!match.empty()) {
            auto file_name = match[1].str();
            auto symbol = demangle(match[3].str());
            auto offset = match[4].str();
            auto address = match[5].str();
            std::cerr << i << ":";
            if (!file_name.empty()) std::cerr << " " << file_name << " ::";
            if (!symbol.empty()) std::cerr << " " << symbol;
            if (!offset.empty()) std::cerr << " (+" << offset << ")";
            if (!address.empty()) std::cerr << " [" << address << "]";
            std::cerr << std::endl;
        }
    }
    free(strings);
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
}
#endif

/* ==========================================================
 *
 * General segfault handler. This function is called if OpenFlipper
 * crashes
 *
 * ==========================================================*/
void segfaultHandling (int) {

  // prevent infinite recursion if segfaultHandling() causes another segfault
  std::signal(SIGSEGV, SIG_DFL);


  std::cerr << "\n" << std::endl;
  std::cerr << "\n" << std::endl;
  std::cerr << "\33[31m" << "=====================================================" << std::endl;
  std::cerr << "\33[31m" << "OpenFlipper or one of its plugins caused a Segfault." << std::endl;
  std::cerr << "\33[31m" << "This should not happen,... Sorry :-(" << std::endl;
  std::cerr << "\33[31m" << "=====================================================" << std::endl;
  std::cerr << "\n" << std::endl;

  // Linux Handler
#ifndef NO_EXECINFO
  std::cerr << "\33[0m"  << "Trying a backtrace to show what happened last: " << std::endl;
  backtrace();

  std::cerr << "\n" << std::endl;
  std::cerr << "Backtrace completed, trying to abort now ..." << std::endl;
#endif

  // Windows handler via StackWalker
#ifdef WIN32
  StackWalkerToConsole sw;
  sw.ShowCallstack();
#endif


Jan Möbius's avatar
Jan Möbius committed
272 273 274 275 276 277 278 279
  std::cerr << "Trying to get additional information (This might fail if the memory is corrupted)." << std::endl;

  if (OpenFlipper::Options::gui()) {
    for ( unsigned int i = 0 ; i <  4 ; ++i) {
      std::cerr << "DrawMode Viewer "<<  i << " " << PluginFunctions::drawMode(i).description() << std::endl;
    }
  }

280 281
  std::abort();
}
282

283 284 285 286 287 288
enum CommandLineParseResult
{
    CommandLineOk,
    CommandLineError,
    CommandLineVersionRequested,
    CommandLineHelpRequested
Jan Möbius's avatar
 
Jan Möbius committed
289 290
};

291

292 293
bool openPolyMeshes = false;
bool remoteControl  = false;
294

295 296
// Parse all options
CommandLineParseResult parseCommandLine(QCommandLineParser &parser, QString *errorMessage) {
297

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
  #ifndef WIN32
  #ifndef __APPLE__
    //workaround for bug with stereo mode on Qt5.7.0 and Qt5.7.1 on Linux
    int QtVersionMajor, QtVersionMinor, QtVersionPatch;
    if(sscanf(qVersion(),"%1d.%1d.%1d",&QtVersionMajor, &QtVersionMinor, &QtVersionPatch) == 3)
    {
      if(QtVersionMajor == 5 && QtVersionMinor >= 7)
      {
        if(QtVersionPatch < 2)
        {
          std::cerr << "The used Qt Version does not support stereo mode. Disabling stereo mode." << std::endl;
          OpenFlipper::Options::stereo(false);
        }
        else
          std::cerr << "Stereo Mode has not been tested for the used Qt Version." << std::endl;
      }
    }
  #endif
  #endif


 parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);

321

322 323
 QCommandLineOption debugOption(QStringList() << "d" << "debug",QCoreApplication::translate("main", "Enable debugging mode"));
 parser.addOption(debugOption);
324

325 326
 QCommandLineOption stereoOption("disable-stereo",QCoreApplication::translate("main", "Disable stereo mode"));
 parser.addOption(stereoOption);
Jan Möbius's avatar
 
Jan Möbius committed
327

328 329
 QCommandLineOption batchOption(QStringList() << "b" << "batch",QCoreApplication::translate("main", "Batch mode, you have to provide a script for execution"));
 parser.addOption(batchOption);
Jan Möbius's avatar
 
Jan Möbius committed
330

331 332
 QCommandLineOption logConsoleOption(QStringList() << "c" << "log-to-console",QCoreApplication::translate("main", "Write logger window contents to console"));
 parser.addOption(logConsoleOption);
333

334 335
 QCommandLineOption remoteControlOption("remote-control",QCoreApplication::translate("main", "Batch mode accepting remote connections"));
 parser.addOption(remoteControlOption);
336

337
 QCommandLineOption fulscreenOption(QStringList() << "f" << "fullscreen",QCoreApplication::translate("main", "Start in fullscreen mode"));
338
 parser.addOption(fulscreenOption);
339

340 341
 QCommandLineOption hideLoggerOption(QStringList() << "l" << "hide-logger",QCoreApplication::translate("main", "Start with hidden log window"));
 parser.addOption(hideLoggerOption);
342

343 344
 QCommandLineOption hideToolboxOption(QStringList() << "t" << "hide-toolbox",QCoreApplication::translate("main", "Start with hidden toolbox"));
 parser.addOption(hideToolboxOption);
345

346 347
 QCommandLineOption noSplashOption("no-splash",QCoreApplication::translate("main", "Hide splash screen"));
 parser.addOption(noSplashOption);
348

349 350
 QCommandLineOption polyMeshOption("p",QCoreApplication::translate("main", "Open files as PolyMeshes"));
 parser.addOption(polyMeshOption);
351

352 353
 QCommandLineOption remotePortOption("remote-port",QCoreApplication::translate("main", "Remote port"),"portnumber");
 parser.addOption(remotePortOption);
354

355 356
 QCommandLineOption coreProfileOption("core-profile",QCoreApplication::translate("main", "OpenGL Core Profile Mode"));
 parser.addOption(coreProfileOption);
357 358 359 360 361 362 363
 
 QCommandLineOption glVersionOption("glVersion",QCoreApplication::translate("main","Request OpenGL version <major>.<minor> "),QCoreApplication::translate("main","< 1.0 | 1.1 | ... | 4.6 >"));
 parser.addOption(glVersionOption);
 
 QCommandLineOption samplesOption("samples",QCoreApplication::translate("main","Overwrite multisampling sample count"),QCoreApplication::translate("main","< 0 | 1 | 2 | ... | 16 >"));
 parser.addOption(samplesOption);
 
364 365 366
 QCommandLineOption glStereoOption("glStereo",QCoreApplication::translate("main","Overwrite OpenGL Stereo setting"),QCoreApplication::translate("main","< true | false >"));
 parser.addOption(glStereoOption);
 
367
 QCommandLineOption profileOption("profile",QCoreApplication::translate("main","Request OpenGL context profile <profile> with profile set as compat or core"),QCoreApplication::translate("main","< compat | core >"));
368
 parser.addOption(profileOption);
369 370 371 372

 QCommandLineOption pluginOptionsOption(QStringList() << "o" << "pluginoptions",QCoreApplication::translate("main", "Pass options to plugins"), "key1=value1;key2=value2;...");
 parser.addOption(pluginOptionsOption);

373 374
 const QCommandLineOption helpOption = parser.addHelpOption();
 const QCommandLineOption versionOption = parser.addVersionOption();
Dirk Wilden's avatar
Dirk Wilden committed
375 376


377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
 // Now parse the command line
 if (!parser.parse(QCoreApplication::arguments())) {
   *errorMessage = parser.errorText();
   return CommandLineError;
 }

 if (parser.isSet(helpOption))
   return CommandLineHelpRequested;

 if (parser.isSet(versionOption))
   return CommandLineVersionRequested;

 if (parser.isSet(debugOption)) {
   OpenFlipper::Options::debug(true);
 }

 if (parser.isSet(stereoOption)) {
   OpenFlipper::Options::stereo(false);
 }

 if (parser.isSet(batchOption)) {
   OpenFlipper::Options::nogui(true);
 }

 if (parser.isSet(logConsoleOption)) {
   OpenFlipper::Options::logToConsole(true);
 }

 if (parser.isSet(remoteControlOption)) {
   OpenFlipper::Options::remoteControl(true);
 }

 if (parser.isSet(fulscreenOption)) {
   OpenFlipperSettings().setValue("Core/Gui/fullscreen",true);
 }

 if (parser.isSet(hideLoggerOption)) {
   OpenFlipper::Options::loggerState(OpenFlipper::Options::Hidden);
 }

 if (parser.isSet(hideToolboxOption)) {
   OpenFlipperSettings().setValue("Core/Gui/ToolBoxes/hidden",true);
 }

 if (parser.isSet(noSplashOption)) {
   OpenFlipperSettings().setValue("Core/Gui/splash",false);
 }

 if (parser.isSet(polyMeshOption)) {
   openPolyMeshes = true;
 }

 if (parser.isSet(remotePortOption)) {
   const QString port = parser.value("remote-port");
   std::cerr << "Got port option : " << port.toStdString() << std::endl;
   OpenFlipper::Options::remoteControl(port.toInt());
433
 }
434 435 436 437 438 439 440 441 442 443
 if(parser.isSet("samples"))
   OpenFlipper::Options::samples(parser.value("samples").toInt(),true);
 if(parser.isSet("glVersion"))
 {
   QStringList values = parser.value("glVersion").split(".");
   QPair<int,int> version(
          values[0].toInt(),
          values[1].toInt());
   OpenFlipper::Options::glVersion(version,true);
 }
444 445 446
 
 if(parser.isSet("glStereo"))
   OpenFlipper::Options::glStereo(parser.value("glStereo")=="true");
447

448 449
 if(parser.value(profileOption)=="core")
 {
450
     OpenFlipper::Options::coreProfile(true, true);
451 452 453 454 455
 }
 else
 {
     if(parser.value(profileOption)=="compat")
     {
456
         OpenFlipper::Options::coreProfile(false, true);
457 458
     }
 }
459
 if(parser.isSet(coreProfileOption)) {
460
   OpenFlipper::Options::coreProfile(true, true);
461
 }
462 463 464 465 466 467 468 469 470 471 472 473 474
 if(parser.isSet(pluginOptionsOption))
 {
   QStringList poptions = parser.value(pluginOptionsOption).split(";");
   QVector<QPair<QString, QString>> pcloptions;
   for(auto s : poptions)
   {
       auto kvp = s.split("=");
       auto key = kvp[0];
       auto value = kvp[1];
       pcloptions.push_back({key, value});
   }
   PluginFunctions::setPluginCommandLineOptions(pcloptions);
 }
475

476
 return CommandLineOk;
Dirk Wilden's avatar
Dirk Wilden committed
477 478
}

479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536

namespace
{

// Print human-readable GL profile strings
std::string profileToString(QSurfaceFormat::OpenGLContextProfile _profile)
{
    if(_profile == QSurfaceFormat::CompatibilityProfile)
        return "CompatibilityProfile";

    if(_profile == QSurfaceFormat::CoreProfile)
        return "CoreProfile";

    if(_profile == QSurfaceFormat::NoProfile)
        return "NoProfile";

    return "[Unknown]";
}

// Check whether a specific context request can be fulfilled
// Can also return the format of the actually created context
bool verifySpecificContextFormat(QSurfaceFormat format, QSurfaceFormat* resultingFormat = nullptr)
{
    // All created surfaces try to obey the given format
    QSurfaceFormat::setDefaultFormat(format);

    // We need a temporary qApp to create a surface and test the current context
    int tempArgC = 0;
    QApplication tempApp(tempArgC, nullptr);
    QOffscreenSurface *surface = new QOffscreenSurface();
    surface->create();

    auto shareContext = QOpenGLContext::globalShareContext();
    if(!shareContext)
    {
        std::cerr << "Error: Apparently no GL context was created!" << std::endl;
        return false;
    }

    // Make the globally shared OpenGLContext current
    shareContext->makeCurrent(surface);

    // The opengl surface properties that have actually been applied
    // (does not necessarily match the requested properties)
    auto resultFormat = QOpenGLContext::globalShareContext()->format();

    // Return the format of the actually created context (may be identical to the requested one)
    if(resultingFormat != nullptr)
        *resultingFormat = resultFormat;

    auto curVersion = resultFormat.version();

    // Human-readable name of requested profile
    auto reqProfileString = profileToString(format.profile());

    // Human-readable name of current profile
    auto curProfileString = profileToString(resultFormat.profile());

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
    
    // Example: OpenGL Version 4.6 -> 46
    auto reqVersionInt = format.version().first * 10 + format.version().second;
    auto curVersionInt = curVersion.first * 10 + curVersion.second;
    
    
    // Qt Docs say: Whenever "NoProfile" is returned, either the GL version is < 3.2 or (GL >= 3.2) it is actually a core profile
    // Thus we set the following guidelines:
    // 1. Whenever the actually received GL version is < than the requested one, the context is not the one requested
    // 2. If the requested version is >= 3.2 and Compat, only Compat is allowed (as NoProfile is considered core)
    // 3. If the requested version is >= 3.2 and Core or NoProfile is requested, Compat is not allowed
    
    
    // For >= 3.2, treat Core and NoProfile equally
    bool reqCoreOrNoProfile = format.profile() == QSurfaceFormat::NoProfile || format.profile() == QSurfaceFormat::CoreProfile;
    bool curCoreOrNoProfile = resultFormat.profile() == QSurfaceFormat::NoProfile || resultFormat.profile() == QSurfaceFormat::CoreProfile;
        
    if(curVersionInt < 32 && resultFormat.profile() == QSurfaceFormat::CoreProfile)
    {
        std::cerr << "Warning: Got an OpenGL core context with OpengGL version < 3.2 (" << curVersion.first << "." << curVersion.second << ")! This should not be possible." << std::endl;
        return false;
    }
    
    // Check whether the conditions above are met.
561
    // If not, print some error to the console
562 563
    if(curVersionInt < reqVersionInt ||
       (reqVersionInt >= 32 && reqCoreOrNoProfile != curCoreOrNoProfile))
564 565 566 567 568 569 570 571 572 573 574
    {
        std::cout << "[OpenGL context] Requested: "
                  << format.version().first << "." << format.version().second << " (" << reqProfileString << ")"
                  << ", Actually created: "
                  << curVersion.first << "." << curVersion.second << " (" << curProfileString << ")"
                  << std::endl;
        return false;
    }

    std::cout << "[OpenGL context] Successfully created OpenGL context with version " << curVersion.first << "."
              << curVersion.second << " (" << curProfileString << ")." << std::endl;
575 576 577 578
    if(resultFormat.profile() == QSurfaceFormat::NoProfile || curVersionInt < 32)
    {
        std::cout << "[OpenGL context] Note that 'NoProfile' is fine for OpenGL version < 3.2 as core profile was introduced in 3.2" << std::endl;
    }
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612

    return true;
}

// Create a QSurfaceFormat from the most important properties like version and profile
QSurfaceFormat createFormat(QSurfaceFormat::OpenGLContextProfile _profile, int _glMajor, int _glMinor, int _multisamplingSamples, bool _stereo, bool _debugContext)
{
    QSurfaceFormat format;
    format.setVersion(_glMajor, _glMinor);
    format.setProfile(_profile);
    format.setSamples(_multisamplingSamples);
    format.setStereo(_stereo);
    if(_profile != QSurfaceFormat::CoreProfile)
        format.setOption(QSurfaceFormat::DeprecatedFunctions);
    if (_debugContext)
        format.setOption(format.options() | QSurfaceFormat::DebugContext);

    return format;
}

// This method tries to find the best possible OpenGL context format in the following order:
// 1. The profile/format requested via the settings
// 2. A 4.4 compatibility context (should contain all relevant GL functions)
// 3. A 3.2 core context (best choice e.g. on MacOS)
// 4. Return whatever context was applied instead of the requested ones
QSurfaceFormat getContextFormat()
{
    auto reqProfile = OpenFlipper::Options::coreProfile() ? QSurfaceFormat::CoreProfile : QSurfaceFormat::CompatibilityProfile;
    QPair<int,int> reqVersion = OpenFlipper::Options::glVersion();
    auto reqSamples = OpenFlipper::Options::samples();
    auto reqStereo = OpenFlipper::Options::glStereo();
    bool debugContext = OpenFlipper::Options::debug();


613

614
    /*
615
    // Debug: test all (possible and impossible) OpenGL versions and profiles and exit
616 617 618 619 620 621 622 623 624 625
    for(int majo = 1; majo < 5; ++majo)
        for(int mino = 0; mino < 10; ++mino)
    {
        std::cout << "========== " << majo << "." << mino << " ==========="<<std::endl;
        verifySpecificContextFormat(createFormat(QSurfaceFormat::CoreProfile, majo, mino, reqSamples, reqStereo, debugContext));
        verifySpecificContextFormat(createFormat(QSurfaceFormat::CompatibilityProfile, majo, mino, reqSamples, reqStereo, debugContext));
        verifySpecificContextFormat(createFormat(QSurfaceFormat::NoProfile, majo, mino, reqSamples, reqStereo, debugContext));
        std::cout << "================================" << std::endl;
        std::cout << std::endl;
    }
626
    exit(0);
627 628 629
    */


630

631 632 633 634 635 636 637 638 639 640 641
    QSurfaceFormat resultFormat;


    std::cout << "[OpenGL context] Trying to create a " << reqVersion.first << "." << reqVersion.second << " " << profileToString(reqProfile) << " context (default from settings)..." << std::endl;
    bool success = verifySpecificContextFormat(createFormat(reqProfile, reqVersion.first, reqVersion.second, reqSamples, reqStereo, debugContext), &resultFormat);

    // If that did not work...
    if(!success)
    {
        std::cout << "[OpenGL context] Trying to create a 4.4 compat context..." << std::endl;
        success = verifySpecificContextFormat(createFormat(QSurfaceFormat::CompatibilityProfile, 4, 4, reqSamples, reqStereo, debugContext), &resultFormat);
642
        
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
        if(!success)
        {
            std::cout << "[OpenGL context] Trying to create a 3.2 core context..." << std::endl;
            success = verifySpecificContextFormat(createFormat(QSurfaceFormat::CoreProfile, 3, 2, reqSamples, reqStereo, debugContext), &resultFormat);
            if(!success)
            {
                std::cerr << "[OpenGL context] Warning: Could not create any of the requested GL contexts." << std::endl;
                std::cerr << "[OpenGL context] The following context (proposed by the graphics driver) will be created:"  << std::endl;
                std::cerr << "[OpenGL context] Profile: " << profileToString(resultFormat.profile()) << ", Version: "
                          << resultFormat.version().first << "." << resultFormat.version().second << std::endl;
                std::cerr << "[OpenGL context] Please consider setting a supported OpenGL version and profile in the Options dialog." << std::endl;
            }
        }
    }

    return resultFormat;
}

}

Dirk Wilden's avatar
Dirk Wilden committed
663 664
int main(int argc, char **argv)
{
665

666 667
  // Remove -psn_0_xxxxx argument which is automatically
  // attached by MacOSX
Mike Kremer's avatar
 
Mike Kremer committed
668
  for (int i = 0; i < argc; i++) {
669 670 671 672 673
    if(strlen(argv[i]) > 4) {
      if( ( (argv[i])[0] == '-' ) &&
        ( (argv[i])[1] == 'p' ) &&
        ( (argv[i])[2] == 's' ) &&
        ( (argv[i])[3] == 'n' ) ) {
Jan Möbius's avatar
Jan Möbius committed
674 675
        argc--;
        argv[i] = (char *)"";
676 677 678
      }
    }
  }
Jan Möbius's avatar
Jan Möbius committed
679

Dirk Wilden's avatar
Dirk Wilden committed
680 681 682
  OpenFlipper::Options::argc(&argc);
  OpenFlipper::Options::argv(&argv);

683 684 685 686
  // Set organization and application names
  QCoreApplication::setOrganizationName("rwth-aachen.de");
  QCoreApplication::setApplicationName(TOSTRING(PRODUCT_STRING));
  QCoreApplication::setApplicationVersion(OpenFlipper::Options::coreVersion());
Dirk Wilden's avatar
Dirk Wilden committed
687

688 689 690 691
  // initialize a core application to check for commandline parameters
  QCoreApplication* coreApp = new QCoreApplication(argc, argv);

  OpenFlipper::Options::initializeSettings();
692 693 694

  QCommandLineParser parser;
  QString errorMessage;
Dirk Wilden's avatar
Dirk Wilden committed
695

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
  // parse command line options
  switch (parseCommandLine(parser, &errorMessage)) {
  case CommandLineOk:
	  break;
  case CommandLineError:
	  fputs(qPrintable(errorMessage), stderr);
	  fputs("\n\n", stderr);
	  fputs(qPrintable(parser.helpText()), stderr);
	  return 1;
  case CommandLineVersionRequested:
	  printf("%s %s\n", qPrintable(QCoreApplication::applicationName()),
		  qPrintable(QCoreApplication::applicationVersion()));
	  return 0;
  case CommandLineHelpRequested:
	  parser.showHelp();
	  Q_UNREACHABLE();
  }

  // only one application is allowed so delete the core application
  // once cmdline parsing is done
  delete coreApp;



720 721 722 723
#ifdef WIN32
  //attach a console if necessary
  attachConsole();
#endif
Dirk Wilden's avatar
Dirk Wilden committed
724

725
#ifndef NO_CATCH_SIGSEGV
Dirk Wilden's avatar
Dirk Wilden committed
726 727
  // Set a handler for segfaults
  std::signal(SIGSEGV, segfaultHandling);
728
#endif
Dirk Wilden's avatar
Dirk Wilden committed
729

Jan Möbius's avatar
Jan Möbius committed
730
  OpenFlipper::Options::windowTitle(TOSTRING(PRODUCT_STRING)" v" + OpenFlipper::Options::coreVersion());
731

Jan Möbius's avatar
 
Jan Möbius committed
732
  if ( !OpenFlipper::Options::nogui() ) {
733

Jan Möbius's avatar
 
Jan Möbius committed
734
    // OpenGL check
735
    QApplication::setAttribute(Qt::AA_ShareOpenGLContexts);
Jan Möbius's avatar
 
Jan Möbius committed
736
    QApplication::setColorSpec( QApplication::CustomColor );
737

738 739
    // Try creating a valid OpenGL context
    /******************************/
740

741 742
    // Get a valid context format
    QSurfaceFormat resultFormat = getContextFormat();
743

744 745 746 747 748
    // Set temporary(!) OpenGL settings
    OpenFlipper::Options::samples(resultFormat.samples(), true);
    OpenFlipper::Options::glStereo(resultFormat.stereo(), true);
    OpenFlipper::Options::glVersion(resultFormat.version(), true);
    OpenFlipper::Options::coreProfile(resultFormat.profile() == QSurfaceFormat::CoreProfile, true);
749

750 751
    // Create the actual context
    QSurfaceFormat::setDefaultFormat(resultFormat);
752
    QApplication app(argc, argv);
753 754 755
    QOffscreenSurface *surface = new QOffscreenSurface();
    surface->create();

756
    // Make the globally shared OpenGLContext current
757
    QOpenGLContext::globalShareContext()->makeCurrent(surface);
758
    /******************************/
759 760


761
    // Check whether there is OpenGL support. If not, return.
Jan Möbius's avatar
 
Jan Möbius committed
762 763 764 765
    if ( !QGLFormat::hasOpenGL() ) {
      std::cerr << "This system has no OpenGL support.\n";
      return -1;
    }
766

767
#ifndef __APPLE__
Jan Möbius's avatar
 
Jan Möbius committed
768
    glutInit(&argc,argv);
769
#endif
770

Jan Möbius's avatar
 
Jan Möbius committed
771 772
    // create core ( this also reads the ini files )
    Core * w = new Core( );
773

774
    QString tLang = OpenFlipperSettings().value("Core/Language/Translation","en_US").toString();
775 776 777 778

    if (tLang == "locale")
      tLang = QLocale::system().name();

779 780
    // Install translator for qt internals
    QTranslator qtTranslator;
Jan Möbius's avatar
Jan Möbius committed
781
    qtTranslator.load("qt_" + tLang, QLibraryInfo::location(QLibraryInfo::TranslationsPath));
782 783 784
    app.installTranslator(&qtTranslator);
    
    // install translator for Core Application
Dirk Wilden's avatar
Dirk Wilden committed
785 786 787 788 789 790 791 792 793 794 795 796
    QString translationDir = OpenFlipper::Options::translationsDirStr() + QDir::separator();
    QDir dir(translationDir);
    dir.setFilter(QDir::Files);

    QFileInfoList list = dir.entryInfoList();

    for (int i = 0; i < list.size(); ++i) {
      QFileInfo fileInfo = list.at(i);

      if ( fileInfo.baseName().contains(tLang) ){
        QTranslator* myAppTranslator = new QTranslator();

schultz's avatar
schultz committed
797 798
        if ( myAppTranslator->load( fileInfo.filePath() ) )
        {    
Dirk Wilden's avatar
Dirk Wilden committed
799
          app.installTranslator(myAppTranslator);
schultz's avatar
schultz committed
800 801 802
        } else 
        {
  	        delete myAppTranslator;
Dirk Wilden's avatar
Dirk Wilden committed
803 804 805
        }
      }
     }
Jan's avatar
Jan committed
806 807 808 809

    #ifndef __APPLE__
    initGlew();
    #endif
810 811 812 813

    // After setting all Options from command line, build the real gui
    w->init();

814 815 816 817 818
    const QStringList positionalArguments = parser.positionalArguments();

    for ( auto file: positionalArguments ) {
      w->commandLineOpen(file, openPolyMeshes);
    }
819

Jan Möbius's avatar
 
Jan Möbius committed
820
    return app.exec();
821

Jan Möbius's avatar
 
Jan Möbius committed
822
  } else {
823

Jan Möbius's avatar
 
Jan Möbius committed
824
    QCoreApplication app(argc,argv);
825

Jan Möbius's avatar
 
Jan Möbius committed
826 827
    // create widget ( this also reads the ini files )
    Core * w = new Core( );
828

Jan Möbius's avatar
 
Jan Möbius committed
829 830
    // After setting all Options from command line, build the real gui
    w->init();
831

832 833 834 835 836
    const QStringList positionalArguments = parser.positionalArguments();

    for ( auto file: positionalArguments ) {
      w->commandLineOpen(file, openPolyMeshes);
    }
837

Dirk Wilden's avatar
Dirk Wilden committed
838
    return app.exec();
Jan Möbius's avatar
 
Jan Möbius committed
839 840 841 842
  }

  return 0;
}