main.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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/CCombinedContainer.h"
  20. #include "WallpaperEngine/Assets/CPackageLoadException.h"
  21. float g_Time;
  22. bool g_KeepRunning = true;
  23. int g_AudioVolume = 15;
  24. using namespace WallpaperEngine::Core::Types;
  25. const char* assets_default_paths [] = {
  26. ".steam/steam/steamapps/common/wallpaper_engine/assets",
  27. ".local/share/Steam/steamapps/common/wallpaper_engine/assets",
  28. nullptr
  29. };
  30. const char* backgrounds_default_paths [] = {
  31. ".local/share/Steam/steamapps/workshop/content/431960",
  32. nullptr
  33. };
  34. void print_help (const char* route)
  35. {
  36. std::cout
  37. << "Usage: " << route << " [options] background_path/background_id" << std::endl
  38. << std::endl
  39. << "where background_path/background_id can be:" << std::endl
  40. << "\tthe ID of the background (for autodetection on your steam installation)" << std::endl
  41. << "\ta full path to the background's folder" << std::endl
  42. << std::endl
  43. << "options:" << std::endl
  44. << " --silent\t\tMutes all the sound the wallpaper might produce" << std::endl
  45. << " --volume <amount>\tSets the volume for all the sounds in the background" << std::endl
  46. << " --screen-root <screen name>\tDisplay as screen's background" << std::endl
  47. << " --fps <maximum-fps>\tLimits the FPS to the given number, useful to keep battery consumption low" << std::endl
  48. << " --assets-dir <path>\tFolder where the assets are stored" << std::endl;
  49. }
  50. std::string stringPathFixes(const std::string& s)
  51. {
  52. if (s.empty () == true)
  53. return s;
  54. std::string str (s);
  55. // remove single-quotes from the arguments
  56. if (str [0] == '\'' && str [str.size() - 1] == '\'')
  57. str
  58. .erase (str.size() - 1, 1)
  59. .erase (0, 1);
  60. return std::move (str);
  61. }
  62. void signalhandler(int sig)
  63. {
  64. g_KeepRunning = false;
  65. }
  66. int validatePath(const char* path, std::string& final)
  67. {
  68. char finalPath [PATH_MAX];
  69. char* pointer = realpath (path, finalPath);
  70. if (finalPath == nullptr)
  71. return errno;
  72. // ensure the path points to a folder
  73. struct stat pathinfo;
  74. if (stat (finalPath, &pathinfo) != 0)
  75. return errno;
  76. if (!S_ISDIR (pathinfo.st_mode))
  77. return ENOTDIR;
  78. final = finalPath;
  79. return 0;
  80. }
  81. std::string getHomePath ()
  82. {
  83. char* home = getenv ("HOME");
  84. if (home == nullptr)
  85. throw std::runtime_error ("$HOME doesn't exist");
  86. std::string homepath;
  87. int error = validatePath (home, homepath);
  88. if (error == ENOTDIR)
  89. throw std::runtime_error ("Invalid user home path");
  90. else if (error == ENAMETOOLONG)
  91. throw std::runtime_error ("Cannot get user's home folder, path is too long");
  92. else if (error != 0)
  93. throw std::runtime_error ("Cannot find the home folder for the user");
  94. return homepath;
  95. }
  96. void initGLFW ()
  97. {
  98. // first of all, initialize the window
  99. if (glfwInit () == GLFW_FALSE)
  100. throw std::runtime_error ("Failed to initialize GLFW");
  101. // initialize freeimage
  102. FreeImage_Initialise (TRUE);
  103. // set some window hints (opengl version to be used)
  104. glfwWindowHint (GLFW_SAMPLES, 4);
  105. glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 2);
  106. glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 1);
  107. }
  108. void addPkg (CCombinedContainer* containers, const std::string& path, std::string pkgfile)
  109. {
  110. try
  111. {
  112. std::string scene_path = path + pkgfile;
  113. // add the package to the list
  114. containers->add (new WallpaperEngine::Assets::CPackage (scene_path));
  115. std::cout << "Detected " << pkgfile << " file at " << scene_path << ". Adding to list of searchable paths" << std::endl;
  116. }
  117. catch (CPackageLoadException& ex)
  118. {
  119. // ignore this error, the package file was not found
  120. std::cout << "No " << pkgfile << " file found at " << path << ". Defaulting to normal folder storage" << std::endl;
  121. }
  122. catch (std::runtime_error& ex)
  123. {
  124. // the package was found but there was an error loading it (wrong header or something)
  125. fprintf (stderr, "Failed to load scene.pkg file: %s\n", ex.what());
  126. throw std::runtime_error ("Cannot load package file");
  127. }
  128. }
  129. int main (int argc, char* argv[])
  130. {
  131. std::vector <std::string> screens;
  132. int maximumFPS = 30;
  133. bool shouldEnableAudio = true;
  134. std::string path;
  135. std::string assetsDir;
  136. static struct option long_options [] = {
  137. {"screen-root", required_argument, 0, 'r'},
  138. {"pkg", required_argument, 0, 'p'},
  139. {"dir", required_argument, 0, 'd'},
  140. {"silent", no_argument, 0, 's'},
  141. {"volume", required_argument, 0, 'v'},
  142. {"help", no_argument, 0, 'h'},
  143. {"fps", required_argument, 0, 'f'},
  144. {"assets-dir", required_argument, 0, 'a'},
  145. {nullptr, 0, 0, 0}
  146. };
  147. while (true)
  148. {
  149. int c = getopt_long (argc, argv, "r:p:d:shf:a:", long_options, nullptr);
  150. if (c == -1)
  151. break;
  152. switch (c)
  153. {
  154. case 'r':
  155. screens.emplace_back (optarg);
  156. break;
  157. case 'p':
  158. case 'd':
  159. std::cerr << "--dir/--pkg is deprecated and not used anymore" << std::endl;
  160. path = stringPathFixes (optarg);
  161. break;
  162. case 's':
  163. shouldEnableAudio = false;
  164. break;
  165. case 'h':
  166. print_help (argv [0]);
  167. break;
  168. case 'f':
  169. maximumFPS = atoi (optarg);
  170. break;
  171. case 'a':
  172. assetsDir = optarg;
  173. break;
  174. case 'v':
  175. g_AudioVolume = atoi (optarg);
  176. break;
  177. }
  178. }
  179. if (path.empty () == true)
  180. {
  181. if (optind < argc && strlen (argv [optind]) > 0)
  182. {
  183. path = argv [optind];
  184. }
  185. else
  186. {
  187. print_help (argv [0]);
  188. return 0;
  189. }
  190. }
  191. // attach signals so if a stop is requested the X11 resources are freed and the program shutsdown gracefully
  192. std::signal(SIGINT, signalhandler);
  193. std::signal(SIGTERM, signalhandler);
  194. // initialize glfw
  195. initGLFW ();
  196. std::string homepath = getHomePath ();
  197. auto containers = new WallpaperEngine::Assets::CCombinedContainer ();
  198. // check if the background might be an ID and try to find the right path in the steam installation folder
  199. if (path.find ('/') == std::string::npos)
  200. {
  201. for (const char** current = backgrounds_default_paths; *current != nullptr; current ++)
  202. {
  203. std::string tmppath = homepath + "/" + *current + "/" + path;
  204. int error = validatePath (tmppath.c_str (), tmppath);
  205. if (error != 0)
  206. continue;
  207. path = tmppath;
  208. }
  209. }
  210. int error = validatePath (path.c_str (), path);
  211. if (error == ENOTDIR)
  212. throw std::runtime_error ("The background path is not a folder");
  213. else if (error == ENAMETOOLONG)
  214. throw std::runtime_error ("Cannot get wallpaper's folder, path is too long");
  215. else if (error != 0)
  216. throw std::runtime_error ("Cannot find the specified folder");
  217. // add a trailing slash to the path so the right file can be found
  218. path += "/";
  219. // the background's path is required to load project.json regardless of the type of background we're using
  220. containers->add (new WallpaperEngine::Assets::CDirectory (path));
  221. // try to add the common packages
  222. addPkg (containers, path, "scene.pkg");
  223. addPkg (containers, path, "gifscene.pkg");
  224. if (assetsDir.empty () == true)
  225. {
  226. for (const char** current = assets_default_paths; *current != nullptr; current ++)
  227. {
  228. std::string tmppath = homepath + "/" + *current;
  229. error = validatePath (tmppath.c_str (), tmppath);
  230. if (error != 0)
  231. continue;
  232. assetsDir = tmppath;
  233. std::cout << "Found wallpaper engine's assets at " << assetsDir << std::endl;
  234. break;
  235. }
  236. if (assetsDir.empty () == true)
  237. {
  238. unsigned long len = strlen (argv [0]) + 1;
  239. char* copy = new char[len];
  240. strncpy (copy, argv [0], len);
  241. // path still not found, try one last thing on the current binary's folder
  242. std::string exepath = dirname (copy);
  243. exepath += "/assets";
  244. error = validatePath (exepath.c_str (), exepath);
  245. if (error == 0)
  246. {
  247. assetsDir = exepath;
  248. std::cout << "Found assets folder alongside the binary: " << assetsDir << std::endl;
  249. }
  250. delete[] copy;
  251. }
  252. }
  253. else
  254. {
  255. error = validatePath (assetsDir.c_str (), assetsDir);
  256. if (error == ENOTDIR)
  257. throw std::runtime_error ("Invalid assets folder");
  258. else if (error == ENAMETOOLONG)
  259. throw std::runtime_error ("Cannot get assets folder, path is too long");
  260. else if (error != 0)
  261. throw std::runtime_error ("Cannot find the specified assets folder");
  262. std::cout << "Found wallpaper engine's assets at " << assetsDir << " based on --assets-dir parameter" << std::endl;
  263. }
  264. if (assetsDir.empty () == true)
  265. throw std::runtime_error ("Cannot determine a valid path for the wallpaper engine assets");
  266. // add containers to the list
  267. containers->add (new WallpaperEngine::Assets::CDirectory (assetsDir + "/"));
  268. // auto projection = project->getWallpaper ()->as <WallpaperEngine::Core::CScene> ()->getOrthogonalProjection ();
  269. // create the window!
  270. // TODO: DO WE NEED TO PASS MONITOR HERE OR ANYTHING?
  271. // TODO: FIGURE OUT HOW TO PUT THIS WINDOW IN THE BACKGROUND
  272. GLFWwindow* window = glfwCreateWindow (1920, 1080, "WallpaperEngine", NULL, NULL);
  273. if (window == nullptr)
  274. {
  275. fprintf (stderr, "Failed to open a GLFW window");
  276. glfwTerminate ();
  277. return 2;
  278. }
  279. glfwMakeContextCurrent (window);
  280. // TODO: FIGURE THESE OUT BASED ON THE SCREEN
  281. int windowWidth = 1920;
  282. int windowHeight = 1080;
  283. // get the real framebuffer size
  284. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  285. // initialize glew
  286. if (glewInit () != GLEW_OK)
  287. {
  288. fprintf (stderr, "Failed to initialize GLEW");
  289. glfwTerminate ();
  290. return 3;
  291. }
  292. if (shouldEnableAudio == true && SDL_Init (SDL_INIT_AUDIO) < 0)
  293. {
  294. std::cerr << "Cannot initialize SDL audio system, SDL_GetError: " << SDL_GetError() << std::endl;
  295. std::cerr << "Continuing without audio support" << std::endl;
  296. }
  297. // parse the project.json file
  298. auto project = WallpaperEngine::Core::CProject::fromFile ("project.json", containers);
  299. // go to the right folder so the videos will play
  300. if (project->getWallpaper ()->is <WallpaperEngine::Core::CVideo> () == true)
  301. chdir (path.c_str ());
  302. // initialize custom context class
  303. WallpaperEngine::Render::CContext* context = new WallpaperEngine::Render::CContext (screens, window);
  304. // initialize mouse support
  305. context->setMouse (new CMouseInput (window));
  306. // set the default viewport
  307. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  308. // ensure the context knows what wallpaper to render
  309. context->setWallpaper (
  310. WallpaperEngine::Render::CWallpaper::fromWallpaper (project->getWallpaper (), containers, context)
  311. );
  312. // update maximum FPS if it's a video
  313. if (context->getWallpaper ()->is <WallpaperEngine::Render::CVideo> () == true)
  314. maximumFPS = context->getWallpaper ()->as <WallpaperEngine::Render::CVideo> ()->getFPS ();
  315. // TODO: FIGURE OUT THE REQUIRED INPUT MODE, AS SOME WALLPAPERS USE THINGS LIKE MOUSE POSITION
  316. // glfwSetInputMode (window, GLFW_STICKY_KEYS, GL_TRUE);
  317. double startTime, endTime, minimumTime = 1.0 / maximumFPS;
  318. while (glfwWindowShouldClose (window) == 0 && g_KeepRunning == true)
  319. {
  320. // get the real framebuffer size
  321. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  322. // set the default viewport
  323. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  324. // calculate the current time value
  325. g_Time = (float) glfwGetTime ();
  326. // get the start time of the frame
  327. startTime = glfwGetTime ();
  328. // render the scene
  329. context->render ();
  330. // do buffer swapping
  331. glfwSwapBuffers (window);
  332. // poll for events (like closing the window)
  333. glfwPollEvents ();
  334. // get the end time of the frame
  335. endTime = glfwGetTime ();
  336. // ensure the frame time is correct to not overrun FPS
  337. if ((endTime - startTime) < minimumTime)
  338. usleep ((minimumTime - (endTime - startTime)) * CLOCKS_PER_SEC);
  339. }
  340. // ensure this is updated as sometimes it might not come from a signal
  341. g_KeepRunning = false;
  342. std::cout << "Stop requested" << std::endl;
  343. // terminate gl
  344. glfwTerminate ();
  345. // terminate free image
  346. FreeImage_DeInitialise ();
  347. // terminate SDL
  348. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  349. SDL_Quit ();
  350. // free context
  351. delete context;
  352. return 0;
  353. }