3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include <IrrlichtDevice.h>
22 #include "fontengine.h"
25 #include "util/numeric.h"
26 #include "guiscalingfilter.h"
27 #include "localplayer.h"
28 #include "client/hud.h"
31 #include "clientmap.h"
32 #include "renderingengine.h"
33 #include "render/core.h"
34 #include "render/factory.h"
35 #include "inputhandler.h"
37 #include "../gui/guiSkin.h"
39 #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \
40 !defined(SERVER) && !defined(__HAIKU__)
45 #include <X11/Xutil.h>
46 #include <X11/Xatom.h>
58 RenderingEngine *RenderingEngine::s_singleton = nullptr;
59 const float RenderingEngine::BASE_BLOOM_STRENGTH = 8.0f;
62 static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment,
63 gui::EGUI_SKIN_TYPE type, video::IVideoDriver *driver)
65 gui::GUISkin *skin = new gui::GUISkin(type, driver);
67 gui::IGUIFont *builtinfont = environment->getBuiltInFont();
68 gui::IGUIFontBitmap *bitfont = nullptr;
69 if (builtinfont && builtinfont->getType() == gui::EGFT_BITMAP)
70 bitfont = (gui::IGUIFontBitmap*)builtinfont;
72 gui::IGUISpriteBank *bank = 0;
73 skin->setFont(builtinfont);
76 bank = bitfont->getSpriteBank();
78 skin->setSpriteBank(bank);
84 RenderingEngine::RenderingEngine(IEventReceiver *receiver)
86 sanity_check(!s_singleton);
88 // Resolution selection
89 bool fullscreen = g_settings->getBool("fullscreen");
91 u16 screen_w = 0, screen_h = 0;
93 u16 screen_w = std::max<u16>(g_settings->getU16("screen_w"), 1);
94 u16 screen_h = std::max<u16>(g_settings->getU16("screen_h"), 1);
98 bool vsync = g_settings->getBool("vsync");
99 u16 fsaa = g_settings->getU16("fsaa");
101 // stereo buffer required for pageflip stereo
102 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
105 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
106 const std::string &driverstring = g_settings->get("video_driver");
107 std::vector<video::E_DRIVER_TYPE> drivers =
108 RenderingEngine::getSupportedVideoDrivers();
110 for (i = 0; i != drivers.size(); i++) {
111 if (!strcasecmp(driverstring.c_str(),
112 RenderingEngine::getVideoDriverInfo(drivers[i]).name.c_str())) {
113 driverType = drivers[i];
117 if (i == drivers.size()) {
118 errorstream << "Invalid video_driver specified; "
119 "defaulting to opengl"
123 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
125 params.LoggingLevel = irr::ELL_DEBUG;
126 params.DriverType = driverType;
127 params.WindowSize = core::dimension2d<u32>(screen_w, screen_h);
128 params.AntiAlias = fsaa;
129 params.Fullscreen = fullscreen;
130 params.Stencilbuffer = false;
131 params.Stereobuffer = stereo_buffer;
132 params.Vsync = vsync;
133 params.EventReceiver = receiver;
134 params.HighPrecisionFPU = true;
136 params.PrivateData = porting::app_global;
139 // there is no standardized path for these on desktop
140 std::string rel_path = std::string("client") + DIR_DELIM
141 + "shaders" + DIR_DELIM + "Irrlicht";
142 params.OGLES2ShaderPath = (porting::path_share + DIR_DELIM + rel_path + DIR_DELIM).c_str();
145 m_device = createDeviceEx(params);
146 driver = m_device->getVideoDriver();
150 auto skin = createSkin(m_device->getGUIEnvironment(),
151 gui::EGST_WINDOWS_METALLIC, driver);
152 m_device->getGUIEnvironment()->setSkin(skin);
156 RenderingEngine::~RenderingEngine()
159 m_device->closeDevice();
160 s_singleton = nullptr;
163 v2u32 RenderingEngine::_getWindowSize() const
166 return core->getVirtualSize();
167 return m_device->getVideoDriver()->getScreenSize();
170 void RenderingEngine::setResizable(bool resize)
172 m_device->setResizable(resize);
175 void RenderingEngine::removeMesh(const scene::IMesh* mesh)
177 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
180 void RenderingEngine::cleanupMeshCache()
182 auto mesh_cache = m_device->getSceneManager()->getMeshCache();
183 while (mesh_cache->getMeshCount() != 0) {
184 if (scene::IAnimatedMesh *mesh = mesh_cache->getMeshByIndex(0))
185 mesh_cache->removeMesh(mesh);
189 bool RenderingEngine::setupTopLevelWindow(const std::string &name)
191 // FIXME: It would make more sense for there to be a switch of some
192 // sort here that would call the correct toplevel setup methods for
193 // the environment Minetest is running in.
195 /* Setting Xorg properties for the top level window */
196 setupTopLevelXorgWindow(name);
198 /* Setting general properties for the top level window */
199 verbosestream << "Client: Configuring general top level"
200 << " window properties"
202 bool result = setWindowIcon();
207 void RenderingEngine::setupTopLevelXorgWindow(const std::string &name)
210 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
212 Display *x11_dpl = reinterpret_cast<Display *>(exposedData.OpenGLLinux.X11Display);
213 if (x11_dpl == NULL) {
214 warningstream << "Client: Could not find X11 Display in ExposedVideoData"
219 verbosestream << "Client: Configuring X11-specific top level"
220 << " window properties"
224 Window x11_win = reinterpret_cast<Window>(exposedData.OpenGLLinux.X11Window);
226 // Set application name and class hints. For now name and class are the same.
227 XClassHint *classhint = XAllocClassHint();
228 classhint->res_name = const_cast<char *>(name.c_str());
229 classhint->res_class = const_cast<char *>(name.c_str());
231 XSetClassHint(x11_dpl, x11_win, classhint);
234 // FIXME: In the future WMNormalHints should be set ... e.g see the
235 // gtk/gdk code (gdk/x11/gdksurface-x11.c) for the setup_top_level
236 // method. But for now (as it would require some significant changes)
237 // leave the code as is.
239 // The following is borrowed from the above gdk source for setting top
240 // level windows. The source indicates and the Xlib docs suggest that
241 // this will set the WM_CLIENT_MACHINE and WM_LOCAL_NAME. This will not
242 // set the WM_CLIENT_MACHINE to a Fully Qualified Domain Name (FQDN) which is
243 // required by the Extended Window Manager Hints (EWMH) spec when setting
244 // the _NET_WM_PID (see further down) but running Minetest in an env
245 // where the window manager is on another machine from Minetest (therefore
246 // making the PID useless) is not expected to be a problem. Further
247 // more, using gtk/gdk as the model it would seem that not using a FQDN is
248 // not an issue for modern Xorg window managers.
250 verbosestream << "Client: Setting Xorg window manager Properties"
253 XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL);
255 // Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID
256 // (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to
257 // force a shutdown of an application if it doesn't respond to the destroy
260 verbosestream << "Client: Setting Xorg _NET_WM_PID extended window manager property"
263 Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false);
265 pid_t pid = getpid();
267 XChangeProperty(x11_dpl, x11_win, NET_WM_PID,
268 XA_CARDINAL, 32, PropModeReplace,
269 reinterpret_cast<unsigned char *>(&pid),1);
271 // Set the WM_CLIENT_LEADER window property here. Minetest has only one
272 // window and that window will always be the leader.
274 verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property"
277 Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false);
279 XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER,
280 XA_WINDOW, 32, PropModeReplace,
281 reinterpret_cast<unsigned char *>(&x11_win), 1);
286 static bool getWindowHandle(irr::video::IVideoDriver *driver, HWND &hWnd)
288 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
290 switch (driver->getDriverType()) {
292 case video::EDT_OGLES1:
293 case video::EDT_OGLES2:
295 case video::EDT_OPENGL:
296 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
306 bool RenderingEngine::setWindowIcon()
308 #if defined(XORG_USED)
310 return setXorgWindowIconFromPath(
311 porting::path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
313 // We have semi-support for reading in-place data if we are
314 // compiled with RUN_IN_PLACE. Don't break with this and
315 // also try the path_share location.
316 return setXorgWindowIconFromPath(
317 ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") ||
318 setXorgWindowIconFromPath(porting::path_share + "/misc/" PROJECT_NAME
319 "-xorg-icon-128.png");
321 #elif defined(_WIN32)
322 HWND hWnd; // Window handle
323 if (!getWindowHandle(driver, hWnd))
326 // Load the ICON from resource file
327 const HICON hicon = LoadIcon(GetModuleHandle(NULL),
328 MAKEINTRESOURCE(130) // The ID of the ICON defined in
333 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
334 SendMessage(hWnd, WM_SETICON, ICON_SMALL,
335 reinterpret_cast<LPARAM>(hicon));
344 bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file)
348 video::IImageLoader *image_loader = NULL;
349 u32 cnt = driver->getImageLoaderCount();
350 for (u32 i = 0; i < cnt; i++) {
351 if (driver->getImageLoader(i)->isALoadableFileExtension(
352 icon_file.c_str())) {
353 image_loader = driver->getImageLoader(i);
359 warningstream << "Could not find image loader for file '" << icon_file
364 io::IReadFile *icon_f =
365 m_device->getFileSystem()->createAndOpenFile(icon_file.c_str());
368 warningstream << "Could not load icon file '" << icon_file << "'"
373 video::IImage *img = image_loader->loadImage(icon_f);
376 warningstream << "Could not load icon file '" << icon_file << "'"
382 u32 height = img->getDimension().Height;
383 u32 width = img->getDimension().Width;
385 size_t icon_buffer_len = 2 + height * width;
386 long *icon_buffer = new long[icon_buffer_len];
388 icon_buffer[0] = width;
389 icon_buffer[1] = height;
391 for (u32 x = 0; x < width; x++) {
392 for (u32 y = 0; y < height; y++) {
393 video::SColor col = img->getPixel(x, y);
395 pixel_val |= (u8)col.getAlpha() << 24;
396 pixel_val |= (u8)col.getRed() << 16;
397 pixel_val |= (u8)col.getGreen() << 8;
398 pixel_val |= (u8)col.getBlue();
399 icon_buffer[2 + x + y * width] = pixel_val;
406 const video::SExposedVideoData &video_data = driver->getExposedVideoData();
408 Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
410 if (x11_dpl == NULL) {
411 warningstream << "Could not find x11 display for setting its icon."
413 delete[] icon_buffer;
417 Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
419 Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
420 Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
421 XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace,
422 (const unsigned char *)icon_buffer, icon_buffer_len);
424 delete[] icon_buffer;
431 Draws a screen with a single text on it.
432 Text will be removed when the screen is drawn the next time.
433 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
435 void RenderingEngine::draw_load_screen(const std::wstring &text,
436 gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime,
437 int percent, bool clouds)
439 v2u32 screensize = getWindowSize();
441 v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight());
442 v2s32 center(screensize.X / 2, screensize.Y / 2);
443 core::rect<s32> textrect(center - textsize / 2, center + textsize / 2);
445 gui::IGUIStaticText *guitext =
446 guienv->addStaticText(text.c_str(), textrect, false, false);
447 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
449 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
450 if (cloud_menu_background) {
451 g_menuclouds->step(dtime * 3);
452 g_menuclouds->render();
453 get_video_driver()->beginScene(
454 true, true, video::SColor(255, 140, 186, 250));
455 g_menucloudsmgr->drawAll();
457 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
460 if ((percent >= 0) && (percent <= 100)) {
461 video::ITexture *progress_img = tsrc->getTexture("progress_bar.png");
462 video::ITexture *progress_img_bg =
463 tsrc->getTexture("progress_bar_bg.png");
465 if (progress_img && progress_img_bg) {
467 const core::dimension2d<u32> &img_size =
468 progress_img_bg->getSize();
469 u32 imgW = rangelim(img_size.Width, 200, 600) * getDisplayDensity();
470 u32 imgH = rangelim(img_size.Height, 24, 72) * getDisplayDensity();
472 const core::dimension2d<u32> img_size(256, 48);
473 float imgRatio = (float)img_size.Height / img_size.Width;
474 u32 imgW = screensize.X / 2.2f;
475 u32 imgH = floor(imgW * imgRatio);
477 v2s32 img_pos((screensize.X - imgW) / 2,
478 (screensize.Y - imgH) / 2);
480 draw2DImageFilterScaled(get_video_driver(), progress_img_bg,
481 core::rect<s32>(img_pos.X, img_pos.Y,
484 core::rect<s32>(0, 0, img_size.Width,
488 draw2DImageFilterScaled(get_video_driver(), progress_img,
489 core::rect<s32>(img_pos.X, img_pos.Y,
490 img_pos.X + (percent * imgW) / 100,
492 core::rect<s32>(0, 0,
493 (percent * img_size.Width) / 100,
500 get_video_driver()->endScene();
505 Draws the menu scene including (optional) cloud background.
507 void RenderingEngine::draw_menu_scene(gui::IGUIEnvironment *guienv,
508 float dtime, bool clouds)
510 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
511 if (cloud_menu_background) {
512 g_menuclouds->step(dtime * 3);
513 g_menuclouds->render();
514 get_video_driver()->beginScene(
515 true, true, video::SColor(255, 140, 186, 250));
516 g_menucloudsmgr->drawAll();
518 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
521 get_video_driver()->endScene();
524 std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers()
526 // Only check these drivers.
527 // We do not support software and D3D in any capacity.
528 static const irr::video::E_DRIVER_TYPE glDrivers[4] = {
529 irr::video::EDT_NULL,
530 irr::video::EDT_OPENGL,
531 irr::video::EDT_OGLES1,
532 irr::video::EDT_OGLES2,
534 std::vector<irr::video::E_DRIVER_TYPE> drivers;
536 for (int i = 0; i < 4; i++) {
537 if (irr::IrrlichtDevice::isDriverSupported(glDrivers[i]))
538 drivers.push_back(glDrivers[i]);
544 void RenderingEngine::initialize(Client *client, Hud *hud)
546 const std::string &draw_mode = g_settings->get("3d_mode");
547 core.reset(createRenderingCore(draw_mode, m_device, client, hud));
551 void RenderingEngine::finalize()
556 void RenderingEngine::draw_scene(video::SColor skycolor, bool show_hud,
557 bool show_minimap, bool draw_wield_tool, bool draw_crosshair)
559 core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair);
562 const VideoDriverInfo &RenderingEngine::getVideoDriverInfo(irr::video::E_DRIVER_TYPE type)
564 static const std::unordered_map<int, VideoDriverInfo> driver_info_map = {
565 {(int)video::EDT_NULL, {"null", "NULL Driver"}},
566 {(int)video::EDT_OPENGL, {"opengl", "OpenGL"}},
567 {(int)video::EDT_OGLES1, {"ogles1", "OpenGL ES1"}},
568 {(int)video::EDT_OGLES2, {"ogles2", "OpenGL ES2"}},
570 return driver_info_map.at((int)type);
574 #if defined(XORG_USED)
576 static float calcDisplayDensity()
578 const char *current_display = getenv("DISPLAY");
580 if (current_display != NULL) {
581 Display *x11display = XOpenDisplay(current_display);
583 if (x11display != NULL) {
585 int dh = DisplayHeight(x11display, 0);
586 int dw = DisplayWidth(x11display, 0);
587 int dh_mm = DisplayHeightMM(x11display, 0);
588 int dw_mm = DisplayWidthMM(x11display, 0);
589 XCloseDisplay(x11display);
591 if (dh_mm != 0 && dw_mm != 0) {
592 float dpi_height = floor(dh / (dh_mm * 0.039370) + 0.5);
593 float dpi_width = floor(dw / (dw_mm * 0.039370) + 0.5);
594 return std::max(dpi_height, dpi_width) / 96.0;
599 /* return manually specified dpi */
600 return g_settings->getFloat("screen_dpi") / 96.0;
603 float RenderingEngine::getDisplayDensity()
605 static float cached_display_density = calcDisplayDensity();
606 return std::max(cached_display_density * g_settings->getFloat("display_density_factor"), 0.5f);
609 #elif defined(_WIN32)
612 static float calcDisplayDensity(irr::video::IVideoDriver *driver)
615 if (getWindowHandle(driver, hWnd)) {
616 HDC hdc = GetDC(hWnd);
617 float dpi = GetDeviceCaps(hdc, LOGPIXELSX);
618 ReleaseDC(hWnd, hdc);
622 /* return manually specified dpi */
623 return g_settings->getFloat("screen_dpi") / 96.0f;
626 float RenderingEngine::getDisplayDensity()
628 static bool cached = false;
629 static float display_density;
631 display_density = calcDisplayDensity(get_video_driver());
634 return std::max(display_density * g_settings->getFloat("display_density_factor"), 0.5f);
639 float RenderingEngine::getDisplayDensity()
641 return std::max(g_settings->getFloat("screen_dpi") / 96.0f *
642 g_settings->getFloat("display_density_factor"), 0.5f);
648 float RenderingEngine::getDisplayDensity()
650 return porting::getDisplayDensity();
653 #endif // __ANDROID__