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;
61 static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment,
62 gui::EGUI_SKIN_TYPE type, video::IVideoDriver *driver)
64 gui::GUISkin *skin = new gui::GUISkin(type, driver);
66 gui::IGUIFont *builtinfont = environment->getBuiltInFont();
67 gui::IGUIFontBitmap *bitfont = nullptr;
68 if (builtinfont && builtinfont->getType() == gui::EGFT_BITMAP)
69 bitfont = (gui::IGUIFontBitmap*)builtinfont;
71 gui::IGUISpriteBank *bank = 0;
72 skin->setFont(builtinfont);
75 bank = bitfont->getSpriteBank();
77 skin->setSpriteBank(bank);
83 RenderingEngine::RenderingEngine(IEventReceiver *receiver)
85 sanity_check(!s_singleton);
87 // Resolution selection
88 bool fullscreen = g_settings->getBool("fullscreen");
89 u16 screen_w = g_settings->getU16("screen_w");
90 u16 screen_h = g_settings->getU16("screen_h");
93 bool vsync = g_settings->getBool("vsync");
94 u16 fsaa = g_settings->getU16("fsaa");
96 // stereo buffer required for pageflip stereo
97 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
100 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
101 const std::string &driverstring = g_settings->get("video_driver");
102 std::vector<video::E_DRIVER_TYPE> drivers =
103 RenderingEngine::getSupportedVideoDrivers();
105 for (i = 0; i != drivers.size(); i++) {
106 if (!strcasecmp(driverstring.c_str(),
107 RenderingEngine::getVideoDriverInfo(drivers[i]).name.c_str())) {
108 driverType = drivers[i];
112 if (i == drivers.size()) {
113 errorstream << "Invalid video_driver specified; "
114 "defaulting to opengl"
118 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
120 params.LoggingLevel = irr::ELL_DEBUG;
121 params.DriverType = driverType;
122 params.WindowSize = core::dimension2d<u32>(screen_w, screen_h);
123 params.AntiAlias = fsaa;
124 params.Fullscreen = fullscreen;
125 params.Stencilbuffer = false;
126 params.Stereobuffer = stereo_buffer;
127 params.Vsync = vsync;
128 params.EventReceiver = receiver;
129 params.HighPrecisionFPU = true;
131 params.PrivateData = porting::app_global;
134 // there is no standardized path for these on desktop
135 std::string rel_path = std::string("client") + DIR_DELIM
136 + "shaders" + DIR_DELIM + "Irrlicht";
137 params.OGLES2ShaderPath = (porting::path_share + DIR_DELIM + rel_path + DIR_DELIM).c_str();
140 m_device = createDeviceEx(params);
141 driver = m_device->getVideoDriver();
145 auto skin = createSkin(m_device->getGUIEnvironment(),
146 gui::EGST_WINDOWS_METALLIC, driver);
147 m_device->getGUIEnvironment()->setSkin(skin);
151 RenderingEngine::~RenderingEngine()
154 m_device->closeDevice();
155 s_singleton = nullptr;
158 v2u32 RenderingEngine::_getWindowSize() const
161 return core->getVirtualSize();
162 return m_device->getVideoDriver()->getScreenSize();
165 void RenderingEngine::setResizable(bool resize)
167 m_device->setResizable(resize);
170 void RenderingEngine::removeMesh(const scene::IMesh* mesh)
172 m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
175 void RenderingEngine::cleanupMeshCache()
177 auto mesh_cache = m_device->getSceneManager()->getMeshCache();
178 while (mesh_cache->getMeshCount() != 0) {
179 if (scene::IAnimatedMesh *mesh = mesh_cache->getMeshByIndex(0))
180 mesh_cache->removeMesh(mesh);
184 bool RenderingEngine::setupTopLevelWindow(const std::string &name)
186 // FIXME: It would make more sense for there to be a switch of some
187 // sort here that would call the correct toplevel setup methods for
188 // the environment Minetest is running in.
190 /* Setting Xorg properties for the top level window */
191 setupTopLevelXorgWindow(name);
193 /* Setting general properties for the top level window */
194 verbosestream << "Client: Configuring general top level"
195 << " window properties"
197 bool result = setWindowIcon();
202 void RenderingEngine::setupTopLevelXorgWindow(const std::string &name)
205 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
207 Display *x11_dpl = reinterpret_cast<Display *>(exposedData.OpenGLLinux.X11Display);
208 if (x11_dpl == NULL) {
209 warningstream << "Client: Could not find X11 Display in ExposedVideoData"
214 verbosestream << "Client: Configuring X11-specific top level"
215 << " window properties"
219 Window x11_win = reinterpret_cast<Window>(exposedData.OpenGLLinux.X11Window);
221 // Set application name and class hints. For now name and class are the same.
222 XClassHint *classhint = XAllocClassHint();
223 classhint->res_name = const_cast<char *>(name.c_str());
224 classhint->res_class = const_cast<char *>(name.c_str());
226 XSetClassHint(x11_dpl, x11_win, classhint);
229 // FIXME: In the future WMNormalHints should be set ... e.g see the
230 // gtk/gdk code (gdk/x11/gdksurface-x11.c) for the setup_top_level
231 // method. But for now (as it would require some significant changes)
232 // leave the code as is.
234 // The following is borrowed from the above gdk source for setting top
235 // level windows. The source indicates and the Xlib docs suggest that
236 // this will set the WM_CLIENT_MACHINE and WM_LOCAL_NAME. This will not
237 // set the WM_CLIENT_MACHINE to a Fully Qualified Domain Name (FQDN) which is
238 // required by the Extended Window Manager Hints (EWMH) spec when setting
239 // the _NET_WM_PID (see further down) but running Minetest in an env
240 // where the window manager is on another machine from Minetest (therefore
241 // making the PID useless) is not expected to be a problem. Further
242 // more, using gtk/gdk as the model it would seem that not using a FQDN is
243 // not an issue for modern Xorg window managers.
245 verbosestream << "Client: Setting Xorg window manager Properties"
248 XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL);
250 // Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID
251 // (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to
252 // force a shutdown of an application if it doesn't respond to the destroy
255 verbosestream << "Client: Setting Xorg _NET_WM_PID extended window manager property"
258 Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false);
260 pid_t pid = getpid();
262 XChangeProperty(x11_dpl, x11_win, NET_WM_PID,
263 XA_CARDINAL, 32, PropModeReplace,
264 reinterpret_cast<unsigned char *>(&pid),1);
266 // Set the WM_CLIENT_LEADER window property here. Minetest has only one
267 // window and that window will always be the leader.
269 verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property"
272 Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false);
274 XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER,
275 XA_WINDOW, 32, PropModeReplace,
276 reinterpret_cast<unsigned char *>(&x11_win), 1);
281 static bool getWindowHandle(irr::video::IVideoDriver *driver, HWND &hWnd)
283 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
285 switch (driver->getDriverType()) {
287 case video::EDT_OGLES1:
288 case video::EDT_OGLES2:
290 case video::EDT_OPENGL:
291 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
301 bool RenderingEngine::setWindowIcon()
303 #if defined(XORG_USED)
305 return setXorgWindowIconFromPath(
306 porting::path_share + "/misc/dragonfire-xorg-icon-128.png");
308 // We have semi-support for reading in-place data if we are
309 // compiled with RUN_IN_PLACE. Don't break with this and
310 // also try the path_share location.
311 return setXorgWindowIconFromPath(
312 ICON_DIR "/hicolor/128x128/apps/dragonfire.png") ||
313 setXorgWindowIconFromPath(porting::path_share + "/misc/dragonfire-xorg-icon-128.png");
315 #elif defined(_WIN32)
316 HWND hWnd; // Window handle
317 if (!getWindowHandle(driver, hWnd))
320 // Load the ICON from resource file
321 const HICON hicon = LoadIcon(GetModuleHandle(NULL),
322 MAKEINTRESOURCE(130) // The ID of the ICON defined in
327 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
328 SendMessage(hWnd, WM_SETICON, ICON_SMALL,
329 reinterpret_cast<LPARAM>(hicon));
338 bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file)
342 video::IImageLoader *image_loader = NULL;
343 u32 cnt = driver->getImageLoaderCount();
344 for (u32 i = 0; i < cnt; i++) {
345 if (driver->getImageLoader(i)->isALoadableFileExtension(
346 icon_file.c_str())) {
347 image_loader = driver->getImageLoader(i);
353 warningstream << "Could not find image loader for file '" << icon_file
358 io::IReadFile *icon_f =
359 m_device->getFileSystem()->createAndOpenFile(icon_file.c_str());
362 warningstream << "Could not load icon file '" << icon_file << "'"
367 video::IImage *img = image_loader->loadImage(icon_f);
370 warningstream << "Could not load icon file '" << icon_file << "'"
376 u32 height = img->getDimension().Height;
377 u32 width = img->getDimension().Width;
379 size_t icon_buffer_len = 2 + height * width;
380 long *icon_buffer = new long[icon_buffer_len];
382 icon_buffer[0] = width;
383 icon_buffer[1] = height;
385 for (u32 x = 0; x < width; x++) {
386 for (u32 y = 0; y < height; y++) {
387 video::SColor col = img->getPixel(x, y);
389 pixel_val |= (u8)col.getAlpha() << 24;
390 pixel_val |= (u8)col.getRed() << 16;
391 pixel_val |= (u8)col.getGreen() << 8;
392 pixel_val |= (u8)col.getBlue();
393 icon_buffer[2 + x + y * width] = pixel_val;
400 const video::SExposedVideoData &video_data = driver->getExposedVideoData();
402 Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
404 if (x11_dpl == NULL) {
405 warningstream << "Could not find x11 display for setting its icon."
407 delete[] icon_buffer;
411 Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
413 Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
414 Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
415 XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace,
416 (const unsigned char *)icon_buffer, icon_buffer_len);
418 delete[] icon_buffer;
425 Draws a screen with a single text on it.
426 Text will be removed when the screen is drawn the next time.
427 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
429 void RenderingEngine::draw_load_screen(const std::wstring &text,
430 gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime,
431 int percent, bool clouds)
433 v2u32 screensize = getWindowSize();
435 v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight());
436 v2s32 center(screensize.X / 2, screensize.Y / 2);
437 core::rect<s32> textrect(center - textsize / 2, center + textsize / 2);
439 gui::IGUIStaticText *guitext =
440 guienv->addStaticText(text.c_str(), textrect, false, false);
441 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
443 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
444 if (cloud_menu_background) {
445 g_menuclouds->step(dtime * 3);
446 g_menuclouds->render();
447 get_video_driver()->beginScene(
448 true, true, video::SColor(255, 140, 186, 250));
449 g_menucloudsmgr->drawAll();
451 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
454 if ((percent >= 0) && (percent <= 100)) {
455 video::ITexture *progress_img = tsrc->getTexture("progress_bar.png");
456 video::ITexture *progress_img_bg =
457 tsrc->getTexture("progress_bar_bg.png");
459 if (progress_img && progress_img_bg) {
461 const core::dimension2d<u32> &img_size =
462 progress_img_bg->getSize();
463 u32 imgW = rangelim(img_size.Width, 200, 600);
464 u32 imgH = rangelim(img_size.Height, 24, 72);
466 const core::dimension2d<u32> img_size(256, 48);
467 float imgRatio = (float)img_size.Height / img_size.Width;
468 u32 imgW = screensize.X / 2.2f;
469 u32 imgH = floor(imgW * imgRatio);
471 v2s32 img_pos((screensize.X - imgW) / 2,
472 (screensize.Y - imgH) / 2);
474 draw2DImageFilterScaled(get_video_driver(), progress_img_bg,
475 core::rect<s32>(img_pos.X, img_pos.Y,
478 core::rect<s32>(0, 0, img_size.Width,
482 draw2DImageFilterScaled(get_video_driver(), progress_img,
483 core::rect<s32>(img_pos.X, img_pos.Y,
484 img_pos.X + (percent * imgW) / 100,
486 core::rect<s32>(0, 0,
487 (percent * img_size.Width) / 100,
494 get_video_driver()->endScene();
499 Draws the menu scene including (optional) cloud background.
501 void RenderingEngine::draw_menu_scene(gui::IGUIEnvironment *guienv,
502 float dtime, bool clouds)
504 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
505 if (cloud_menu_background) {
506 g_menuclouds->step(dtime * 3);
507 g_menuclouds->render();
508 get_video_driver()->beginScene(
509 true, true, video::SColor(255, 140, 186, 250));
510 g_menucloudsmgr->drawAll();
512 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
515 get_video_driver()->endScene();
518 std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers()
520 // Only check these drivers.
521 // We do not support software and D3D in any capacity.
522 static const irr::video::E_DRIVER_TYPE glDrivers[4] = {
523 irr::video::EDT_NULL,
524 irr::video::EDT_OPENGL,
525 irr::video::EDT_OGLES1,
526 irr::video::EDT_OGLES2,
528 std::vector<irr::video::E_DRIVER_TYPE> drivers;
530 for (int i = 0; i < 4; i++) {
531 if (irr::IrrlichtDevice::isDriverSupported(glDrivers[i]))
532 drivers.push_back(glDrivers[i]);
538 void RenderingEngine::initialize(Client *client, Hud *hud)
540 const std::string &draw_mode = g_settings->get("3d_mode");
541 core.reset(createRenderingCore(draw_mode, m_device, client, hud));
545 void RenderingEngine::finalize()
550 void RenderingEngine::draw_scene(video::SColor skycolor, bool show_hud,
551 bool show_minimap, bool draw_wield_tool, bool draw_crosshair)
553 core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair);
556 const VideoDriverInfo &RenderingEngine::getVideoDriverInfo(irr::video::E_DRIVER_TYPE type)
558 static const std::unordered_map<int, VideoDriverInfo> driver_info_map = {
559 {(int)video::EDT_NULL, {"null", "NULL Driver"}},
560 {(int)video::EDT_OPENGL, {"opengl", "OpenGL"}},
561 {(int)video::EDT_OGLES1, {"ogles1", "OpenGL ES1"}},
562 {(int)video::EDT_OGLES2, {"ogles2", "OpenGL ES2"}},
564 return driver_info_map.at((int)type);
568 #if defined(XORG_USED)
570 static float calcDisplayDensity()
572 const char *current_display = getenv("DISPLAY");
574 if (current_display != NULL) {
575 Display *x11display = XOpenDisplay(current_display);
577 if (x11display != NULL) {
579 int dh = DisplayHeight(x11display, 0);
580 int dw = DisplayWidth(x11display, 0);
581 int dh_mm = DisplayHeightMM(x11display, 0);
582 int dw_mm = DisplayWidthMM(x11display, 0);
583 XCloseDisplay(x11display);
585 if (dh_mm != 0 && dw_mm != 0) {
586 float dpi_height = floor(dh / (dh_mm * 0.039370) + 0.5);
587 float dpi_width = floor(dw / (dw_mm * 0.039370) + 0.5);
588 return std::max(dpi_height, dpi_width) / 96.0;
593 /* return manually specified dpi */
594 return g_settings->getFloat("screen_dpi") / 96.0;
597 float RenderingEngine::getDisplayDensity()
599 static float cached_display_density = calcDisplayDensity();
600 return cached_display_density * g_settings->getFloat("display_density_factor");
603 #elif defined(_WIN32)
606 static float calcDisplayDensity(irr::video::IVideoDriver *driver)
609 if (getWindowHandle(driver, hWnd)) {
610 HDC hdc = GetDC(hWnd);
611 float dpi = GetDeviceCaps(hdc, LOGPIXELSX);
612 ReleaseDC(hWnd, hdc);
616 /* return manually specified dpi */
617 return g_settings->getFloat("screen_dpi") / 96.0f;
620 float RenderingEngine::getDisplayDensity()
622 static bool cached = false;
623 static float display_density;
625 display_density = calcDisplayDensity(get_video_driver());
628 return display_density * g_settings->getFloat("display_density_factor");
633 float RenderingEngine::getDisplayDensity()
635 return (g_settings->getFloat("screen_dpi") / 96.0) * g_settings->getFloat("display_density_factor");
640 v2u32 RenderingEngine::getDisplaySize()
642 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
644 core::dimension2d<u32> deskres =
645 nulldevice->getVideoModeList()->getDesktopResolution();
652 float RenderingEngine::getDisplayDensity()
654 return porting::getDisplayDensity();
657 v2u32 RenderingEngine::getDisplaySize()
659 return porting::getDisplaySize();
661 #endif // __ANDROID__