main.cpp 12 KB

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