main.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. #include <FreeImage.h>
  2. #include <GL/glew.h>
  3. #include <GLFW/glfw3.h>
  4. #include <SDL.h>
  5. #include <SDL_mixer.h>
  6. #include <csignal>
  7. #include <filesystem>
  8. #include <getopt.h>
  9. #include <iostream>
  10. #include <libgen.h>
  11. #include <stdlib.h>
  12. #include <sys/stat.h>
  13. #include <unistd.h>
  14. #include "WallpaperEngine/Core/CProject.h"
  15. #include "WallpaperEngine/Render/CRenderContext.h"
  16. #include "WallpaperEngine/Render/CVideo.h"
  17. #include "WallpaperEngine/Render/CWallpaper.h"
  18. #include "WallpaperEngine/Assets/CPackage.h"
  19. #include "WallpaperEngine/Assets/CDirectory.h"
  20. #include "WallpaperEngine/Assets/CVirtualContainer.h"
  21. #include "WallpaperEngine/Assets/CCombinedContainer.h"
  22. #include "WallpaperEngine/Assets/CPackageLoadException.h"
  23. #include "WallpaperEngine/Render/Drivers/COpenGLDriver.h"
  24. #include "Steam/FileSystem/FileSystem.h"
  25. #include "common.h"
  26. #define WORKSHOP_APP_ID 431960
  27. #define APP_DIRECTORY "wallpaper_engine"
  28. float g_Time;
  29. float g_TimeLast;
  30. bool g_KeepRunning = true;
  31. int g_AudioVolume = 15;
  32. void print_help (const char* route)
  33. {
  34. sLog.out ("Usage: ", route, " [options] background_path/background_id");
  35. sLog.out ("");
  36. sLog.out ("where background_path/background_id can be:");
  37. sLog.out ("\tthe ID of the background (for autodetection on your steam installation)");
  38. sLog.out ("\ta full path to the background's folder");
  39. sLog.out ("");
  40. sLog.out ("options:");
  41. sLog.out ("\t--silent\t\t\t\t\tMutes all the sound the wallpaper might produce");
  42. sLog.out ("\t--volume <amount>\t\t\tSets the volume for all the sounds in the background");
  43. sLog.out ("\t--screen-root <screen name>\tDisplay as screen's background");
  44. sLog.out ("\t--fps <maximum-fps>\t\t\tLimits the FPS to the given number, useful to keep battery consumption low");
  45. sLog.out ("\t--assets-dir <path>\t\t\tFolder where the assets are stored");
  46. sLog.out ("\t--screenshot\t\t\t\tTakes a screenshot of the background");
  47. sLog.out ("\t--list-properties\t\t\tList all the available properties and their possible values");
  48. sLog.out ("\t--set-property <name=value>\tOverrides the default value of the given property");
  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. void addPkg (CCombinedContainer* containers, const std::filesystem::path& path, std::string pkgfile)
  67. {
  68. try
  69. {
  70. auto scene_path = std::filesystem::path (path) / pkgfile;
  71. // add the package to the list
  72. containers->add (new WallpaperEngine::Assets::CPackage (scene_path));
  73. sLog.out ("Detected ", pkgfile, " file at ", scene_path, ". Adding to list of searchable paths");
  74. }
  75. catch (CPackageLoadException& ex)
  76. {
  77. // ignore this error, the package file was not found
  78. sLog.out ("No ", pkgfile, " file found at ", path, ". Defaulting to normal folder storage");
  79. }
  80. catch (std::runtime_error& ex)
  81. {
  82. // the package was found but there was an error loading it (wrong header or something)
  83. sLog.exception ("Failed to load scene.pkg file: ", ex.what());
  84. }
  85. }
  86. CVirtualContainer* buildVirtualContainer ()
  87. {
  88. CVirtualContainer* container = new WallpaperEngine::Assets::CVirtualContainer ();
  89. //
  90. // Had to get a little creative with the effects to achieve the same bloom effect without any custom code
  91. // these virtual files are loaded by an image in the scene that takes current _rt_FullFrameBuffer and
  92. // applies the bloom effect to render it out to the screen
  93. //
  94. // add the effect file for screen bloom
  95. container->add (
  96. "effects/wpenginelinux/bloomeffect.json",
  97. "{"
  98. "\t\"name\":\"camerabloom_wpengine_linux\","
  99. "\t\"group\":\"wpengine_linux_camera\","
  100. "\t\"dependencies\":[],"
  101. "\t\"passes\":"
  102. "\t["
  103. "\t\t{"
  104. "\t\t\t\"material\": \"materials/util/downsample_quarter_bloom.json\","
  105. "\t\t\t\"target\": \"_rt_4FrameBuffer\","
  106. "\t\t\t\"bind\":"
  107. "\t\t\t["
  108. "\t\t\t\t{"
  109. "\t\t\t\t\t\"name\": \"_rt_FullFrameBuffer\","
  110. "\t\t\t\t\t\"index\": 0"
  111. "\t\t\t\t}"
  112. "\t\t\t]"
  113. "\t\t},"
  114. "\t\t{"
  115. "\t\t\t\"material\": \"materials/util/downsample_eighth_blur_v.json\","
  116. "\t\t\t\"target\": \"_rt_8FrameBuffer\","
  117. "\t\t\t\"bind\":"
  118. "\t\t\t["
  119. "\t\t\t\t{"
  120. "\t\t\t\t\t\"name\": \"_rt_4FrameBuffer\","
  121. "\t\t\t\t\t\"index\": 0"
  122. "\t\t\t\t}"
  123. "\t\t\t]"
  124. "\t\t},"
  125. "\t\t{"
  126. "\t\t\t\"material\": \"materials/util/blur_h_bloom.json\","
  127. "\t\t\t\"target\": \"_rt_Bloom\","
  128. "\t\t\t\"bind\":"
  129. "\t\t\t["
  130. "\t\t\t\t{"
  131. "\t\t\t\t\t\"name\": \"_rt_8FrameBuffer\","
  132. "\t\t\t\t\t\"index\": 0"
  133. "\t\t\t\t}"
  134. "\t\t\t]"
  135. "\t\t},"
  136. "\t\t{"
  137. "\t\t\t\"material\": \"materials/util/combine.json\","
  138. "\t\t\t\"target\": \"_rt_FullFrameBuffer\","
  139. "\t\t\t\"bind\":"
  140. "\t\t\t["
  141. "\t\t\t\t{"
  142. "\t\t\t\t\t\"name\": \"_rt_imageLayerComposite_-1_a\","
  143. "\t\t\t\t\t\"index\": 0"
  144. "\t\t\t\t},"
  145. "\t\t\t\t{"
  146. "\t\t\t\t\t\"name\": \"_rt_Bloom\","
  147. "\t\t\t\t\t\"index\": 1"
  148. "\t\t\t\t}"
  149. "\t\t\t]"
  150. "\t\t}"
  151. "\t]"
  152. "}"
  153. );
  154. // add some model for the image element even if it's going to waste rendering cycles
  155. container->add (
  156. "models/wpenginelinux.json",
  157. "{"
  158. "\t\"material\":\"materials/wpenginelinux.json\""
  159. "}"
  160. );
  161. // models require materials, so add that too
  162. container->add (
  163. "materials/wpenginelinux.json",
  164. "{"
  165. "\t\"passes\":"
  166. "\t\t["
  167. "\t\t\t{"
  168. "\t\t\t\t\"blending\": \"normal\","
  169. "\t\t\t\t\"cullmode\": \"nocull\","
  170. "\t\t\t\t\"depthtest\": \"disabled\","
  171. "\t\t\t\t\"depthwrite\": \"disabled\","
  172. "\t\t\t\t\"shader\": \"genericimage2\","
  173. "\t\t\t\t\"textures\": [\"_rt_FullFrameBuffer\"]"
  174. "\t\t\t}"
  175. "\t\t]"
  176. "}"
  177. );
  178. return container;
  179. }
  180. void takeScreenshot (WallpaperEngine::Render::CWallpaper* wp, const std::filesystem::path& filename, FREE_IMAGE_FORMAT format)
  181. {
  182. GLint width, height;
  183. // bind texture and get the size
  184. glBindFramebuffer (GL_FRAMEBUFFER, wp->getWallpaperFramebuffer ());
  185. glBindTexture (GL_TEXTURE_2D, wp->getWallpaperTexture ());
  186. glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
  187. glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height);
  188. // make room for storing the pixel data
  189. uint8_t* buffer = new uint8_t [width * height * sizeof (uint8_t) * 3];
  190. uint8_t* pixel = buffer;
  191. // read the image into the buffer
  192. glReadPixels (0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, buffer);
  193. // build the output file with FreeImage
  194. FIBITMAP* bitmap = FreeImage_Allocate (width, height, 24);
  195. RGBQUAD color;
  196. // now get access to the pixels
  197. for (int y = height; y > 0; y --)
  198. {
  199. for (int x = 0; x < width; x ++)
  200. {
  201. color.rgbRed = *pixel ++;
  202. color.rgbGreen = *pixel ++;
  203. color.rgbBlue = *pixel ++;
  204. // set the pixel in the destination
  205. FreeImage_SetPixelColor (bitmap, x, y, &color);
  206. }
  207. }
  208. // finally save the file
  209. FreeImage_Save (format, bitmap, filename.c_str (), 0);
  210. // free all the used memory
  211. delete[] buffer;
  212. FreeImage_Unload (bitmap);
  213. // unbind the textures
  214. glBindTexture (GL_TEXTURE_2D, GL_NONE);
  215. }
  216. void initLogging ()
  217. {
  218. sLog.addOutput (new std::ostream (std::cout.rdbuf ()));
  219. sLog.addError (new std::ostream (std::cerr.rdbuf ()));
  220. }
  221. int main (int argc, char* argv[])
  222. {
  223. initLogging ();
  224. std::vector <std::string> screens;
  225. std::map <std::string, std::string> propertyOverrides;
  226. int maximumFPS = 30;
  227. bool shouldEnableAudio = true;
  228. bool shouldTakeScreenshot = false;
  229. bool shouldListPropertiesAndStop = false;
  230. FREE_IMAGE_FORMAT screenshotFormat = FIF_UNKNOWN;
  231. std::string path;
  232. std::filesystem::path assetsPath;
  233. std::filesystem::path screenshotPath;
  234. static struct option long_options [] = {
  235. {"screen-root", required_argument, 0, 'r'},
  236. {"pkg", required_argument, 0, 'p'},
  237. {"dir", required_argument, 0, 'd'},
  238. {"silent", no_argument, 0, 's'},
  239. {"volume", required_argument, 0, 'v'},
  240. {"help", no_argument, 0, 'h'},
  241. {"fps", required_argument, 0, 'f'},
  242. {"assets-dir", required_argument, 0, 'a'},
  243. {"screenshot", required_argument, 0, 'c'},
  244. {"list-properties", no_argument, 0, 'l'},
  245. {"set-property", required_argument, 0, 'o'},
  246. {nullptr, 0, 0, 0}
  247. };
  248. while (true)
  249. {
  250. int c = getopt_long (argc, argv, "r:p:d:shf:a:", long_options, nullptr);
  251. if (c == -1)
  252. break;
  253. switch (c)
  254. {
  255. case 'o':
  256. {
  257. std::string value = optarg;
  258. std::string::size_type equals = value.find ('=');
  259. // properties without value are treated as booleans for now
  260. if (equals == std::string::npos)
  261. propertyOverrides.insert_or_assign (value, "1");
  262. else
  263. propertyOverrides.insert_or_assign (
  264. value.substr (0, equals),
  265. value.substr (equals + 1)
  266. );
  267. }
  268. break;
  269. case 'l':
  270. shouldListPropertiesAndStop = true;
  271. break;
  272. case 'r':
  273. screens.emplace_back (optarg);
  274. break;
  275. case 'p':
  276. case 'd':
  277. sLog.error ("--dir/--pkg is deprecated and not used anymore");
  278. path = stringPathFixes (optarg);
  279. break;
  280. case 's':
  281. shouldEnableAudio = false;
  282. break;
  283. case 'h':
  284. print_help (argv [0]);
  285. break;
  286. case 'f':
  287. maximumFPS = atoi (optarg);
  288. break;
  289. case 'a': assetsPath = optarg;
  290. break;
  291. case 'v':
  292. g_AudioVolume = atoi (optarg);
  293. break;
  294. case 'c':
  295. shouldTakeScreenshot = true;
  296. screenshotPath = stringPathFixes (optarg);
  297. break;
  298. }
  299. }
  300. if (path.empty () == true)
  301. {
  302. if (optind < argc && strlen (argv [optind]) > 0)
  303. {
  304. path = argv [optind];
  305. }
  306. else
  307. {
  308. print_help (argv [0]);
  309. return 0;
  310. }
  311. }
  312. // validate screenshot file just to make sure
  313. if (shouldTakeScreenshot == true)
  314. {
  315. if (screenshotPath.has_extension () == false)
  316. sLog.exception ("Cannot determine screenshot format");
  317. std::string extension = screenshotPath.extension ();
  318. if (extension == ".bmp")
  319. screenshotFormat = FIF_BMP;
  320. else if (extension == ".png")
  321. screenshotFormat = FIF_PNG;
  322. else if (extension == ".jpg" || extension == ".jpeg")
  323. screenshotFormat = FIF_JPEG;
  324. else
  325. sLog.exception ("Cannot determine screenshot format, unknown extension ", extension);
  326. }
  327. // check if the background might be an ID and try to find the right path in the steam installation folder
  328. if (path.find ('/') == std::string::npos)
  329. path = Steam::FileSystem::workshopDirectory (WORKSHOP_APP_ID, path);
  330. WallpaperEngine::Assets::CCombinedContainer containers;
  331. // the background's path is required to load project.json regardless of the type of background we're using
  332. containers.add (new WallpaperEngine::Assets::CDirectory (path));
  333. // add the virtual container for mocked up files
  334. containers.add (buildVirtualContainer ());
  335. // try to add the common packages
  336. addPkg (&containers, path, "scene.pkg");
  337. addPkg (&containers, path, "gifscene.pkg");
  338. if (assetsPath.empty () == true)
  339. {
  340. try
  341. {
  342. assetsPath = Steam::FileSystem::appDirectory (APP_DIRECTORY, "assets");
  343. }
  344. catch (std::runtime_error)
  345. {
  346. // set current path as assets' folder
  347. std::filesystem::path directory = std::filesystem::canonical ("/proc/self/exe")
  348. .parent_path () / "assets";
  349. }
  350. }
  351. else
  352. {
  353. sLog.out ("Found wallpaper engine's assets at ", assetsPath, " based on --assets-dir parameter");
  354. }
  355. if (assetsPath.empty () == true)
  356. sLog.exception ("Cannot determine a valid path for the wallpaper engine assets");
  357. // add containers to the list
  358. containers.add (new WallpaperEngine::Assets::CDirectory (assetsPath));
  359. // parse the project.json file
  360. auto project = WallpaperEngine::Core::CProject::fromFile ("project.json", &containers);
  361. // go to the right folder so the videos will play
  362. if (project->getWallpaper ()->is <WallpaperEngine::Core::CVideo> () == true)
  363. chdir (path.c_str ());
  364. // show properties if required
  365. for (auto cur : project->getProperties ())
  366. {
  367. // update the value of the property
  368. auto override = propertyOverrides.find (cur->getName ());
  369. if (override != propertyOverrides.end ())
  370. {
  371. sLog.out ("Applying override value for ", cur->getName ());
  372. cur->update (override->second);
  373. }
  374. if (shouldListPropertiesAndStop)
  375. sLog.out (cur->dump ());
  376. }
  377. // halt if the list-properties option was specified
  378. if (shouldListPropertiesAndStop)
  379. return 0;
  380. // attach signals so if a stop is requested the X11 resources are freed and the program shutsdown gracefully
  381. std::signal(SIGINT, signalhandler);
  382. std::signal(SIGTERM, signalhandler);
  383. if (shouldEnableAudio == true && SDL_Init (SDL_INIT_AUDIO) < 0)
  384. {
  385. sLog.error ("Cannot initialize SDL audio system, SDL_GetError: ", SDL_GetError());
  386. sLog.error ("Continuing without audio support");
  387. }
  388. // initialize OpenGL driver
  389. WallpaperEngine::Render::Drivers::COpenGLDriver videoDriver ("Wallpaper Engine");
  390. // initialize custom context class
  391. WallpaperEngine::Render::CRenderContext context (screens, videoDriver, &containers);
  392. // initialize mouse support
  393. context.setMouse (new CMouseInput (videoDriver.getWindow ()));
  394. // ensure the context knows what wallpaper to render
  395. context.setWallpaper (
  396. WallpaperEngine::Render::CWallpaper::fromWallpaper (project->getWallpaper (), &context)
  397. );
  398. // update maximum FPS if it's a video
  399. if (context.getWallpaper ()->is <WallpaperEngine::Render::CVideo> () == true)
  400. maximumFPS = context.getWallpaper ()->as <WallpaperEngine::Render::CVideo> ()->getFPS ();
  401. float startTime, endTime, minimumTime = 1.0f / maximumFPS;
  402. while (videoDriver.closeRequested () == false && g_KeepRunning == true)
  403. {
  404. // keep track of the previous frame's time
  405. g_TimeLast = g_Time;
  406. // calculate the current time value
  407. g_Time = videoDriver.getRenderTime ();
  408. // get the start time of the frame
  409. startTime = g_Time;
  410. // render the scene
  411. context.render ();
  412. // get the end time of the frame
  413. endTime = videoDriver.getRenderTime ();
  414. // ensure the frame time is correct to not overrun FPS
  415. if ((endTime - startTime) < minimumTime)
  416. usleep ((minimumTime - (endTime - startTime)) * CLOCKS_PER_SEC);
  417. if (shouldTakeScreenshot == true && videoDriver.getFrameCounter () == 5)
  418. {
  419. takeScreenshot (context.getWallpaper (), screenshotPath, screenshotFormat);
  420. // disable screenshot just in case the counter overflows
  421. shouldTakeScreenshot = false;
  422. }
  423. }
  424. // ensure this is updated as sometimes it might not come from a signal
  425. g_KeepRunning = false;
  426. sLog.out ("Stop requested");
  427. // terminate SDL
  428. SDL_QuitSubSystem(SDL_INIT_AUDIO);
  429. SDL_Quit ();
  430. return 0;
  431. }