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>
23 #include "fontengine.h"
26 #include "util/numeric.h"
27 #include "guiscalingfilter.h"
28 #include "localplayer.h"
29 #include "client/hud.h"
32 #include "clientmap.h"
33 #include "renderingengine.h"
34 #include "render/core.h"
35 #include "render/factory.h"
36 #include "inputhandler.h"
38 #include "../gui/guiSkin.h"
40 #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \
41 !defined(SERVER) && !defined(__HAIKU__)
46 #include <X11/Xutil.h>
47 #include <X11/Xatom.h>
59 RenderingEngine *RenderingEngine::s_singleton = nullptr;
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");
90 u16 screen_w = g_settings->getU16("screen_w");
91 u16 screen_h = g_settings->getU16("screen_h");
94 bool vsync = g_settings->getBool("vsync");
95 u16 bits = g_settings->getU16("fullscreen_bpp");
96 u16 fsaa = g_settings->getU16("fsaa");
98 // stereo buffer required for pageflip stereo
99 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
102 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
103 const std::string &driverstring = g_settings->get("video_driver");
104 std::vector<video::E_DRIVER_TYPE> drivers =
105 RenderingEngine::getSupportedVideoDrivers();
107 for (i = 0; i != drivers.size(); i++) {
108 if (!strcasecmp(driverstring.c_str(),
109 RenderingEngine::getVideoDriverName(drivers[i]))) {
110 driverType = drivers[i];
114 if (i == drivers.size()) {
115 errorstream << "Invalid video_driver specified; "
116 "defaulting to opengl"
120 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
121 params.DriverType = driverType;
122 params.WindowSize = core::dimension2d<u32>(screen_w, screen_h);
124 params.AntiAlias = fsaa;
125 params.Fullscreen = fullscreen;
126 params.Stencilbuffer = false;
127 params.Stereobuffer = stereo_buffer;
128 params.Vsync = vsync;
129 params.EventReceiver = receiver;
130 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
131 params.ZBufferBits = 24;
133 params.PrivateData = porting::app_global;
136 // there is no standardized path for these on desktop
137 std::string rel_path = std::string("client") + DIR_DELIM
138 + "shaders" + DIR_DELIM + "Irrlicht";
139 params.OGLES2ShaderPath = (porting::path_share + DIR_DELIM + rel_path + DIR_DELIM).c_str();
142 m_device = createDeviceEx(params);
143 driver = m_device->getVideoDriver();
147 auto skin = createSkin(m_device->getGUIEnvironment(),
148 gui::EGST_WINDOWS_METALLIC, driver);
149 m_device->getGUIEnvironment()->setSkin(skin);
153 RenderingEngine::~RenderingEngine()
157 s_singleton = nullptr;
160 v2u32 RenderingEngine::getWindowSize() const
163 return core->getVirtualSize();
164 return m_device->getVideoDriver()->getScreenSize();
167 void RenderingEngine::setResizable(bool resize)
169 m_device->setResizable(resize);
172 bool RenderingEngine::print_video_modes()
174 IrrlichtDevice *nulldevice;
176 bool vsync = g_settings->getBool("vsync");
177 u16 fsaa = g_settings->getU16("fsaa");
178 MyEventReceiver *receiver = new MyEventReceiver();
180 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
181 params.DriverType = video::EDT_NULL;
182 params.WindowSize = core::dimension2d<u32>(640, 480);
184 params.AntiAlias = fsaa;
185 params.Fullscreen = false;
186 params.Stencilbuffer = false;
187 params.Vsync = vsync;
188 params.EventReceiver = receiver;
189 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
191 nulldevice = createDeviceEx(params);
198 std::cout << _("Available video modes (WxHxD):") << std::endl;
200 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
202 if (videomode_list != NULL) {
203 s32 videomode_count = videomode_list->getVideoModeCount();
204 core::dimension2d<u32> videomode_res;
206 for (s32 i = 0; i < videomode_count; ++i) {
207 videomode_res = videomode_list->getVideoModeResolution(i);
208 videomode_depth = videomode_list->getVideoModeDepth(i);
209 std::cout << videomode_res.Width << "x" << videomode_res.Height
210 << "x" << videomode_depth << std::endl;
213 std::cout << _("Active video mode (WxHxD):") << std::endl;
214 videomode_res = videomode_list->getDesktopResolution();
215 videomode_depth = videomode_list->getDesktopDepth();
216 std::cout << videomode_res.Width << "x" << videomode_res.Height << "x"
217 << videomode_depth << std::endl;
223 return videomode_list != NULL;
226 bool RenderingEngine::setupTopLevelWindow(const std::string &name)
228 // FIXME: It would make more sense for there to be a switch of some
229 // sort here that would call the correct toplevel setup methods for
230 // the environment Minetest is running in.
232 /* Setting Xorg properties for the top level window */
233 setupTopLevelXorgWindow(name);
235 /* Setting general properties for the top level window */
236 verbosestream << "Client: Configuring general top level"
237 << " window properties"
239 bool result = setWindowIcon();
244 void RenderingEngine::setupTopLevelXorgWindow(const std::string &name)
247 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
249 Display *x11_dpl = reinterpret_cast<Display *>(exposedData.OpenGLLinux.X11Display);
250 if (x11_dpl == NULL) {
251 warningstream << "Client: Could not find X11 Display in ExposedVideoData"
256 verbosestream << "Client: Configuring X11-specific top level"
257 << " window properties"
261 Window x11_win = reinterpret_cast<Window>(exposedData.OpenGLLinux.X11Window);
263 // Set application name and class hints. For now name and class are the same.
264 XClassHint *classhint = XAllocClassHint();
265 classhint->res_name = const_cast<char *>(name.c_str());
266 classhint->res_class = const_cast<char *>(name.c_str());
268 XSetClassHint(x11_dpl, x11_win, classhint);
271 // FIXME: In the future WMNormalHints should be set ... e.g see the
272 // gtk/gdk code (gdk/x11/gdksurface-x11.c) for the setup_top_level
273 // method. But for now (as it would require some significant changes)
274 // leave the code as is.
276 // The following is borrowed from the above gdk source for setting top
277 // level windows. The source indicates and the Xlib docs suggest that
278 // this will set the WM_CLIENT_MACHINE and WM_LOCAL_NAME. This will not
279 // set the WM_CLIENT_MACHINE to a Fully Qualified Domain Name (FQDN) which is
280 // required by the Extended Window Manager Hints (EWMH) spec when setting
281 // the _NET_WM_PID (see further down) but running Minetest in an env
282 // where the window manager is on another machine from Minetest (therefore
283 // making the PID useless) is not expected to be a problem. Further
284 // more, using gtk/gdk as the model it would seem that not using a FQDN is
285 // not an issue for modern Xorg window managers.
287 verbosestream << "Client: Setting Xorg window manager Properties"
290 XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL);
292 // Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID
293 // (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to
294 // force a shutdown of an application if it doesn't respond to the destroy
297 verbosestream << "Client: Setting Xorg _NET_WM_PID extened window manager property"
300 Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false);
302 pid_t pid = getpid();
304 XChangeProperty(x11_dpl, x11_win, NET_WM_PID,
305 XA_CARDINAL, 32, PropModeReplace,
306 reinterpret_cast<unsigned char *>(&pid),1);
308 // Set the WM_CLIENT_LEADER window property here. Minetest has only one
309 // window and that window will always be the leader.
311 verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property"
314 Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false);
316 XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER,
317 XA_WINDOW, 32, PropModeReplace,
318 reinterpret_cast<unsigned char *>(&x11_win), 1);
323 static bool getWindowHandle(irr::video::IVideoDriver *driver, HWND &hWnd)
325 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
327 switch (driver->getDriverType()) {
328 case video::EDT_DIRECT3D8:
329 hWnd = reinterpret_cast<HWND>(exposedData.D3D8.HWnd);
331 case video::EDT_DIRECT3D9:
332 hWnd = reinterpret_cast<HWND>(exposedData.D3D9.HWnd);
334 case video::EDT_OPENGL:
335 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
345 bool RenderingEngine::setWindowIcon()
347 #if defined(XORG_USED)
349 return setXorgWindowIconFromPath(
350 porting::path_share + "/misc/dragonfire-xorg-icon-128.png");
352 // We have semi-support for reading in-place data if we are
353 // compiled with RUN_IN_PLACE. Don't break with this and
354 // also try the path_share location.
355 return setXorgWindowIconFromPath(
356 ICON_DIR "/hicolor/128x128/apps/dragonfire.png") ||
357 setXorgWindowIconFromPath(porting::path_share + "/misc/dragonfire-xorg-icon-128.png");
359 #elif defined(_WIN32)
360 HWND hWnd; // Window handle
361 if (!getWindowHandle(driver, hWnd))
364 // Load the ICON from resource file
365 const HICON hicon = LoadIcon(GetModuleHandle(NULL),
366 MAKEINTRESOURCE(130) // The ID of the ICON defined in
371 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
372 SendMessage(hWnd, WM_SETICON, ICON_SMALL,
373 reinterpret_cast<LPARAM>(hicon));
382 bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file)
386 video::IImageLoader *image_loader = NULL;
387 u32 cnt = driver->getImageLoaderCount();
388 for (u32 i = 0; i < cnt; i++) {
389 if (driver->getImageLoader(i)->isALoadableFileExtension(
390 icon_file.c_str())) {
391 image_loader = driver->getImageLoader(i);
397 warningstream << "Could not find image loader for file '" << icon_file
402 io::IReadFile *icon_f =
403 m_device->getFileSystem()->createAndOpenFile(icon_file.c_str());
406 warningstream << "Could not load icon file '" << icon_file << "'"
411 video::IImage *img = image_loader->loadImage(icon_f);
414 warningstream << "Could not load icon file '" << icon_file << "'"
420 u32 height = img->getDimension().Height;
421 u32 width = img->getDimension().Width;
423 size_t icon_buffer_len = 2 + height * width;
424 long *icon_buffer = new long[icon_buffer_len];
426 icon_buffer[0] = width;
427 icon_buffer[1] = height;
429 for (u32 x = 0; x < width; x++) {
430 for (u32 y = 0; y < height; y++) {
431 video::SColor col = img->getPixel(x, y);
433 pixel_val |= (u8)col.getAlpha() << 24;
434 pixel_val |= (u8)col.getRed() << 16;
435 pixel_val |= (u8)col.getGreen() << 8;
436 pixel_val |= (u8)col.getBlue();
437 icon_buffer[2 + x + y * width] = pixel_val;
444 const video::SExposedVideoData &video_data = driver->getExposedVideoData();
446 Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
448 if (x11_dpl == NULL) {
449 warningstream << "Could not find x11 display for setting its icon."
451 delete[] icon_buffer;
455 Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
457 Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
458 Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
459 XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace,
460 (const unsigned char *)icon_buffer, icon_buffer_len);
462 delete[] icon_buffer;
469 Draws a screen with a single text on it.
470 Text will be removed when the screen is drawn the next time.
471 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
473 void RenderingEngine::_draw_load_screen(const std::wstring &text,
474 gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime,
475 int percent, bool clouds)
477 v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();
479 v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight());
480 v2s32 center(screensize.X / 2, screensize.Y / 2);
481 core::rect<s32> textrect(center - textsize / 2, center + textsize / 2);
483 gui::IGUIStaticText *guitext =
484 guienv->addStaticText(text.c_str(), textrect, false, false);
485 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
487 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
488 if (cloud_menu_background) {
489 g_menuclouds->step(dtime * 3);
490 g_menuclouds->render();
491 get_video_driver()->beginScene(
492 true, true, video::SColor(255, 140, 186, 250));
493 g_menucloudsmgr->drawAll();
495 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
498 if ((percent >= 0) && (percent <= 100)) {
499 video::ITexture *progress_img = tsrc->getTexture("progress_bar.png");
500 video::ITexture *progress_img_bg =
501 tsrc->getTexture("progress_bar_bg.png");
503 if (progress_img && progress_img_bg) {
505 const core::dimension2d<u32> &img_size =
506 progress_img_bg->getSize();
507 u32 imgW = rangelim(img_size.Width, 200, 600);
508 u32 imgH = rangelim(img_size.Height, 24, 72);
510 const core::dimension2d<u32> img_size(256, 48);
511 float imgRatio = (float)img_size.Height / img_size.Width;
512 u32 imgW = screensize.X / 2.2f;
513 u32 imgH = floor(imgW * imgRatio);
515 v2s32 img_pos((screensize.X - imgW) / 2,
516 (screensize.Y - imgH) / 2);
518 draw2DImageFilterScaled(get_video_driver(), progress_img_bg,
519 core::rect<s32>(img_pos.X, img_pos.Y,
522 core::rect<s32>(0, 0, img_size.Width,
526 draw2DImageFilterScaled(get_video_driver(), progress_img,
527 core::rect<s32>(img_pos.X, img_pos.Y,
528 img_pos.X + (percent * imgW) / 100,
530 core::rect<s32>(0, 0,
531 (percent * img_size.Width) / 100,
538 get_video_driver()->endScene();
543 Draws the menu scene including (optional) cloud background.
545 void RenderingEngine::_draw_menu_scene(gui::IGUIEnvironment *guienv,
546 float dtime, bool clouds)
548 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
549 if (cloud_menu_background) {
550 g_menuclouds->step(dtime * 3);
551 g_menuclouds->render();
552 get_video_driver()->beginScene(
553 true, true, video::SColor(255, 140, 186, 250));
554 g_menucloudsmgr->drawAll();
556 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
559 get_video_driver()->endScene();
562 std::vector<core::vector3d<u32>> RenderingEngine::getSupportedVideoModes()
564 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
565 sanity_check(nulldevice);
567 std::vector<core::vector3d<u32>> mlist;
568 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
570 s32 num_modes = modelist->getVideoModeCount();
571 for (s32 i = 0; i != num_modes; i++) {
572 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
573 u32 mode_depth = (u32)modelist->getVideoModeDepth(i);
574 mlist.emplace_back(mode_res.Width, mode_res.Height, mode_depth);
581 std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers()
583 std::vector<irr::video::E_DRIVER_TYPE> drivers;
585 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
586 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
587 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
593 void RenderingEngine::_initialize(Client *client, Hud *hud)
595 const std::string &draw_mode = g_settings->get("3d_mode");
596 core.reset(createRenderingCore(draw_mode, m_device, client, hud));
600 void RenderingEngine::_finalize()
605 void RenderingEngine::_draw_scene(video::SColor skycolor, bool show_hud,
606 bool show_minimap, bool draw_wield_tool, bool draw_crosshair)
608 core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair);
611 const char *RenderingEngine::getVideoDriverName(irr::video::E_DRIVER_TYPE type)
613 static const char *driver_ids[] = {
624 return driver_ids[type];
627 const char *RenderingEngine::getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
629 static const char *driver_names[] = {
640 return driver_names[type];
644 #if defined(XORG_USED)
646 static float calcDisplayDensity()
648 const char *current_display = getenv("DISPLAY");
650 if (current_display != NULL) {
651 Display *x11display = XOpenDisplay(current_display);
653 if (x11display != NULL) {
655 int dh = DisplayHeight(x11display, 0);
656 int dw = DisplayWidth(x11display, 0);
657 int dh_mm = DisplayHeightMM(x11display, 0);
658 int dw_mm = DisplayWidthMM(x11display, 0);
659 XCloseDisplay(x11display);
661 if (dh_mm != 0 && dw_mm != 0) {
662 float dpi_height = floor(dh / (dh_mm * 0.039370) + 0.5);
663 float dpi_width = floor(dw / (dw_mm * 0.039370) + 0.5);
664 return std::max(dpi_height, dpi_width) / 96.0;
669 /* return manually specified dpi */
670 return g_settings->getFloat("screen_dpi") / 96.0;
673 float RenderingEngine::getDisplayDensity()
675 static float cached_display_density = calcDisplayDensity();
676 return cached_display_density;
679 #elif defined(_WIN32)
682 static float calcDisplayDensity(irr::video::IVideoDriver *driver)
685 if (getWindowHandle(driver, hWnd)) {
686 HDC hdc = GetDC(hWnd);
687 float dpi = GetDeviceCaps(hdc, LOGPIXELSX);
688 ReleaseDC(hWnd, hdc);
692 /* return manually specified dpi */
693 return g_settings->getFloat("screen_dpi") / 96.0f;
696 float RenderingEngine::getDisplayDensity()
698 static bool cached = false;
699 static float display_density;
701 display_density = calcDisplayDensity(get_video_driver());
704 return display_density;
709 float RenderingEngine::getDisplayDensity()
711 return g_settings->getFloat("screen_dpi") / 96.0;
716 v2u32 RenderingEngine::getDisplaySize()
718 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
720 core::dimension2d<u32> deskres =
721 nulldevice->getVideoModeList()->getDesktopResolution();
728 float RenderingEngine::getDisplayDensity()
730 return porting::getDisplayDensity();
733 v2u32 RenderingEngine::getDisplaySize()
735 return porting::getDisplaySize();
737 #endif // __ANDROID__