main.cpp 20 KB

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