main.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. #include <iostream>
  2. #include <getopt.h>
  3. #include <unistd.h>
  4. #include <SDL_mixer.h>
  5. #include <SDL.h>
  6. #include <FreeImage.h>
  7. #include <sys/stat.h>
  8. #include <GL/glew.h>
  9. #include <GL/glx.h>
  10. #include <filesystem>
  11. #include <csignal>
  12. #include "GLFW/glfw3.h"
  13. #include <X11/Xlib.h>
  14. #include <X11/Xatom.h>
  15. #include "WallpaperEngine/Core/CProject.h"
  16. #include "WallpaperEngine/Render/CWallpaper.h"
  17. #include "WallpaperEngine/Render/CContext.h"
  18. #include "WallpaperEngine/Render/CScene.h"
  19. #include "WallpaperEngine/Render/CVideo.h"
  20. #include "WallpaperEngine/Assets/CPackage.h"
  21. #include "WallpaperEngine/Assets/CDirectory.h"
  22. #include "WallpaperEngine/Assets/CCombinedContainer.h"
  23. float g_Time;
  24. using namespace WallpaperEngine::Core::Types;
  25. void print_help (const char* route)
  26. {
  27. std::cout
  28. << "Usage:" << route << " [options] background_path" << std::endl
  29. << "options:" << std::endl
  30. << " --silent\t\tMutes all the sound the wallpaper might produce" << std::endl
  31. << " --screen-root <screen name>\tDisplay as screen's background" << std::endl
  32. << " --fps <maximum-fps>\tLimits the FPS to the given number, useful to keep battery consumption low" << std::endl;
  33. }
  34. std::string stringPathFixes(const std::string& s)
  35. {
  36. if (s.empty () == true)
  37. return s;
  38. std::string str (s);
  39. // remove single-quotes from the arguments
  40. if (str [0] == '\'' && str [str.size() - 1] == '\'')
  41. str
  42. .erase (str.size() - 1, 1)
  43. .erase (0, 1);
  44. // ensure there's a slash at the end of the path
  45. if (str [str.size() - 1] != '/')
  46. str += '/';
  47. return std::move (str);
  48. }
  49. void free_display_wallpaper(int sig)
  50. {
  51. Display* display = XOpenDisplay (nullptr);
  52. Window root = DefaultRootWindow(display);
  53. // create a blank pm to reset compositors values, compositors will render as a blank X window.
  54. Pixmap pm = XCreatePixmap(display, root, 1, 1, 1);
  55. Atom prop_root = XInternAtom(display, "_XROOTPMAP_ID", False);
  56. Atom prop_esetroot = XInternAtom(display, "ESETROOT_PMAP_ID", False);
  57. XChangeProperty(display, root, prop_root, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pm, 1);
  58. XChangeProperty(display, root, prop_esetroot, XA_PIXMAP, 32, PropModeReplace, (unsigned char *) &pm, 1);
  59. XFreePixmap(display, pm);
  60. // set background to black. Only needed if no compositors are running
  61. XSetWindowBackground(display, root, 0);
  62. // sync changes before exiting
  63. XClearWindow(display, root);
  64. XFlush(display);
  65. XCloseDisplay(display);
  66. exit(sig);
  67. }
  68. int main (int argc, char* argv[])
  69. {
  70. std::vector <std::string> screens;
  71. int maximumFPS = 30;
  72. bool shouldEnableAudio = true;
  73. std::string path;
  74. static struct option long_options [] = {
  75. {"screen-root", required_argument, 0, 'r'},
  76. {"pkg", required_argument, 0, 'p'},
  77. {"dir", required_argument, 0, 'd'},
  78. {"silent", no_argument, 0, 's'},
  79. {"help", no_argument, 0, 'h'},
  80. {"fps", required_argument, 0, 'f'},
  81. {nullptr, 0, 0, 0}
  82. };
  83. while (true)
  84. {
  85. int c = getopt_long (argc, argv, "r:p:d:shf:", long_options, nullptr);
  86. if (c == -1)
  87. break;
  88. switch (c)
  89. {
  90. case 'r':
  91. screens.emplace_back (optarg);
  92. break;
  93. case 'p':
  94. case 'd':
  95. std::cerr << "--dir/--pkg is deprecated and not used anymore" << std::endl;
  96. path = stringPathFixes (optarg);
  97. break;
  98. case 's':
  99. shouldEnableAudio = false;
  100. break;
  101. case 'h':
  102. print_help (argv [0]);
  103. break;
  104. case 'f':
  105. maximumFPS = atoi (optarg);
  106. break;
  107. default:
  108. break;
  109. }
  110. }
  111. // increment the option index (useful for when no options were found)
  112. // option_index ++;
  113. if (path.empty () == true)
  114. {
  115. if (optind < argc && strlen (argv [optind]) > 0)
  116. {
  117. path = argv [optind];
  118. }
  119. else
  120. {
  121. print_help (argv [0]);
  122. return 0;
  123. }
  124. }
  125. char* finalPath = realpath(path.c_str (), nullptr);
  126. if (finalPath == nullptr)
  127. {
  128. if (errno == ENAMETOOLONG)
  129. throw std::runtime_error ("Cannot get wallpaper's folder, path is too long");
  130. else
  131. throw std::runtime_error ("Cannot find the specified folder");
  132. }
  133. // ensure the path points to a folder
  134. struct stat pathinfo;
  135. if (stat (finalPath, &pathinfo) != 0)
  136. throw std::runtime_error ("Cannot find the specified wallpaper folder");
  137. if (!S_ISDIR (pathinfo.st_mode))
  138. throw std::runtime_error ("The specified path is not a folder");
  139. // ensure the path has a trailing slash
  140. // Attach signals for unexpected killing of program by user. We need to reset the
  141. // screen otherwise the background will remain the last frame on sigterm or sigint.
  142. if (!screens.empty())
  143. {
  144. std::signal(SIGINT, free_display_wallpaper);
  145. std::signal(SIGTERM, free_display_wallpaper);
  146. }
  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. // will hide the window if we are drawing to X
  160. if (!screens.empty())
  161. glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
  162. auto containers = new WallpaperEngine::Assets::CCombinedContainer ();
  163. // update the used path with the full one
  164. path = finalPath;
  165. path += "/";
  166. // the background's path is required to load project.json regardless of the type of background we're using
  167. containers->add (new WallpaperEngine::Assets::CDirectory (path));
  168. // check if scene.pkg exists and add it to the list
  169. try
  170. {
  171. std::string scene_path = path + "scene.pkg";
  172. // add the package to the list
  173. containers->add (new WallpaperEngine::Assets::CPackage (scene_path));
  174. std::cout << "Detected scene.pkg file at " << scene_path << ". Adding to list of searchable paths" << std::endl;
  175. }
  176. catch(std::filesystem::filesystem_error ex)
  177. {
  178. // ignore this error, the package file was not found
  179. std::cout << "No scene.pkg file found at " << path << ". Defaulting to normal folder storage" << std::endl;
  180. }
  181. catch (std::runtime_error ex)
  182. {
  183. // the package was found but there was an error loading it (wrong header or something)
  184. fprintf (stderr, "Failed to load scene.pkg file: %s\n", ex.what());
  185. return 4;
  186. }
  187. // add containers to the list
  188. containers->add (new WallpaperEngine::Assets::CDirectory ("./assets/"));
  189. // parse the project.json file
  190. auto project = WallpaperEngine::Core::CProject::fromFile ("project.json", containers);
  191. WallpaperEngine::Render::CWallpaper* wallpaper;
  192. // initialize custom context class
  193. WallpaperEngine::Render::CContext* context = new WallpaperEngine::Render::CContext (screens);
  194. // auto projection = project->getWallpaper ()->as <WallpaperEngine::Core::CScene> ()->getOrthogonalProjection ();
  195. // create the window!
  196. // TODO: DO WE NEED TO PASS MONITOR HERE OR ANYTHING?
  197. // TODO: FIGURE OUT HOW TO PUT THIS WINDOW IN THE BACKGROUND
  198. GLFWwindow* window = glfwCreateWindow (1920, 1080, "WallpaperEngine", NULL, NULL);
  199. if (window == nullptr)
  200. {
  201. fprintf (stderr, "Failed to open a GLFW window");
  202. glfwTerminate ();
  203. return 2;
  204. }
  205. // initialize inputs
  206. CMouseInput* mouseInput = new CMouseInput (window);
  207. context->setMouse (mouseInput);
  208. glfwMakeContextCurrent (window);
  209. // TODO: FIGURE THESE OUT BASED ON THE SCREEN
  210. int windowWidth = 1920;
  211. int windowHeight = 1080;
  212. // get the real framebuffer size
  213. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  214. // set the default viewport
  215. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  216. if (glewInit () != GLEW_OK)
  217. {
  218. fprintf (stderr, "Failed to initialize GLEW");
  219. glfwTerminate ();
  220. return 3;
  221. }
  222. if (project->getType () == "scene")
  223. {
  224. WallpaperEngine::Core::CScene* scene = project->getWallpaper ()->as <WallpaperEngine::Core::CScene> ();
  225. wallpaper = new WallpaperEngine::Render::CScene (scene, containers, context);
  226. }
  227. else if (project->getType () == "video")
  228. {
  229. // special steps, running a video needs a root directory change, files are not loaded from the container classes
  230. // as they're streamed from disk
  231. chdir (path.c_str ());
  232. WallpaperEngine::Core::CVideo* video = project->getWallpaper ()->as <WallpaperEngine::Core::CVideo> ();
  233. wallpaper = new WallpaperEngine::Render::CVideo (video, containers, context);
  234. }
  235. else
  236. {
  237. throw std::runtime_error ("Unsupported wallpaper type");
  238. }
  239. // ensure the context knows what wallpaper to render
  240. context->setWallpaper (wallpaper);
  241. if (shouldEnableAudio == true)
  242. {
  243. int mixer_flags = MIX_INIT_MP3 | MIX_INIT_FLAC | MIX_INIT_OGG;
  244. if (SDL_Init (SDL_INIT_AUDIO) < 0 || mixer_flags != Mix_Init (mixer_flags))
  245. {
  246. // Mix_GetError is an alias for SDL_GetError, so calling it directly will yield the correct result
  247. // it doesn't matter if SDL_Init or Mix_Init failed, both report the errors through the same functions
  248. fprintf (stderr, "Cannot initialize SDL audio system, SDL_GetError: %s", SDL_GetError ());
  249. return 2;
  250. }
  251. // initialize audio engine
  252. Mix_OpenAudio (22050, AUDIO_S16SYS, 2, 640);
  253. }
  254. // TODO: FIGURE OUT THE REQUIRED INPUT MODE, AS SOME WALLPAPERS USE THINGS LIKE MOUSE POSITION
  255. // glfwSetInputMode (window, GLFW_STICKY_KEYS, GL_TRUE);
  256. // enable depth text
  257. glEnable (GL_DEPTH_TEST);
  258. glDepthFunc (GL_LESS);
  259. // cull anything that doesn't look at the camera (might be useful to disable in the future)
  260. glDisable (GL_CULL_FACE);
  261. double minimumTime = 1.0 / maximumFPS;
  262. double startTime = 0.0;
  263. double endTime = 0.0;
  264. while (glfwWindowShouldClose (window) == 0)
  265. {
  266. // get the real framebuffer size
  267. glfwGetFramebufferSize (window, &windowWidth, &windowHeight);
  268. // set the default viewport
  269. context->setDefaultViewport ({0, 0, windowWidth, windowHeight});
  270. // calculate the current time value
  271. g_Time = (float) glfwGetTime ();
  272. // get the start time of the frame
  273. startTime = glfwGetTime ();
  274. // update our inputs first
  275. mouseInput->update ();
  276. // render the scene
  277. context->render ();
  278. // do buffer swapping
  279. glfwSwapBuffers (window);
  280. // poll for events (like closing the window)
  281. glfwPollEvents ();
  282. // get the end time of the frame
  283. endTime = glfwGetTime ();
  284. // ensure the frame time is correct to not overrun FPS
  285. if ((endTime - startTime) < minimumTime)
  286. usleep ((minimumTime - (endTime - startTime)) * CLOCKS_PER_SEC);
  287. }
  288. // terminate gl
  289. glfwTerminate ();
  290. // terminate SDL
  291. SDL_Quit ();
  292. // terminate free image
  293. FreeImage_DeInitialise ();
  294. // free paths
  295. free(finalPath);
  296. return 0;
  297. }