main.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. #include <iostream>
  2. #include <getopt.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <SDL_mixer.h>
  6. #include <SDL.h>
  7. #include <FreeImage.h>
  8. #include <sys/stat.h>
  9. #include <GL/glew.h>
  10. #include <csignal>
  11. #include <GLFW/glfw3.h>
  12. #include <libgen.h>
  13. #include "WallpaperEngine/Core/CProject.h"
  14. #include "WallpaperEngine/Render/CRenderContext.h"
  15. #include "WallpaperEngine/Render/CVideo.h"
  16. #include "WallpaperEngine/Render/CWallpaper.h"
  17. #include "WallpaperEngine/Assets/CPackage.h"
  18. #include "WallpaperEngine/Assets/CDirectory.h"
  19. #include "WallpaperEngine/Assets/CVirtualContainer.h"
  20. #include "WallpaperEngine/Assets/CCombinedContainer.h"
  21. #include "WallpaperEngine/Assets/CPackageLoadException.h"
  22. #include "common.h"
  23. float g_Time;
  24. float g_TimeLast;
  25. bool g_KeepRunning = true;
  26. int g_AudioVolume = 15;
  27. const char* assets_default_paths [] = {
  28. ".steam/steam/steamapps/common/wallpaper_engine/assets",
  29. ".local/share/Steam/steamapps/common/wallpaper_engine/assets",
  30. nullptr
  31. };
  32. const char* backgrounds_default_paths [] = {
  33. ".local/share/Steam/steamapps/workshop/content/431960",
  34. ".steam/steam/steamapps/workshop/content/431960",
  35. nullptr
  36. };
  37. void print_help (const char* route)
  38. {
  39. sLog.out ("Usage: ", route, " [options] background_path/background_id");
  40. sLog.out ("");
  41. sLog.out ("where background_path/background_id can be:");
  42. sLog.out ("\tthe ID of the background (for autodetection on your steam installation)");
  43. sLog.out ("\ta full path to the background's folder");
  44. sLog.out ("");
  45. sLog.out ("options:");
  46. sLog.out ("\t--silent\t\t\t\t\tMutes all the sound the wallpaper might produce");
  47. sLog.out ("\t--volume <amount>\t\t\tSets the volume for all the sounds in the background");
  48. sLog.out ("\t--screen-root <screen name>\tDisplay as screen's background");
  49. sLog.out ("\t--fps <maximum-fps>\t\t\tLimits the FPS to the given number, useful to keep battery consumption low");
  50. sLog.out ("\t--assets-dir <path>\t\t\tFolder where the assets are stored");
  51. sLog.out ("\t--screenshot\t\t\t\tTakes a screenshot of the background");
  52. sLog.out ("\t--list-properties\t\t\tList all the available properties and their possible values");
  53. sLog.out ("\t--set-property <name=value>\tOverrides the default value of the given property");
  54. }
  55. std::string stringPathFixes(const std::string& s)
  56. {
  57. if (s.empty () == true)
  58. return s;
  59. std::string str (s);
  60. // remove single-quotes from the arguments
  61. if (str [0] == '\'' && str [str.size() - 1] == '\'')
  62. str
  63. .erase (str.size() - 1, 1)
  64. .erase (0, 1);
  65. return std::move (str);
  66. }
  67. void signalhandler(int sig)
  68. {
  69. g_KeepRunning = false;
  70. }
  71. int handleValidatePath (const char* path, std::string& final)
  72. {
  73. char finalPath [PATH_MAX];
  74. char* pointer = realpath (path, finalPath);
  75. if (pointer == nullptr)
  76. return errno;
  77. // ensure the path points to a folder
  78. struct stat pathinfo;
  79. if (stat (finalPath, &pathinfo) != 0)
  80. return errno;
  81. if (!S_ISDIR (pathinfo.st_mode))
  82. return ENOTDIR;
  83. final = finalPath;
  84. return 0;
  85. }
  86. void validatePath(const char* path, std::string& final)
  87. {
  88. int error = handleValidatePath (path, final);
  89. switch (error)
  90. {
  91. case ENOTDIR:
  92. sLog.exception ("Invalid directory, ", path, " is not a folder");
  93. break;
  94. case ENAMETOOLONG:
  95. sLog.exception ("Path ", path, " too long");
  96. break;
  97. case 0:
  98. return;
  99. default:
  100. sLog.exception ("Cannot find the specified folder");
  101. break;
  102. }
  103. }
  104. std::string getHomePath ()
  105. {
  106. char* home = getenv ("HOME");
  107. if (home == nullptr)
  108. sLog.exception ("Cannot find home directory for the current user");
  109. std::string homepath;
  110. validatePath (home, homepath);
  111. return homepath;
  112. }
  113. void initGLFW ()
  114. {
  115. // first of all, initialize the window
  116. if (glfwInit () == GLFW_FALSE)
  117. sLog.exception ("Failed to initialize GLFW");
  118. // initialize freeimage
  119. FreeImage_Initialise (TRUE);
  120. // set some window hints (opengl version to be used)
  121. glfwWindowHint (GLFW_SAMPLES, 4);
  122. glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3);
  123. glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 3);
  124. glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  125. if (DEBUG)
  126. glfwWindowHint (GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
  127. }
  128. void addPkg (CCombinedContainer* containers, const std::string& path, std::string pkgfile)
  129. {
  130. try
  131. {
  132. std::string scene_path = path + pkgfile;
  133. // add the package to the list
  134. containers->add (new WallpaperEngine::Assets::CPackage (scene_path));
  135. sLog.out ("Detected ", pkgfile, " file at ", scene_path, ". Adding to list of searchable paths");
  136. }
  137. catch (CPackageLoadException& ex)
  138. {
  139. // ignore this error, the package file was not found
  140. sLog.out ("No ", pkgfile, " file found at ", path, ". Defaulting to normal folder storage");
  141. }
  142. catch (std::runtime_error& ex)
  143. {
  144. // the package was found but there was an error loading it (wrong header or something)
  145. sLog.exception ("Failed to load scene.pkg file: ", ex.what());
  146. }
  147. }
  148. CVirtualContainer* buildVirtualContainer ()
  149. {
  150. CVirtualContainer* container = new WallpaperEngine::Assets::CVirtualContainer ();
  151. //
  152. // Had to get a little creative with the effects to achieve the same bloom effect without any custom code
  153. // these virtual files are loaded by an image in the scene that takes current _rt_FullFrameBuffer and
  154. // applies the bloom effect to render it out to the screen
  155. //
  156. // add the effect file for screen bloom
  157. container->add (
  158. "effects/wpenginelinux/bloomeffect.json",
  159. "{"
  160. "\t\"name\":\"camerabloom_wpengine_linux\","
  161. "\t\"group\":\"wpengine_linux_camera\","
  162. "\t\"dependencies\":[],"
  163. "\t\"passes\":"
  164. "\t["
  165. "\t\t{"
  166. "\t\t\t\"material\": \"materials/util/downsample_quarter_bloom.json\","
  167. "\t\t\t\"target\": \"_rt_4FrameBuffer\","
  168. "\t\t\t\"bind\":"
  169. "\t\t\t["
  170. "\t\t\t\t{"
  171. "\t\t\t\t\t\"name\": \"_rt_FullFrameBuffer\","
  172. "\t\t\t\t\t\"index\": 0"
  173. "\t\t\t\t}"
  174. "\t\t\t]"
  175. "\t\t},"
  176. "\t\t{"
  177. "\t\t\t\"material\": \"materials/util/downsample_eighth_blur_v.json\","
  178. "\t\t\t\"target\": \"_rt_8FrameBuffer\","
  179. "\t\t\t\"bind\":"
  180. "\t\t\t["
  181. "\t\t\t\t{"
  182. "\t\t\t\t\t\"name\": \"_rt_4FrameBuffer\","
  183. "\t\t\t\t\t\"index\": 0"
  184. "\t\t\t\t}"
  185. "\t\t\t]"
  186. "\t\t},"
  187. "\t\t{"
  188. "\t\t\t\"material\": \"materials/util/blur_h_bloom.json\","
  189. "\t\t\t\"target\": \"_rt_Bloom\","
  190. "\t\t\t\"bind\":"
  191. "\t\t\t["
  192. "\t\t\t\t{"
  193. "\t\t\t\t\t\"name\": \"_rt_8FrameBuffer\","
  194. "\t\t\t\t\t\"index\": 0"
  195. "\t\t\t\t}"
  196. "\t\t\t]"
  197. "\t\t},"
  198. "\t\t{"
  199. "\t\t\t\"material\": \"materials/util/combine.json\","
  200. "\t\t\t\"target\": \"_rt_FullFrameBuffer\","
  201. "\t\t\t\"bind\":"
  202. "\t\t\t["
  203. "\t\t\t\t{"
  204. "\t\t\t\t\t\"name\": \"_rt_imageLayerComposite_-1_a\","
  205. "\t\t\t\t\t\"index\": 0"
  206. "\t\t\t\t},"
  207. "\t\t\t\t{"
  208. "\t\t\t\t\t\"name\": \"_rt_Bloom\","
  209. "\t\t\t\t\t\"index\": 1"
  210. "\t\t\t\t}"
  211. "\t\t\t]"
  212. "\t\t}"
  213. "\t]"
  214. "}"
  215. );
  216. // add some model for the image element even if it's going to waste rendering cycles
  217. container->add (
  218. "models/wpenginelinux.json",
  219. "{"
  220. "\t\"material\":\"materials/wpenginelinux.json\""
  221. "}"
  222. );
  223. // models require materials, so add that too
  224. container->add (
  225. "materials/wpenginelinux.json",
  226. "{"
  227. "\t\"passes\":"
  228. "\t\t["
  229. "\t\t\t{"
  230. "\t\t\t\t\"blending\": \"normal\","
  231. "\t\t\t\t\"cullmode\": \"nocull\","
  232. "\t\t\t\t\"depthtest\": \"disabled\","
  233. "\t\t\t\t\"depthwrite\": \"disabled\","
  234. "\t\t\t\t\"shader\": \"genericimage2\","
  235. "\t\t\t\t\"textures\": [\"_rt_FullFrameBuffer\"]"
  236. "\t\t\t}"
  237. "\t\t]"
  238. "}"
  239. );
  240. return container;
  241. }
  242. void takeScreenshot (WallpaperEngine::Render::CWallpaper* wp, const std::string& filename, FREE_IMAGE_FORMAT format)
  243. {
  244. GLint width, height;
  245. // bind texture and get the size
  246. glBindFramebuffer (GL_FRAMEBUFFER, wp->getWallpaperFramebuffer ());
  247. glBindTexture (GL_TEXTURE_2D, wp->getWallpaperTexture ());
  248. glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
  249. glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height);
  250. // make room for storing the pixel data
  251. uint8_t* buffer = new uint8_t [width * height * sizeof (uint8_t) * 3];
  252. uint8_t* pixel = buffer;
  253. // read the image into the buffer
  254. glReadPixels (0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
  255. // build the output file with FreeImage
  256. FIBITMAP* bitmap = FreeImage_Allocate (width, height, 24);
  257. RGBQUAD color;
  258. // now get access to the pixels
  259. for (int y = height; y > 0; y --)
  260. {
  261. for (int x = 0; x < width; x ++)
  262. {
  263. color.rgbRed = *pixel ++;
  264. color.rgbGreen = *pixel ++;
  265. color.rgbBlue = *pixel ++;
  266. // set the pixel in the destination
  267. FreeImage_SetPixelColor (bitmap, x, y, &color);
  268. }
  269. }
  270. // finally save the file
  271. FreeImage_Save (format, bitmap, filename.c_str (), 0);
  272. // free all the used memory
  273. delete[] buffer;
  274. FreeImage_Unload (bitmap);
  275. // unbind the textures
  276. glBindTexture (GL_TEXTURE_2D, GL_NONE);
  277. }
  278. void initLogging ()
  279. {
  280. sLog.addOutput (new std::ostream (std::cout.rdbuf ()));
  281. sLog.addError (new std::ostream (std::cerr.rdbuf ()));
  282. }
  283. int main (int argc, char* argv[])
  284. {
  285. initLogging ();
  286. std::vector <std::string> screens;
  287. std::map <std::string, std::string> propertyOverrides;
  288. int maximumFPS = 30;
  289. bool shouldEnableAudio = true;
  290. bool shouldTakeScreenshot = false;
  291. bool shouldListPropertiesAndStop = false;
  292. FREE_IMAGE_FORMAT screenshotFormat = FIF_UNKNOWN;
  293. std::string path;
  294. std::string assetsDir;
  295. std::string screenshotPath;
  296. static struct option long_options [] = {
  297. {"screen-root", required_argument, 0, 'r'},
  298. {"pkg", required_argument, 0, 'p'},
  299. {"dir", required_argument, 0, 'd'},
  300. {"silent", no_argument, 0, 's'},
  301. {"volume", required_argument, 0, 'v'},
  302. {"help", no_argument, 0, 'h'},
  303. {"fps", required_argument, 0, 'f'},
  304. {"assets-dir", required_argument, 0, 'a'},
  305. {"screenshot", required_argument, 0, 'c'},
  306. {"list-properties", no_argument, 0, 'l'},
  307. {"set-property", required_argument, 0, 'o'},
  308. {nullptr, 0, 0, 0}
  309. };
  310. while (true)
  311. {
  312. int c = getopt_long (argc, argv, "r:p:d:shf:a:", long_options, nullptr);
  313. if (c == -1)
  314. break;
  315. switch (c)
  316. {
  317. case 'o':
  318. {
  319. std::string value = optarg;
  320. std::string::size_type equals = value.find ('=');
  321. // properties without value are treated as booleans for now
  322. if (equals == std::string::npos)
  323. propertyOverrides.insert_or_assign (value, "1");
  324. else
  325. propertyOverrides.insert_or_assign (
  326. value.substr (0, equals),
  327. value.substr (equals + 1)
  328. );
  329. }
  330. break;
  331. case 'l':
  332. shouldListPropertiesAndStop = true;
  333. break;
  334. case 'r':
  335. screens.emplace_back (optarg);
  336. break;
  337. case 'p':
  338. case 'd':
  339. sLog.error ("--dir/--pkg is deprecated and not used anymore");
  340. path = stringPathFixes (optarg);
  341. break;
  342. case 's':
  343. shouldEnableAudio = false;
  344. break;
  345. case 'h':
  346. print_help (argv [0]);
  347. break;
  348. case 'f':
  349. maximumFPS = atoi (optarg);
  350. break;
  351. case 'a':
  352. assetsDir = optarg;
  353. break;
  354. case 'v':
  355. g_AudioVolume = atoi (optarg);
  356. break;
  357. case 'c':
  358. shouldTakeScreenshot = true;
  359. screenshotPath = stringPathFixes (optarg);
  360. break;
  361. }
  362. }
  363. if (path.empty () == true)
  364. {
  365. if (optind < argc && strlen (argv [optind]) > 0)
  366. {
  367. path = argv [optind];
  368. }
  369. else
  370. {
  371. print_help (argv [0]);
  372. return 0;
  373. }
  374. }
  375. // validate screenshot file just to make sure
  376. if (shouldTakeScreenshot == true)
  377. {
  378. // ensure the file is one of the supported formats
  379. std::string extension = screenshotPath.substr (screenshotPath.find_last_of (".") + 1);
  380. if (extension == "bmp")
  381. screenshotFormat = FIF_BMP;
  382. else if (extension == "png")
  383. screenshotFormat = FIF_PNG;
  384. else if (extension == "jpg" || extension == "jpeg")
  385. screenshotFormat = FIF_JPEG;
  386. else
  387. sLog.exception ("Unsupported screenshot format ", extension);
  388. }
  389. std::string homepath = getHomePath ();
  390. auto containers = new WallpaperEngine::Assets::CCombinedContainer ();
  391. // check if the background might be an ID and try to find the right path in the steam installation folder
  392. if (path.find ('/') == std::string::npos)
  393. {
  394. for (const char** current = backgrounds_default_paths; *current != nullptr; current ++)
  395. {
  396. std::string tmppath = homepath + "/" + *current + "/" + path;
  397. int error = handleValidatePath (tmppath.c_str (), tmppath);
  398. if (error != 0)
  399. continue;
  400. path = tmppath;
  401. }
  402. }
  403. validatePath (path.c_str (), path);
  404. // add a trailing slash to the path so the right file can be found
  405. path += "/";
  406. // the background's path is required to load project.json regardless of the type of background we're using
  407. containers->add (new WallpaperEngine::Assets::CDirectory (path));
  408. // add the virtual container for mocked up files
  409. containers->add (buildVirtualContainer ());
  410. // try to add the common packages
  411. addPkg (containers, path, "scene.pkg");
  412. addPkg (containers, path, "gifscene.pkg");
  413. if (assetsDir.empty () == true)
  414. {
  415. for (const char** current = assets_default_paths; *current != nullptr; current ++)
  416. {
  417. std::string tmppath = homepath + "/" + *current;
  418. int error = handleValidatePath (tmppath.c_str (), tmppath);
  419. if (error != 0)
  420. continue;
  421. assetsDir = tmppath;
  422. sLog.out ("Found wallpaper engine's assets at ", assetsDir);
  423. break;
  424. }
  425. if (assetsDir.empty () == true)
  426. {
  427. unsigned long len = strlen (argv [0]) + 1;
  428. char* copy = new char[len];
  429. strncpy (copy, argv [0], len);
  430. // path still not found, try one last thing on the current binary's folder
  431. std::string exepath = dirname (copy);
  432. exepath += "/assets";
  433. int error = handleValidatePath (exepath.c_str (), exepath);
  434. if (error == 0)
  435. {
  436. assetsDir = exepath;
  437. sLog.out ("Found assets folder alongside the binary: ", assetsDir);
  438. }
  439. delete[] copy;
  440. }
  441. }
  442. else
  443. {
  444. validatePath (assetsDir.c_str (), assetsDir);
  445. sLog.out ("Found wallpaper engine's assets at ", assetsDir, " based on --assets-dir parameter");
  446. }
  447. if (assetsDir.empty () == true)
  448. sLog.exception ("Cannot determine a valid path for the wallpaper engine assets");
  449. // add containers to the list
  450. containers->add (new WallpaperEngine::Assets::CDirectory (assetsDir + "/"));
  451. // parse the project.json file
  452. auto project = WallpaperEngine::Core::CProject::fromFile ("project.json", containers);
  453. // go to the right folder so the videos will play
  454. if (project->getWallpaper ()->is <WallpaperEngine::Core::CVideo> () == true)
  455. chdir (path.c_str ());
  456. // show properties if required
  457. for (auto cur : project->getProperties ())
  458. {
  459. // update the value of the property
  460. auto override = propertyOverrides.find (cur->getName ());
  461. if (override != propertyOverrides.end ())
  462. {
  463. sLog.out ("Applying override value for ", cur->getName ());
  464. cur->update (override->second);
  465. }
  466. if (shouldListPropertiesAndStop)
  467. sLog.out (cur->dump ());
  468. }
  469. // halt if the list-properties option was specified
  470. if (shouldListPropertiesAndStop)
  471. return 0;
  472. // attach signals so if a stop is requested the X11 resources are freed and the program shutsdown gracefully
  473. std::signal(SIGINT, signalhandler);
  474. std::signal(SIGTERM, signalhandler);
  475. // initialize glfw
  476. initGLFW ();
  477. // auto projection = project->getWallpaper ()->as <WallpaperEngine::Core::CScene> ()->getOrthogonalProjection ();
  478. // create the window!
  479. // TODO: DO WE NEED TO PASS MONITOR HERE OR ANYTHING?
  480. // TODO: FIGURE OUT HOW TO PUT THIS WINDOW IN THE BACKGROUND
  481. GLFWwindow* window = glfwCreateWindow (1920, 1080, "WallpaperEngine", NULL, NULL);
  482. if (window == nullptr)
  483. {
  484. sLog.error ("GLFW", "Failed to open a GLFW window");
  485. glfwTerminate ();
  486. return 2;
  487. }
  488. glfwMakeContextCurrent (window);
  489. // TODO: FIGURE THESE OUT BASED ON THE SCREEN
  490. int windowWidth = 1920;
  491. int windowHeight = 1080;
  492. // get the real framebuffer size
  493. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  494. GLenum glewInitResult = glewInit ();
  495. // initialize glew
  496. if (glewInitResult != GLEW_OK)
  497. {
  498. sLog.error ("GLEW", "Failed to initialize GLEW: ", glewGetErrorString (glewInitResult));
  499. glfwTerminate ();
  500. return 3;
  501. }
  502. if (shouldEnableAudio == true && SDL_Init (SDL_INIT_AUDIO) < 0)
  503. {
  504. sLog.error ("SDL", "Cannot initialize SDL audio system, SDL_GetError: ", SDL_GetError());
  505. sLog.error ("SDL", "Continuing without audio support");
  506. }
  507. // initialize custom context class
  508. WallpaperEngine::Render::CRenderContext* context = new WallpaperEngine::Render::CRenderContext (screens, window, containers);
  509. // initialize mouse support
  510. context->setMouse (new CMouseInput (window));
  511. // set the default viewport
  512. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  513. // ensure the context knows what wallpaper to render
  514. context->setWallpaper (
  515. WallpaperEngine::Render::CWallpaper::fromWallpaper (project->getWallpaper (), context)
  516. );
  517. // update maximum FPS if it's a video
  518. if (context->getWallpaper ()->is <WallpaperEngine::Render::CVideo> () == true)
  519. maximumFPS = context->getWallpaper ()->as <WallpaperEngine::Render::CVideo> ()->getFPS ();
  520. // TODO: FIGURE OUT THE REQUIRED INPUT MODE, AS SOME WALLPAPERS USE THINGS LIKE MOUSE POSITION
  521. // glfwSetInputMode (window, GLFW_STICKY_KEYS, GL_TRUE);
  522. double startTime, endTime, minimumTime = 1.0 / maximumFPS;
  523. uint32_t frameCounter = 0;
  524. while (glfwWindowShouldClose (window) == 0 && g_KeepRunning == true)
  525. {
  526. // get the real framebuffer size
  527. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  528. // set the default viewport
  529. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  530. // keep track of the previous frame's time
  531. g_TimeLast = g_Time;
  532. // calculate the current time value
  533. g_Time = (float) glfwGetTime ();
  534. // get the start time of the frame
  535. startTime = glfwGetTime ();
  536. // render the scene
  537. context->render ();
  538. // do buffer swapping
  539. glfwSwapBuffers (window);
  540. // poll for events (like closing the window)
  541. glfwPollEvents ();
  542. // get the end time of the frame
  543. endTime = glfwGetTime ();
  544. // ensure the frame time is correct to not overrun FPS
  545. if ((endTime - startTime) < minimumTime)
  546. usleep ((minimumTime - (endTime - startTime)) * CLOCKS_PER_SEC);
  547. frameCounter ++;
  548. if (frameCounter == 5 && shouldTakeScreenshot == true)
  549. {
  550. takeScreenshot (context->getWallpaper (), screenshotPath, screenshotFormat);
  551. // disable screenshot just in case the counter overflows
  552. shouldTakeScreenshot = false;
  553. }
  554. }
  555. // ensure this is updated as sometimes it might not come from a signal
  556. g_KeepRunning = false;
  557. sLog.out ("Stop requested");
  558. // terminate gl
  559. glfwTerminate ();
  560. // terminate free image
  561. FreeImage_DeInitialise ();
  562. // terminate SDL
  563. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  564. SDL_Quit ();
  565. // free context
  566. delete context;
  567. return 0;
  568. }